#!/usr/bin/env python3 """Our numbers on factchecked.science/may-2024-auroral-expansion/ ("Our analysis"): how far equatorward DMSP saw electrons and fast ion flow in May 2024, what published fits give for the same times, and the same measure on earlier great storms. Usage: python3 -I auroral_edges.py [DATA_FOLDER] It needs Python 3.10 or later with numpy and netCDF4. It downloads what it lacks into DATA_FOLDER (default: a folder auroral_data beside this script), about 250 MB, reads everything as data, and writes six files beside this script: auroral-numbers.json, auroral-main-phase.csv, auroral-crossings.csv, auroral-other-storms.csv, auroral-raw-counts.txt and auroral-raw-counts-1989.txt. WHAT THIS IS, AND IS NOT. Every definition below is OURS. We could read only the public view of Wang et al. (2026, JGR Space Physics, doi:10.1029/2026JA035972), so nothing here says how that paper defines an edge, which passes it took or what it found. This tests where electrons were, not why they were there. WHY THE RULES LOOK AS THEY DO. They were not blind. RULES_dmsp_before_running.txt, hosted beside this script, was written first. The first run under it failed, and amendments 1 to 4 say what changed, why, and what had been seen by then. Amendments 5 to 7 follow a fresh review of the page. rules_sha256.txt logs the hashes. In short: - SSJ5 text files from NOAA NCEI: 40 values a second, electron channels 1-20 (channel 11 is a status word), then ions. - Electron counts are averaged over 11 s; background per second = 25th percentile across the 19 channels + 2 sqrt(max(b,1)/11). - AFRL's formula and pre-flight geometric factors: JE = sum C_i/(G_i dt) E_i dE_i, dt 0.05 s (SSJ5) or 0.098 s (SSJ4). Our flux runs about 1.27 times NASA's product for F18 in December 2014 (calibration, in the JSON). - Quantity: JE at or above 1 keV, in eV/cm2/s/sr. Masked: flat counts (10th percentile >= 10 and 90th/10th < 2.5), and the South Atlantic box (geodetic latitude -60 to 0, longitude 270-360 or 0-40 E). The mask also hides some real aurora. - Edge at threshold X: walking from the equator side, the lowest |CGM| with JE >= X and at least half of the seconds in the next 2 deg poleward also >= X. So "edge" here means the edge at 1 keV and above. The files stop near |CGM| 40; an edge within 1 deg of a crossing's lowest latitude is a limit. - Softer electrons (amendment 5, after the review, not blind): flat level F = median of the 11-s means of channels 1-4 (9.45 keV and above); excess in channels 5-16 (6.46 keV to 139 eV) over F + 2 sqrt(max(F,0.5)/11); AFRL's formula; the same walk at 1e9, 3e9 and 1e10, South Atlantic box masked. Whether electrons at about 0.005 erg/cm2/s count as "the oval" is a matter of definition. - Thresholds: 1e10 is the lowest the quiet-time control allows (F18 fails below it); 3e10 is the working rung, because at 1e10 four crossings reach the file's floor where the raw counts look like noise; 4e10 is about SSUSI's 0.2 erg/cm2/s and 2e11 about 1 erg/cm2/s, each converted with pi sr. 2e9 and 6e9 are kept in the crossings table and do not count. - Main phase: 17:05 UT 10 May to 02:14 UT 11 May 2024, SYM-H's low (amendment 6, after the data were seen; it was 02:00 UT before). Sector: MLT 00-06 at the edge. Quiet control: before 17:05 UT. - Fast flow: |vy| from SSIES, 11-s median, same walk at 300, 500 and 1000 m/s. Speed only. It cannot show cause. - Published fits (RULES_dmsp_before_running.txt): Gussenhoven et al. 1983 and Troyer et al. 2025 with coefficients as transcribed in the ocbpy code, unchecked against the papers; Yokoyama et al. 1998 read from the paper. - Earlier storms (RULES_other_storms.txt): March 1989 by this same pipeline from NOAA's binary files; 2003 from NASA's background-subtracted product. Coarse: different sensors, backgrounds and local times. - SuperDARN deposit: all-sector reach only. The file's columns don't name MLT, and our test of its orientation was inconclusive. The lowest latitudes reached are close to the deposit's coverage floor. CREDIT AND TERMS. SSJ: NOAA NCEI and AFRL (format and factors: AFRL ASCII and Binary File Format Descriptions). SSUSI: NASA SPDF and JHU/APL. SSIES: University of Texas at Dallas, through NASA CDAWeb. NASA's SSJ product: AFRL, NCEI and CU through CDAWeb. Kp and Hp30: GFZ Potsdam, CC BY 4.0, doi:10.5880/Kp.0001 and doi:10.5880/Hpo.0003. Dst and SYM-H: World Data Center for Geomagnetism, Kyoto, and the observatories that supply it, doi:10.17593/14515-74000 and doi:10.14989/267216, for scientific use and no commercial use, a condition that carries over to this script's outputs. SuperDARN CSV: T. Wang (2026), doi:10.5281/zenodo.20321232, CC BY 4.0. Fit coefficients as transcribed in ocbpy (Burrell et al., doi:10.5281/zenodo.1179230, BSD 3-clause licence). Nothing here is taken from the paper's figures or text. """ import csv import datetime as dt import gzip import io import json import math import os import re import struct import sys import time import urllib.error import urllib.request import warnings import zipfile import netCDF4 as nc import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) UA = "factchecked-research/1.0" NCEI = "https://www.ncei.noaa.gov/data/dmsp-space-weather-sensors/access" SPDF = "https://spdf.gsfc.nasa.gov/pub/data/dmsp" HAPI = "https://cdaweb.gsfc.nasa.gov/hapi" KYOTO = "https://wdc.kugi.kyoto-u.ac.jp/hapi/data" GFZ = "https://kp.gfz-potsdam.de/app/json/" ZENODO_ZIP = "https://zenodo.org/api/records/20321232/files/SuperDARN-csv.zip/content" EPOCH = dt.datetime(2024, 5, 1) EPOCH_OLD = dt.datetime(1980, 1, 1) SC = (dt.datetime(2024, 5, 10, 17, 5) - EPOCH).total_seconds() WINDOW_END = (dt.datetime(2024, 5, 11, 2, 14) - EPOCH).total_seconds() # SYM-H's low; amendment 6 CH_E = np.array([30000, 20400, 13900, 9450, 6460, 4400, 3000, 2040, 1392, 949, 949, 646, 440, 300, 204, 139, 95, 65, 44, 30], float) CH_DE = np.array([9600, 8050, 5475, 3720, 2525, 1730, 1180, 804, 545.5, 373, 373, 254.5, 173, 118, 80.5, 54.5, 37, 25.5, 17.5, 14], float) # AFRL Tables 23 and 25: electron geometric factors (cm2 eV sr), channels 1-20. On SSJ5, channel 11 is a status word. G = { "F16": [1.781, 1.477, 1.188, 0.935, 0.722, 0.551, 0.416, 0.306, 0.225, 0.166, np.nan, 0.123, 0.0876, 0.0613, 0.0429, 0.0289, 0.0182, 0.0113, 0.00621, 0.00307], "F17": [1.044, 0.808, 0.602, 0.458, 0.349, 0.262, 0.191, 0.142, 0.103, 0.0727, np.nan, 0.0541, 0.0394, 0.0276, 0.0188, 0.0134, 0.00901, 0.00645, 0.00445, 0.00294], "F18": [0.725, 0.534, 0.412, 0.315, 0.266, 0.199, 0.147, 0.107, 0.0803, 0.0562, np.nan, 0.041, 0.0296, 0.0203, 0.014, 0.0104, 0.00708, 0.00562, 0.00386, 0.00239], } G_J4 = { "F08": [0.326, 0.275, 0.23, 0.185, 0.152, 0.118, 0.0899, 0.073, 0.0539, 0.0427, 0.03163, 0.02402, 0.01917, 0.01245, 0.008737, 0.005564, 0.003261, 0.001917, 0.001057, 0.0005465], "F09": [0.201, 0.17, 0.142, 0.115, 0.0937, 0.0729, 0.0555, 0.0451, 0.0333, 0.0264, 0.03688, 0.02797, 0.02234, 0.01455, 0.01014, 0.006467, 0.003801, 0.002234, 0.001229, 0.0006363], } DT_J5, DT_J4 = 0.05, 0.098 LADDER = {"2e9": 2e9, "6e9": 6e9, "1e10": 1e10, "3e10": 3e10, "4e10": 4e10, "6e10": 6e10, "1e11": 1e11, "2e11": 2e11} SOFT_LADDER = {"1e9": 1e9, "3e9": 3e9, "1e10": 1e10} SOFT_TOP = [0, 1, 2, 3] # channels 1-4, 9.45 keV and above: the flat level SOFT_J5 = [i for i in range(4, 16) if i != 10] # channels 5-16, 6.46 keV to 139 eV, without SSJ5's status word SOFT_J4 = list(range(4, 16)) # on SSJ4 channel 11 is a real channel OLD_LADDER = {"1e10": 1e10, "3e10": 3e10, "4e10": 4e10, "2e11": 2e11} # AFRL Table 19: channel order in a one-second group of the binary files ORDER = [4, 3, 2, 1, 8, 7, 6, 5, 12, 11, 10, 9, 16, 15, 14, 13, 20, 19, 18, 17] E19 = np.array([30000, 20400, 13900, 9450, 6460, 4400, 3000, 2040, 1392, 949, 646, 440, 300, 204, 139, 95, 65, 44, 30], float) DE19 = np.array([9600, 8050, 5475, 3720, 2525, 1730, 1180, 804, 545.5, 373, 254.5, 173, 118, 80.5, 54.5, 37, 25.5, 17.5, 14], float) GUSS_L0 = {0: 66.1, 1: 65.1, 4: 67.7, 5: 67.8, 6: 68.2, 7: 68.9, 8: 69.3, 9: 69.5, 10: 69.6, 11: 70.1, 12: 69.4, 15: 70.9, 16: 71.6, 17: 71.1, 18: 71.2, 19: 70.4, 20: 69.4, 21: 68.6, 22: 67.9, 23: 67.8} GUSS_A = {0: -1.99, 1: -1.55, 4: -1.48, 5: -1.87, 6: -1.90, 7: -1.91, 8: -1.87, 9: -1.67, 10: -1.41, 11: -1.25, 12: -0.84, 15: -0.81, 16: -1.28, 17: -1.31, 18: -1.74, 19: -1.83, 20: -1.89, 21: -1.86, 22: -1.78, 23: -2.07} # Stretches printed to auroral-raw-counts.txt: satellite, start, stop DUMPS = [("F18", "2024-05-10T18:54:30", "2024-05-10T18:56:20"), ("F18", "2024-05-10T19:20:50", "2024-05-10T19:22:30"), ("F18", "2024-05-10T20:37:20", "2024-05-10T20:39:40"), ("F18", "2024-05-10T21:01:00", "2024-05-10T21:03:40"), ("F18", "2024-05-10T22:17:30", "2024-05-10T22:22:55"), ("F18", "2024-05-10T22:41:49", "2024-05-10T22:46:10"), ("F17", "2024-05-10T22:46:30", "2024-05-10T22:49:00"), ("F16", "2024-05-10T23:01:10", "2024-05-10T23:03:20"), ("F18", "2024-05-11T00:01:50", "2024-05-11T00:04:40"), ("F18", "2024-05-11T01:43:50", "2024-05-11T01:46:40"), ("F17", "2024-05-11T02:10:00", "2024-05-11T02:13:20"), ("F16", "2024-05-10T21:19:30", "2024-05-10T21:23:30"), ("F16", "2024-05-11T00:44:00", "2024-05-11T00:47:20"), ("F16", "2024-05-10T22:37:30", "2024-05-10T22:40:20"), ("F17", "2024-05-10T22:23:30", "2024-05-10T22:26:20")] DUMPS_1989 = [("F09", "1989-03-13T22:49:00", "1989-03-13T22:53:00"), ("F09", "1989-03-14T00:33:00", "1989-03-14T00:37:00"), ("F09", "1989-03-14T00:58:00", "1989-03-14T01:05:00")] # ---------------------------------------------------------------- downloads def fetch(url, path, optional=False): """Fetch url to path under a plain client name, unless the file is already there. A refusal stops the run, or returns False if optional.""" if os.path.exists(path) and os.path.getsize(path) > 0: return True os.makedirs(os.path.dirname(path), exist_ok=True) req = urllib.request.Request(url, headers={"User-Agent": UA}) for attempt in range(3): try: with urllib.request.urlopen(req, timeout=300) as r: data = r.read() with open(path + ".part", "wb") as f: f.write(data) os.replace(path + ".part", path) return True except urllib.error.HTTPError as e: if e.code in (403, 404, 429): if optional: print(" not available:", url, e.code, flush=True) return False sys.exit(f"Refused: {url} answered {e.code}. Not retried another way.") time.sleep(5 * (attempt + 1)) except (urllib.error.URLError, TimeoutError): time.sleep(5 * (attempt + 1)) if optional: return False sys.exit(f"Could not fetch {url}") def listing(url): req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=120) as r: return r.read().decode("utf-8", "replace") def get_inputs(folder): ssj = os.path.join(folder, "ssj_2024-05") t0, t1 = dt.datetime(2024, 5, 10, 9, 0), dt.datetime(2024, 5, 11, 3, 0) for sat in ("f16", "f17", "f18"): base = f"{NCEI}/{sat}/ssj/2024/05/" for name in re.findall(r'', listing(base)): m = re.search(r"DD\.(\d{8})_TP\.(\d{6})-(\d{6})_DF\.(SDR|EDR)$", name) if not m: continue start = dt.datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S") stop = dt.datetime.strptime(m.group(1) + m.group(3), "%Y%m%d%H%M%S") if stop < start: stop += dt.timedelta(days=1) if stop >= t0 and start <= t1: fetch(base + name, os.path.join(ssj, name)) print("SSJ 2024 done", flush=True) for sat, name in (("f08", "j4f0889072.gz"), ("f08", "j4f0889073.gz"), ("f09", "j4f0989072.gz"), ("f09", "j4f0989073.gz")): fetch(f"{NCEI}/{sat}/ssj/1989/03/{name}", os.path.join(folder, "j4_1989", name)) ssusi = os.path.join(folder, "ssusi") for sat in ("dmspf17", "dmspf18"): # SPDF has no F16 or F19 EDR-Aurora for these days for day in ("131", "132"): base = f"{SPDF}/{sat}/ssusi/data/edr-aurora/2024/{day}/" for name in re.findall(r'', listing(base)): m = re.search(r"_(\d{7})T(\d{6})-(\d{7})T(\d{6})-REV", name) if m and m.group(3) + m.group(4) >= "2024131160000" and m.group(1) + m.group(2) <= "2024132030000": fetch(base + name, os.path.join(ssusi, name)) print("SSUSI done", flush=True) for s in ("F16", "F17", "F18"): fetch(f"{HAPI}/data?id=DMSP-{s}_SSIES-3_THERMAL-PLASMA&time.min=2024-05-10T09:00:00Z&time.max=2024-05-11T03:00:00Z¶meters=vy,vyrms,dmhrough,dens,corvely&format=csv", os.path.join(folder, "ssies", s + ".csv")) a = "SC_GEOCENTRIC_LAT,SC_GEOCENTRIC_LON,SC_AACGM_LAT,SC_AACGM_LTIME,ELE_DIFF_ENERGY_FLUX" b = "ELE_DIFF_ENERGY_FLUX,SC_GEOCENTRIC_LAT,SC_GEOCENTRIC_LON,SC_AACGM_LAT,SC_AACGM_LTIME" # F16's dataset lists the flux first wins = {"20031029": ("2003-10-29T06:00:00Z", "2003-10-30T01:00:00Z"), "20031030": ("2003-10-30T16:00:00Z", "2003-10-31T00:00:00Z"), "20031120": ("2003-11-20T08:00:00Z", "2003-11-20T21:00:00Z")} for s, order, labels in (("F13", a, wins), ("F15", a, wins), ("F14", a, ["20031120"]), ("F16", b, ["20031029"])): for lab in labels: fetch(f"{HAPI}/data?id=DMSP-{s}_SSJ_PRECIPITATING-ELECTRONS-IONS&time.min={wins[lab][0]}&time.max={wins[lab][1]}¶meters={order}&format=csv", os.path.join(folder, "ssj_2003", f"{s}_{lab}.csv")) fetch(f"{HAPI}/data?id=DMSP-F18_SSJ_PRECIPITATING-ELECTRONS-IONS&time.min=2014-12-01T10:00:00Z&time.max=2014-12-01T10:40:00Z¶meters=ELE_COUNTS_OBS,ELE_COUNTS_BKG,ELE_DIFF_ENERGY_FLUX,ELE_TOTAL_ENERGY_FLUX,SC_AACGM_LAT,SC_AACGM_LTIME&format=csv", os.path.join(folder, "f18-ssj-2014-12-01-sample.csv")) print("CDAWeb done", flush=True) k = os.path.join(folder, "kyoto") fetch(f"{KYOTO}?id=hour_dst_provisional¶meters=dstValue&time.min=2024-05-10T00:00:00Z&time.max=2024-05-11T12:00:00Z&format=csv", os.path.join(k, "dst_202405.csv")) fetch(f"{KYOTO}?id=min_asysym¶meters=symHValue,versionCode&time.min=2024-05-10T16:00:00Z&time.max=2024-05-11T04:00:00Z&format=csv", os.path.join(k, "symh_202405.csv")) for lab, x0, x1 in (("198903", "1989-03-13T00:00:00Z", "1989-03-14T12:00:00Z"), ("200310", "2003-10-29T00:00:00Z", "2003-10-31T12:00:00Z"), ("200311", "2003-11-20T00:00:00Z", "2003-11-21T12:00:00Z")): fetch(f"{KYOTO}?id=hour_dst¶meters=dstValue&time.min={x0}&time.max={x1}&format=csv", os.path.join(k, f"dst_{lab}.csv")) fetch(f"{GFZ}?start=2024-05-10T00:00:00Z&end=2024-05-12T23:59:59Z&index=Kp", os.path.join(folder, "gfz", "kp.json")) fetch(f"{GFZ}?start=2024-05-10T15:00:00Z&end=2024-05-11T06:00:00Z&index=Hp30", os.path.join(folder, "gfz", "hp30.json")) fetch(ZENODO_ZIP, os.path.join(folder, "SuperDARN-csv.zip"), optional=True) # Zenodo has refused curl from some networks; the rest runs without it # ---------------------------------------------------------------- reading SSJ5 text files def read_sdr(path): """Blocks of: A index yyyy m d H M S mltH mltM counter daynumber; B geodetic lat, lon, footprint lat, lon, CGM lat, lon at 110 km, altitude (nmi); then four one-second groups: index yyyy m d H M S and four lines of ten values.""" out = [] with open(path, "r", encoding="latin-1") as f: lines = f.read().split("\n") i, n, block = 3, len(lines), None while i < n: toks = lines[i].split() if len(toks) == 11 and "." in toks[10]: try: mlt_h, mlt_m = int(toks[7]), int(toks[8]) pos = [float(x) for x in lines[i + 1].split()] except (ValueError, IndexError): i += 1 continue if len(pos) != 7: i += 1 continue block = dict(mlt_h=mlt_h, mlt_m=mlt_m, glat=pos[0], glon=pos[1], cgmlat=pos[4], cgmlon=pos[5], alt=pos[6]) i += 2 continue if len(toks) == 7 and block is not None and i + 4 < n: try: y, mo, d, h, mi, s = [int(t) for t in toks[1:7]] vals = [] for k in range(1, 5): vals.extend(float(x) for x in lines[i + k].split()) except ValueError: i += 1 continue if len(vals) == 40: rec = dict(block) rec["t"] = (dt.datetime(y, mo, d, h, mi, 0) - EPOCH).total_seconds() + s rec["ele"] = vals[:20] out.append(rec) i += 5 continue i += 1 return out def load_ssj(folder): by_sat = {} for name in sorted(os.listdir(folder)): if name.endswith("_DF.SDR"): sat = "F" + re.search(r"SSJ5X-F(\d\d)-", name).group(1) d = by_sat.setdefault(sat, {}) for r in read_sdr(os.path.join(folder, name)): d.setdefault(r["t"], r) tables = {} for sat, d in by_sat.items(): ts = sorted(d) tables[sat] = dict(t=np.array(ts), glat=np.array([d[x]["glat"] for x in ts]), glon=np.array([d[x]["glon"] for x in ts]), cgmlat=np.array([d[x]["cgmlat"] for x in ts]), alt=np.array([d[x]["alt"] for x in ts]), mlt_file=np.array([d[x]["mlt_h"] + (d[x]["mlt_m"] + 0.5) / 60.0 for x in ts]), ele=np.array([d[x]["ele"] for x in ts])) return tables def parse_edr(folder): rows = {} for name in sorted(os.listdir(folder)): if not name.endswith("_DF.EDR"): continue sat = re.search(r"SSJ5X-(F\d\d)-", name).group(1) lines = open(os.path.join(folder, name), encoding="latin-1").read().split("\n") i = 1 while i + 1 < len(lines): a, b = lines[i].split(), lines[i + 1].split() if len(a) >= 13 and len(b) >= 11: y, mo, d, h, mi, s = [int(x) for x in a[3:9]] tm = dt.datetime(y, mo, d, h, mi, s) rows[(sat, tm, b[2])] = dict(sat=sat, t=(tm - EPOCH).total_seconds(), mlt=int(a[9]) + int(a[10]) / 60 + int(a[11]) / 3600, glat=float(b[0]), glon=float(b[1]), cgmlat=float(b[2])) i += 2 return list(rows.values()) # ---------------------------------------------------------------- the pipeline def utstr(t, epoch=EPOCH): return (epoch + dt.timedelta(seconds=float(t))).strftime("%Y-%m-%d %H:%M:%S") def coadd(o, w): """Running mean over w seconds of each column, on a 1-s grid with NaN where a second is missing; at least half the window must be present.""" n, k = o.shape valid = ~np.isnan(o) ca = np.vstack([np.zeros((1, k)), np.cumsum(np.where(valid, o, 0.0), axis=0)]) cv = np.vstack([np.zeros((1, k)), np.cumsum(valid, axis=0)]) h = w // 2 lo, hi = np.clip(np.arange(n) - h, 0, n), np.clip(np.arange(n) + h + 1, 0, n) s, c = ca[hi] - ca[lo], cv[hi] - cv[lo] with np.errstate(invalid="ignore", divide="ignore"): m = s / c m[c < (w + 1) // 2] = np.nan return m def je_from_counts(g, use, ele_grid, w, dwell): """JE >= 1 keV, JE all energies, the flat-count mask, and JE from channels 1-3 (13.9 keV and above), from per-second counts.""" o = ele_grid[:, use].copy() o[o < 0] = np.nan mean = coadd(o, w) with warnings.catch_warnings(): warnings.simplefilter("ignore") b = np.nanpercentile(mean, 25, axis=1) p10 = np.nanpercentile(mean, 10, axis=1) p90 = np.nanpercentile(mean, 90, axis=1) B = b + 2.0 * np.sqrt(np.maximum(b, 1.0) / w) c = np.maximum(mean - B[:, None], 0.0) je = c / (g[use] * dwell) * CH_E[use] * CH_DE[use] hi = CH_E[use] >= 1000 je_hi, je_all, je_top = np.nansum(je[:, hi], axis=1), np.nansum(je, axis=1), np.nansum(je[:, :3], axis=1) nan = np.isnan(b) je_hi[nan], je_all[nan], je_top[nan] = np.nan, np.nan, np.nan with np.errstate(all="ignore"): flat = (p10 >= 10) & (p90 / p10 < 2.5) return je_hi, je_all, flat, je_top def soft_from_counts(g, chans, ele_grid, w, dwell): """Amendment 5: excess over the flat level in the channels of 6.46 keV to 139 eV, in eV/cm2/s/sr.""" o = ele_grid.copy() o[o < 0] = np.nan mean = coadd(o, w) with warnings.catch_warnings(): warnings.simplefilter("ignore") fl = np.nanmedian(mean[:, SOFT_TOP], axis=1) sig = np.sqrt(np.maximum(fl, 0.5) / w) x = np.maximum(mean[:, chans] - fl[:, None] - 2.0 * sig[:, None], 0.0) je = np.nansum(x / (g[chans] * dwell) * CH_E[chans] * CH_DE[chans], axis=1) je[np.isnan(fl)] = np.nan return je def saa_box(glat, glon): lon = np.asarray(glon) % 360.0 return (np.asarray(glat) >= -60.0) & (np.asarray(glat) <= 0.0) & ((lon >= 270.0) | (lon <= 40.0)) def legs(t, lat): """Crossings: stretches of same-sign latitude with no gap over 10 min, split at the highest-latitude point.""" out, n = [], len(t) breaks = np.where((np.diff(t) > 600) | (np.sign(lat[1:]) != np.sign(lat[:-1])))[0] for a, b in zip(np.r_[0, breaks + 1], np.r_[breaks + 1, n]): if b - a < 60: continue k = a + int(np.argmax(np.abs(lat[a:b]))) if k - a >= 30: out.append(np.arange(a, k + 1)) if b - k >= 30: out.append(np.arange(k, b)) return out def edge_walk(lg, s, x, win): ok = s >= x if not np.any(ok): return None order = np.argsort(lg) lg_o, ok_o = lg[order], ok[order] for i in np.where(ok_o)[0]: j = np.searchsorted(lg_o, lg_o[i] + win, side="right") if ok_o[i:j].mean() >= 0.5: return int(order[i]) return None def grid_leg(tl): tgrid = np.arange(tl[0], tl[-1] + 1) idx = np.clip(np.searchsorted(tl, tgrid), 0, len(tl) - 1) return tgrid, idx, tl[idx] == tgrid def guss(mlt, kp): """Gussenhoven et al. 1983 as transcribed in ocbpy. Bin h covers h to h+1, centred at h+0.5; linear between bins and across the missing bins.""" hrs = sorted(GUSS_L0) xs = np.array([h + 0.5 for h in hrs] + [hrs[0] + 24.5]) ys = np.array([GUSS_L0[h] + GUSS_A[h] * kp for h in hrs] + [GUSS_L0[hrs[0]] + GUSS_A[hrs[0]] * kp]) m = mlt % 24 if m < xs[0]: m += 24 return float(np.interp(m, xs, ys)) def troyer(mlt, h): """Troyer et al. 2025, 50th percentile, as transcribed in ocbpy.""" a0, a1, al = 1.5 * h + 20.57, -3.45 * math.tanh(-0.34 * h) + 2.49, 0.23 * h - 2.25 return 90.0 - (a0 + a1 * math.cos(2 * math.pi * (mlt + al) / 24.0)) def lat_from_eb(eb): return math.degrees(math.acos(math.sqrt(1.0 / (8e17 / eb) ** (1.0 / 3.0)))) def yokoyama_all(d): return lat_from_eb((-4e13 * d + 4.7e14) / 0.11) def yokoyama_1989(d): return lat_from_eb(-4e13 * d / 0.17 + 1.4e16) def lval(x): return 1.0 / math.cos(math.radians(x)) ** 2 def ilat_to_mlat(x, h=400.0, re_km=6371.0): return math.degrees(math.acos(math.sqrt((1 + h / re_km) / lval(x)))) def dipole_mlt(t, glat, glon): """Centred-dipole MLT, only to check the files' MLT field. Pole at 80.8 N, 72.7 W.""" plat, plon = math.radians(80.8), math.radians(-72.7) def cd_lon(la, lo): la, lo = math.radians(la), math.radians(lo) x, y, z = math.cos(la) * math.cos(lo), math.cos(la) * math.sin(lo), math.sin(la) x1, y1 = x * math.cos(plon) + y * math.sin(plon), -x * math.sin(plon) + y * math.cos(plon) return math.degrees(math.atan2(y1, x1 * math.sin(plat) - z * math.cos(plat))) tm = EPOCH + dt.timedelta(seconds=float(t)) ut = tm.hour + tm.minute / 60 + tm.second / 3600 doy = tm.timetuple().tm_yday + ut / 24 decl = 23.44 * math.sin(2 * math.pi * (doy - 81) / 365.25) b = 2 * math.pi * (doy - 81) / 364.0 eot = 9.87 * math.sin(2 * b) - 7.53 * math.cos(b) - 1.5 * math.sin(b) return ((cd_lon(glat, glon) - cd_lon(decl, 15.0 * (12.0 - ut - eot / 60.0))) / 15.0 + 12.0) % 24.0 def series_at(series, t): v = None for a, b in series: if a <= t: v = b else: break return v def load_gfz(path, key): d = json.load(open(path, encoding="utf-8")) return [((dt.datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ") - EPOCH).total_seconds(), float(v)) for x, v in zip(d["datetime"], d[key])] def load_dst_csv(path, epoch): out = [] for row in csv.reader(open(path, encoding="utf-8")): tm = dt.datetime.strptime(row[0][:13] + ":00:00", "%Y-%m-%dT%H:%M:%S") out.append(((tm - epoch).total_seconds(), float(row[1]))) return out def rnd(v, n=2): return None if v is None else round(float(v), n) def analyse_2024(tables, kp, hp, dst): variants = {"primary": (11, "hi", 2.0), "all_energies": (11, "all", 2.0), "coadd5": (5, "hi", 2.0), "coadd21": (21, "hi", 2.0), "persist1": (11, "hi", 1.0), "persist3": (11, "hi", 3.0)} use = np.ones(20, bool) use[10] = False rows, control, soft_control = [], {}, {} ths = [2e9, 4e9, 6e9, 1e10, 2e10, 4e10, 2e11] for sat, T in sorted(tables.items()): g = np.array(G[sat]) t, lat = T["t"], T["cgmlat"] ctrl_vals = [] ctrl_nosaa = [] soft_nosaa, soft_saa = [], [] q0006, q0006_saa = 0, 0 for leg in legs(t, lat): tgrid, idx, ok = grid_leg(t[leg]) if ok.sum() < 30: continue ele = np.full((len(tgrid), 20), np.nan) ele[ok] = T["ele"][leg][idx[ok]] lg = np.interp(np.arange(len(tgrid)), np.where(ok)[0], np.abs(lat[leg][idx[ok]])) mlt = np.full(len(tgrid), np.nan) mlt[ok] = T["mlt_file"][leg][idx[ok]] floor = float(lg.min()) saa = np.zeros(len(tgrid), bool) saa[ok] = saa_box(T["glat"][leg][idx[ok]], T["glon"][leg][idx[ok]]) res, s0 = {}, None for nm, (w, q, win) in variants.items(): je_hi, je_all, flat, _ = je_from_counts(g, use, ele, w, DT_J5) s = (je_hi if q == "hi" else je_all).copy() s[flat] = np.nan if nm == "primary" and tgrid[-1] < SC: # the control as amendment 3 used it, before the South Atlantic mask sel = (lg >= 40) & (lg < 45) & ~np.isnan(s) ctrl_nosaa.append(s[sel]) s[saa] = np.nan if nm == "primary": s0 = s for lab, x in LADDER.items(): if nm == "primary" or lab == "1e10": res[(nm, lab)] = edge_walk(lg, s, x, win) soft = soft_from_counts(g, SOFT_J5, ele, 11, DT_J5) soft_m = soft.copy() soft_m[saa] = np.nan if tgrid[-1] < SC: ctrl_vals.append(s0[(lg >= 40) & (lg < 45) & ~np.isnan(s0)]) band = (lg >= 40) & (lg < 45) soft_nosaa.append(soft[band & ~np.isnan(soft)]) soft_saa.append(soft_m[band & ~np.isnan(soft_m)]) with np.errstate(invalid="ignore"): sector = band & (mlt >= 0) & (mlt < 6) q0006 += int(sector.sum()) q0006_saa += int((sector & saa).sum()) i0 = res[("primary", "1e10")] if i0 is None: continue tm0 = float(tgrid[i0]) m0 = mlt[i0] if not np.isnan(mlt[i0]) else float(np.nanmedian(mlt[max(0, i0 - 5): i0 + 6])) above = np.where(s0 >= 1e10)[0] rec = dict(sat=sat, hemi="N" if np.median(lat[leg]) > 0 else "S", t_edge=tm0, ut=utstr(tm0), mlt=float(m0), floor=floor, lowest_any=float(lg[above].min()) if len(above) else None) for lab in LADDER: ii = res[("primary", lab)] rec["edge_" + lab] = None if ii is None else float(lg[ii]) ii = res[("primary", "2e11")] rec["ut_2e11"] = None if ii is None else utstr(tgrid[ii]) rec["mlt_2e11"] = None if ii is None or np.isnan(mlt[ii]) else float(mlt[ii]) for nm in ("all_energies", "coadd5", "coadd21", "persist1", "persist3"): ii = res[(nm, "1e10")] rec["edge_" + nm] = None if ii is None else float(lg[ii]) rec["at_floor"] = rec["edge_1e10"] - floor <= 1.0 for lab, x in SOFT_LADDER.items(): ii = edge_walk(lg, soft_m, x, 2.0) rec["soft_" + lab] = None if ii is None else float(lg[ii]) je_p, _, _, top_p = je_from_counts(g, use, ele, 11, DT_J5) # no mask: the raw quantity, for the floor and the shares low = lg <= floor + 2.0 rec["floor_median"] = float(np.nanmedian(je_p[low])) for lab, x in (("1e10", 1e10), ("2e10", 2e10), ("3e10", 3e10), ("4e10", 4e10)): rec["floor_frac_" + lab] = float(np.mean(je_p[low] >= x)) i3 = res[("primary", "3e10")] if i3 is not None: rec["ut_3e10"] = utstr(tgrid[i3]) rec["mlt_3e10"] = float(mlt[i3]) if not np.isnan(mlt[i3]) else float(np.nanmedian(mlt[max(0, i3 - 5): i3 + 6])) rec["top_share_edge"] = float(top_p[i3] / max(je_p[i3], 1.0)) near = (lg >= lg[i3]) & (lg <= lg[i3] + 2.0) rec["top_share_2deg"] = float(np.nansum(top_p[near]) / max(np.nansum(je_p[near]), 1.0)) rec["peak_next_2deg"] = float(np.nanmax(je_p[near])) rec["kp"], rec["hp30"], rec["dst"] = series_at(kp, tm0), series_at(hp, tm0), series_at(dst, tm0) if rec["kp"] is not None: rec["g83"], rec["tr25_kp"] = guss(rec["mlt"], rec["kp"]), troyer(rec["mlt"], rec["kp"]) if rec["hp30"] is not None: rec["tr25_hp"] = troyer(rec["mlt"], rec["hp30"]) if rec["dst"] is not None and rec["dst"] < 0: rec["yo98_all"], rec["yo98_89"] = yokoyama_all(rec["dst"]), yokoyama_1989(rec["dst"]) rows.append(rec) v = np.concatenate(ctrl_vals) vn = np.concatenate(ctrl_nosaa) control[sat] = dict(seconds_before_saa_mask=int(len(vn)), fraction_above_before_saa_mask={f"{x:.0e}": round(float(np.mean(vn >= x)), 4) for x in ths}, seconds_with_saa_mask=int(len(v)), fraction_above_1e10_with_saa_mask=round(float(np.mean(v >= 1e10)), 5), quiet_seconds_00_06_mlt=q0006, of_which_in_south_atlantic_box=q0006_saa) a, b = np.concatenate(soft_nosaa), np.concatenate(soft_saa) soft_control[sat] = dict(seconds_before_saa_mask=int(len(a)), fraction_above_before_saa_mask={f"{x:.0e}": round(float(np.mean(a >= x)), 4) for x in SOFT_LADDER.values()}, seconds_with_saa_mask=int(len(b)), fraction_above_with_saa_mask={f"{x:.0e}": round(float(np.mean(b >= x)), 4) if len(b) else None for x in SOFT_LADDER.values()}) rows.sort(key=lambda c: c["t_edge"]) return rows, control, soft_control def analyse_ssies(folder, tables): rows, frame = [], {} for sat in ("F16", "F17", "F18"): t, vy, cor = [], [], [] for row in csv.reader(open(os.path.join(folder, sat + ".csv"), encoding="utf-8")): if len(row) >= 6: t.append((dt.datetime.strptime(row[0][:19], "%Y-%m-%dT%H:%M:%S") - EPOCH).total_seconds()) vy.append(float(row[1])) cor.append(float(row[5])) t, vy, cor = np.array(t), np.array(vy), np.array(cor) vy[np.abs(vy) > 1e5] = np.nan cor[np.abs(cor) > 1e5] = np.nan T = tables[sat] tt, lat, mlt = T["t"], T["cgmlat"], T["mlt_file"] idx = np.clip(np.searchsorted(t, tt), 0, len(t) - 1) q = (t[idx] == tt) & (tt < SC) & (np.abs(lat) >= 40) & (np.abs(lat) < 50) a, b = np.nanstd(vy[idx][q]), np.nanstd((vy - cor)[idx][q]) frame[sat] = dict(cadence_s=float(np.median(np.diff(t))), quiet_std_vy=round(float(a), 1), quiet_std_vy_minus_corvely=round(float(b), 1), used="vy" if a <= b else "vy-corvely") v = np.abs(vy if a <= b else vy - cor) for leg in legs(tt, lat): tgrid, ii, ok = grid_leg(tt[leg]) if ok.sum() < 30: continue lg = np.interp(np.arange(len(tgrid)), np.where(ok)[0], np.abs(lat[leg][ii[ok]])) m = np.interp(np.arange(len(tgrid)), np.where(ok)[0], np.unwrap(mlt[leg][ii[ok]] * 2 * np.pi / 24) * 24 / (2 * np.pi)) % 24 jj = np.clip(np.searchsorted(t, tgrid), 0, len(t) - 1) good = t[jj] == tgrid vv = np.full(len(tgrid), np.nan) vv[good] = v[jj[good]] s = np.full(len(tgrid), np.nan) with warnings.catch_warnings(): warnings.simplefilter("ignore") for i in range(len(tgrid)): seg = vv[max(0, i - 5): min(len(tgrid), i + 6)] if np.sum(~np.isnan(seg)) >= 6: s[i] = np.nanmedian(seg) rec = dict(sat=sat, hemi="N" if np.median(lat[leg]) > 0 else "S") for x in (300.0, 500.0, 1000.0): i = edge_walk(lg, s, x, 2.0) rec[f"edge_{int(x)}"] = None if i is None else round(float(lg[i]), 2) if x == 300.0: j = len(tgrid) // 2 if i is None else i rec["t"], rec["mlt"] = float(tgrid[j]), float(m[j]) rec["ut"] = utstr(rec["t"]) rec["vmax"] = round(float(np.nanmax(s)), 0) if np.any(~np.isnan(s)) else None rows.append(rec) rows.sort(key=lambda r: r["t"]) return rows, frame def pair_ion(ion_rows, main): pairs, pairs_soft = [], [] for c in main: best = None for q in ion_rows: if q["sat"] == c["sat"] and q["hemi"] == c["hemi"] and q["edge_300"] is not None and 0 <= q["mlt"] < 6 and q["t"] >= SC: d = abs(q["t"] - c["t_edge"]) if d < 900 and (best is None or d < best[0]): best = (d, q) c["ion"] = best[1] if best else None if best: pairs.append(best[1]["edge_300"] - c["edge_3e10"]) if c["soft_1e9"] is not None: pairs_soft.append(best[1]["edge_300"] - c["soft_1e9"]) return pairs, pairs_soft def analyse_ssusi(folder): per_file, allmin = [], [] for name in sorted(os.listdir(folder)): if not name.endswith(".nc"): continue m = re.search(r"dmsp(f\d\d)_ssusi_edr-aurora_(\d{7}T\d{6})-", name) ds = nc.Dataset(os.path.join(folder, name)) gl, gm = np.array(ds["LATITUDE_GEOMAGNETIC_GRID_MAP"][:]), np.array(ds["MLT_GRID_MAP"][:]) for hemi, a, b, qv, utv in (("N", "NORTH_GEOMAGNETIC_LATITUDE", "NORTH_MAGNETIC_LOCAL_TIME", "ENERGY_FLUX_NORTH_MAP", "UT_N"), ("S", "SOUTH_GEOMAGNETIC_LATITUDE", "SOUTH_MAGNETIC_LOCAL_TIME", "ENERGY_FLUX_SOUTH_MAP", "UT_S")): la = np.abs(np.ma.filled(ds[a][:], np.nan).astype(float)) lt = np.ma.filled(ds[b][:], np.nan).astype(float) good = np.isfinite(la) & (la > 0) if good.any(): allmin.append(float(la[good].min())) sec = good & np.isfinite(lt) & (lt >= 0) & (lt < 6) q = np.ma.filled(ds[qv][:], np.nan).astype(float) ut = np.array(ds[utv][:], dtype=float) sw = ut > 0 sel = (gm >= 0) & (gm < 6) & sw hit = sel & (q >= 0.2) per_file.append(dict(sat=m.group(1).upper(), file_start=m.group(2), hemi=hemi, median_ut_h=rnd(np.median(ut[sw])) if sw.any() else None, boundary_lowest_00_06=rnd(la[sec].min()) if sec.any() else None, n_boundary_below_50=int((la[sec] < 50).sum()), map_lowest_00_06=rnd(gl[sel].min()) if sel.any() else None, q02_lowest_00_06=rnd(gl[hit].min()) if hit.any() else None)) ds.close() return per_file, round(min(allmin), 2) def calibration(path): g = np.array(G["F18"]) use = np.ones(20, bool) use[10] = False E, dE, Gu = CH_E[use], CH_DE[use], g[use] ratios = [] for row in csv.reader(open(path, encoding="utf-8")): vals = [float(x) for x in row[1:]] obs, bkg, flx = np.array(vals[0:19]), np.array(vals[19:38]), np.array(vals[38:57]) c = np.abs(obs - bkg) with np.errstate(divide="ignore", invalid="ignore"): r = flx / (c / (Gu * DT_J5) * E) ratios.extend(r[(c > 20) & np.isfinite(r) & (flx > 0)].tolist()) return dict(n=len(ratios), nasa_over_ours_median=round(float(np.median(ratios)), 3), p05=round(float(np.percentile(ratios, 5)), 3), p95=round(float(np.percentile(ratios, 95)), 3)) def superdarn(zip_path): if not os.path.exists(zip_path): return None z = zipfile.ZipFile(zip_path) rows = [] for n in sorted(x for x in z.namelist() if x.endswith(".csv")): m = re.search(r"_(\d{2})(\d{2})(\d{2})\.csv$", n) minute = int(m.group(1)) * 60 + int(m.group(2)) with z.open(n) as raw: for r in csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8")): rows.append((minute, float(r["mlats"]), float(r["v_mag"]))) a = np.array(rows) out = [] for start in range(17 * 60, 24 * 60, 30): s = (a[:, 0] >= start) & (a[:, 0] < start + 30) rec = dict(ut_bin_start=f"{start // 60:02d}:{start % 60:02d}", n_vectors=int(s.sum()), lowest_mlat_any=float(a[s, 1].min())) for thr in (300, 500, 1000): f = s & (a[:, 2] >= thr) low = None if f.any(): vals, cnt = np.unique(a[f, 1], return_counts=True) ok = vals[cnt >= 3] low = float(ok.min()) if len(ok) else None rec[f"lowest_mlat_3_vectors_ge{thr}"] = low out.append(rec) return out # ---------------------------------------------------------------- earlier storms def latconv(i): return (i - 4995) / 10.0 if i > 1800 else (i - 900) / 10.0 def read_j4(path, year): b = gzip.open(path, "rb").read() ts, lats, mlts, eles, glats, glons = [], [], [], [], [], [] for k in range(len(b) // 5280): w = struct.unpack(">2640H", b[k * 5280: (k + 1) * 5280]) if w[0] == 0 or w[4] + 1950 != year: # word 5 holds the year minus 1950 continue t0 = (dt.datetime(year, 1, 1) + dt.timedelta(days=w[0] - 1, hours=w[1], minutes=w[2], seconds=w[3]) - EPOCH_OLD).total_seconds() cgm, mlt = latconv(w[10]), w[12] + w[13] / 60.0 + w[14] / 3600.0 for s in range(60): raw = np.array(w[15 + 43 * s + 3: 15 + 43 * s + 23], dtype=float) x = raw % 32 e = (x + 32) * (2.0 ** ((raw - x) // 32)) - 33.0 e[e < 0] = np.nan row = np.full(20, np.nan) for j, ch in enumerate(ORDER): row[ch - 1] = e[j] ts.append(t0 + s) lats.append(cgm) mlts.append(mlt) eles.append(row) glats.append(latconv(w[5])) glons.append(w[6] / 10.0) ts, lats, mlts = np.array(ts), np.array(lats), np.array(mlts) mins = np.arange(0, len(ts), 60) lat_i = np.interp(ts, ts[mins], lats[mins]) mlt_i = np.interp(ts, ts[mins], np.unwrap(mlts[mins] * 2 * np.pi / 24) * 24 / (2 * np.pi)) % 24 return ts, lat_i, mlt_i, np.array(eles), np.array(glats), np.array(glons) def read_hapi_2003(path, sat): ts, lat, mlt, je, glat, glon = [], [], [], [], [], [] hi = E19 >= 1000 for row in csv.reader(open(path, encoding="utf-8")): if len(row) < 24: continue tm = dt.datetime.strptime(row[0][:19], "%Y-%m-%dT%H:%M:%S") if sat == "F16": fl, ga, go, la, lt = row[1:20], row[20], row[21], row[22], row[23] else: ga, go, la, lt, fl = row[1], row[2], row[3], row[4], row[5:24] try: ga, go, la, lt = float(ga), float(go), float(la), float(lt) f = np.array([float(x) for x in fl]) except ValueError: continue if np.isnan(la): continue ts.append((tm - EPOCH_OLD).total_seconds()) lat.append(la) mlt.append(lt) glat.append(ga) glon.append(go) je.append(np.nansum(f[hi] * DE19[hi]) if not np.all(np.isnan(f)) else np.nan) return np.array(ts), np.array(lat), np.array(mlt), np.array(je), np.array(glat), np.array(glon) def old_crossings(t, lat, mlt, series_fn, sat, label, dst, extra_fn=None): rows = [] for leg in legs(t, lat): tgrid, idx, ok = grid_leg(t[leg]) if ok.sum() < 30: continue lg = np.interp(np.arange(len(tgrid)), np.where(ok)[0], np.abs(lat[leg][idx[ok]])) m = np.interp(np.arange(len(tgrid)), np.where(ok)[0], np.unwrap(mlt[leg][idx[ok]] * 2 * np.pi / 24) * 24 / (2 * np.pi)) % 24 s = series_fn(leg, tgrid, idx, ok) rec = dict(storm=label, sat=sat, hemi="N" if np.median(lat[leg]) > 0 else "S", floor=round(float(lg.min()), 2)) first = None for lab, x in OLD_LADDER.items(): i = edge_walk(lg, s, x, 2.0) rec["edge_" + lab] = None if i is None else round(float(lg[i]), 2) if i is not None and first is None: first = i if first is None: continue if extra_fn is not None: for col, (ser, x) in extra_fn(leg, tgrid, idx, ok).items(): i = edge_walk(lg, ser, x, 2.0) rec[col] = None if i is None else round(float(lg[i]), 2) rec["t"] = float(tgrid[first]) rec["ut"] = utstr(rec["t"], EPOCH_OLD) rec["mlt"] = round(float(m[first]), 2) rec["dst"] = series_at(dst, rec["t"]) rows.append(rec) return rows def analyse_old(folder): rows = [] d89 = load_dst_csv(os.path.join(folder, "kyoto", "dst_198903.csv"), EPOCH_OLD) d0310 = load_dst_csv(os.path.join(folder, "kyoto", "dst_200310.csv"), EPOCH_OLD) d0311 = load_dst_csv(os.path.join(folder, "kyoto", "dst_200311.csv"), EPOCH_OLD) use = np.ones(20, bool) for sat, a, b in (("F08", "j4f0889072.gz", "j4f0889073.gz"), ("F09", "j4f0989072.gz", "j4f0989073.gz")): pa, pb = [read_j4(os.path.join(folder, "j4_1989", x), 1989) for x in (a, b)] t, lat, mlt, ele, gl, go = [np.r_[pa[i], pb[i]] if i != 3 else np.vstack([pa[3], pb[3]]) for i in range(6)] sel = (t >= (dt.datetime(1989, 3, 13, 12) - EPOCH_OLD).total_seconds()) & (t <= (dt.datetime(1989, 3, 14, 4) - EPOCH_OLD).total_seconds()) t, lat, mlt, ele = t[sel], lat[sel], mlt[sel], ele[sel] mask = saa_box(gl[sel], go[sel]) def fn(leg, tgrid, idx, ok, ele=ele, mask=mask, g=np.array(G_J4[sat])): e = np.full((len(tgrid), 20), np.nan) e[ok] = ele[leg][idx[ok]] hi, _, flat, _ = je_from_counts(g, use, e, 11, DT_J4) hi[flat] = np.nan m_ = np.zeros(len(tgrid), bool) m_[ok] = mask[leg][idx[ok]] hi[m_] = np.nan return hi def fn_extra(leg, tgrid, idx, ok, ele=ele, mask=mask, g=np.array(G_J4[sat])): e = np.full((len(tgrid), 20), np.nan) e[ok] = ele[leg][idx[ok]] hi, _, flat, _ = je_from_counts(g, use, e, 11, DT_J4) hi[flat] = np.nan # flat mask on, South Atlantic box off m_ = np.zeros(len(tgrid), bool) m_[ok] = mask[leg][idx[ok]] sft = soft_from_counts(g, SOFT_J4, e, 11, DT_J4) sft[m_] = np.nan return {"edge_3e10_box_off": (hi, 3e10), "edge_4e10_box_off": (hi, 4e10), "soft_1e9": (sft, 1e9), "soft_3e9": (sft, 3e9)} rows += old_crossings(t, lat, mlt, fn, sat, "1989-03", d89, fn_extra) for sat, labs in (("F13", ("20031029", "20031030", "20031120")), ("F14", ("20031120",)), ("F15", ("20031029", "20031030", "20031120")), ("F16", ("20031029",))): for lab in labs: t, lat, mlt, je, ga, go = read_hapi_2003(os.path.join(folder, "ssj_2003", f"{sat}_{lab}.csv"), sat) je = je.copy() je[saa_box(ga, go)] = np.nan def fn2(leg, tgrid, idx, ok, je=je): g = np.full((len(tgrid), 1), np.nan) g[ok, 0] = je[leg][idx[ok]] return coadd(g, 11)[:, 0] label = {"20031029": "2003-10-29", "20031030": "2003-10-30", "20031120": "2003-11-20"}[lab] rows += old_crossings(t, lat, mlt, fn2, sat, label, d0311 if lab == "20031120" else d0310) rows.sort(key=lambda r: r["t"]) summ = {} keys = tuple("edge_" + k for k in OLD_LADDER) for storm in sorted({r["storm"] for r in rows}): rr = [r for r in rows if r["storm"] == storm] def low(sub, k): v = [r[k] for r in sub if r.get(k) is not None and r[k] >= 35.0] return min(v) if v else None def group(sub): return {k: low(sub, k) for k in keys} summ[storm] = dict(n=len(rr), n_00_06=sum(1 for r in rr if 0 <= r["mlt"] < 6), lowest_00_06=group([r for r in rr if 0 <= r["mlt"] < 6]), lowest_00_08=group([r for r in rr if 0 <= r["mlt"] < 8]), lowest_18_24=group([r for r in rr if 18 <= r["mlt"] < 24]), suspect_below_35_left_out={k: sum(1 for r in rr if r.get(k) is not None and r[k] < 35.0) for k in keys}, sats=sorted({r["sat"] for r in rr}), min_dst=min(r["dst"] for r in rr if r.get("dst") is not None)) return rows, summ # ---------------------------------------------------------------- outputs def fmt(v, nd=2): return "" if v is None else f"{v:.{nd}f}" def dump_counts(tables, path): out = ["Raw SSJ electron counts, for looking at crossings in and just past 00-06 MLT during the main phase of the May 2024 storm. One second is shown every 10 s.", "Columns: UT, CGM latitude, MLT, then counts in each electron channel: 30 keV down to 949 eV | 646 eV down to 30 eV. Public data from NOAA NCEI. Which of these look like precipitation and which like background is our judgment."] for sat, a, b in DUMPS: T = tables[sat] t0 = (dt.datetime.fromisoformat(a) - EPOCH).total_seconds() t1 = (dt.datetime.fromisoformat(b) - EPOCH).total_seconds() out += ["", f"== {sat} {a} to {b}", "UT cgm mlt | 30k 20k 14k 9.4k 6.5k 4.4k 3k 2k 1.4k 949 | 646 440 300 204 139 95 65 44 30"] for i in np.where((T["t"] >= t0) & (T["t"] <= t1))[0][::10]: e = T["ele"][i] tm = EPOCH + dt.timedelta(seconds=float(T["t"][i])) out.append(tm.strftime("%H:%M:%S") + f" {T['cgmlat'][i]:7.2f} {T['mlt_file'][i]:5.2f} | " + " ".join(f"{int(x):5d}" for x in e[:10]) + " | " + " ".join(f"{int(x):5d}" for x in e[11:])) with open(path, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(out) + "\n") def dump_counts_1989(folder, path): out = ["Raw SSJ4 electron counts on the F09 passes of March 1989 named on the page. One second is shown every 10 s. Public data from NOAA NCEI, decoded by AFRL Table 19.", "Columns: UT, CGM latitude, MLT, geodetic latitude and longitude, 1 if the second lies in our South Atlantic box, then counts in each electron channel: 30 keV down to 949 eV | 949 eV down to 30 eV. Which of these look like precipitation is our judgment."] parts = [read_j4(os.path.join(folder, "j4_1989", x), 1989) for x in ("j4f0989072.gz", "j4f0989073.gz")] t, lat, mlt, ele, gl, go = [np.r_[parts[0][i], parts[1][i]] if i != 3 else np.vstack([parts[0][3], parts[1][3]]) for i in range(6)] box = saa_box(gl, go) for sat, a, b in DUMPS_1989: t0 = (dt.datetime.fromisoformat(a) - EPOCH_OLD).total_seconds() t1 = (dt.datetime.fromisoformat(b) - EPOCH_OLD).total_seconds() out += ["", f"== {sat} {a} to {b}", "UT cgm mlt glat glon box | 30k 20k 14k 9.4k 6.5k 4.4k 3k 2k 1.4k 949 | 949 646 440 300 204 139 95 65 44 30"] for i in np.where((t >= t0) & (t <= t1))[0][::10]: e = np.nan_to_num(ele[i], nan=-1.0) tm = EPOCH_OLD + dt.timedelta(seconds=float(t[i])) out.append(tm.strftime("%H:%M:%S") + f" {lat[i]:7.2f} {mlt[i]:5.2f} {gl[i]:6.1f} {go[i]:6.1f} {int(box[i])} | " + " ".join(f"{int(x):5d}" for x in e[:10]) + " | " + " ".join(f"{int(x):5d}" for x in e[10:])) with open(path, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(out) + "\n") def main(): folder = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, "auroral_data") os.makedirs(folder, exist_ok=True) get_inputs(folder) ssj_dir = os.path.join(folder, "ssj_2024-05") tables = load_ssj(ssj_dir) kp = load_gfz(os.path.join(folder, "gfz", "kp.json"), "Kp") hp = load_gfz(os.path.join(folder, "gfz", "hp30.json"), "Hp30") dst = load_dst_csv(os.path.join(folder, "kyoto", "dst_202405.csv"), EPOCH) sym = {} for row in csv.reader(open(os.path.join(folder, "kyoto", "symh_202405.csv"), encoding="utf-8")): sym[row[0][:16]] = float(row[1]) symmax, symmin = max(sym.items(), key=lambda x: x[1]), min(sym.items(), key=lambda x: x[1]) rows, control, soft_control = analyse_2024(tables, kp, hp, dst) for c in rows: c["symh"] = sym.get(c["ut"][:16].replace(" ", "T")) assert symmin[0] == "2024-05-11T02:14" main_ = [c for c in rows if SC <= c["t_edge"] <= WINDOW_END and 0 <= c["mlt"] < 6] after = [c for c in rows if c["t_edge"] > WINDOW_END and 0 <= c["mlt"] < 6] quiet = [c for c in rows if c["t_edge"] < SC and 0 <= c["mlt"] < 6] ion_rows, frame = analyse_ssies(os.path.join(folder, "ssies"), tables) pairs, pairs_soft = pair_ion(ion_rows, main_) ion_main = [c["ion"] for c in main_ if c.get("ion")] ion_quiet = [q for q in ion_rows if q["t"] < SC and 0 <= q["mlt"] < 6 and q["edge_300"] is not None] edr = parse_edr(ssj_dir) ssusi_rows, ssusi_low = analyse_ssusi(os.path.join(folder, "ssusi")) old_rows, old_summ = analyse_old(folder) mlt_chk = {} for sat, T in tables.items(): d = [] for i in np.arange(0, len(T["t"]), 120): if 40 <= abs(T["cgmlat"][i]) <= 60: d.append(((T["mlt_file"][i] - dipole_mlt(T["t"][i], T["glat"][i], T["glon"][i]) + 12) % 24) - 12) mlt_chk[sat] = dict(n=len(d), median=round(float(np.median(d)), 3), p95_abs=round(float(np.percentile(np.abs(d), 95)), 3)) def count(k): return sum(1 for c in main_ if c[k] is not None and c[k] < 50) def is_1856(c): return c["ut"].startswith("2024-05-10 18:5") and c["sat"] == "F18" def count_wo(k): return sum(1 for c in main_ if c[k] is not None and c[k] < 50 and not is_1856(c)) def lowest_of(k): v = [c[k] for c in main_ if c[k] is not None] return rnd(min(v)) if v else None def dst_at_lat(lat, line): eb = 8e17 * math.cos(math.radians(lat)) ** 6 return round(-(0.11 * eb - 4.7e14) / 4e13) if line == "all" else round(-(0.17 * (eb - 1.4e16)) / 4e13) rule_rows = [c for c in main_ if c["edge_1e10"] < 50 and c["edge_3e10"] < 50] g18 = np.array(G["F18"]) one = 1.0 / (g18[:9] * DT_J5) * CH_E[:9] * CH_DE[:9] from_1921 = [c["edge_3e10"] for c in main_ if c["t_edge"] >= (dt.datetime(2024, 5, 10, 19, 0) - EPOCH).total_seconds()] eb50 = 8e17 * math.cos(math.radians(50)) ** 6 numbers = dict( about="Our analysis of public data. Every definition is ours; the paper's is unread. See the docstring of auroral_edges.py and the hosted rules. Fluxes in eV/cm2/s/sr; latitudes in degrees of |CGM| at 110 km unless named.", main_phase=dict(interval="17:05 UT 10 May to 02:14 UT 11 May 2024 (amendment 6)", sector="MLT 00-06 at the edge", energies="edges at 1 keV and above", n_crossings=len(main_), below_50={k: count("edge_" + k) for k in ("1e10", "3e10", "4e10", "6e10", "1e11", "2e11")}, below_50_without_1856={k: count_wo("edge_" + k) for k in ("1e10", "3e10", "4e10", "6e10", "1e11", "2e11")}, lowest={k: rnd(min(c["edge_" + k] for c in main_)) for k in ("1e10", "3e10", "4e10", "6e10", "1e11", "2e11")}, n_at_file_floor_1e10=sum(int(c["at_floor"]) for c in main_), reading_rule_rows_below_50_at_1e10_and_3e10=len(rule_rows), counted_by_inspection=dict(rows=["F18 N 20:41", "F18 N 22:23", "F18 S 22:42", "F18 N 01:47 by its arc at 48.9", "F17 S 02:12"], n=5, not_counted=["F18 N 18:56: below about 50.5 deg the counts are flat", "F18 N 00:04: channels at 13.9 keV and above give all the flux at the edge; soft electrons only"]), median_edge_3e10_from_1921=rnd(float(np.median(from_1921))), n_from_1921=len(from_1921), one_count_flux_f18=dict(channel_30kev=float(f"{one[0]:.3g}"), nine_channels=float(f"{one.sum():.3g}"))), soft_band=dict(rule="amendment 5, after the review, not blind", below_50={k: count("soft_" + k) for k in SOFT_LADDER}, below_50_without_1856={k: count_wo("soft_" + k) for k in SOFT_LADDER}, lowest={k: lowest_of("soft_" + k) for k in SOFT_LADDER}, below_50_by_satellite={s: sum(1 for c in main_ if c["sat"] == s and c["soft_1e9"] is not None and c["soft_1e9"] < 50) for s in ("F16", "F17", "F18")}, control_40_45_deg=soft_control, quiet_soft_1e9=dict(n=sum(1 for c in quiet if c["soft_1e9"] is not None), lowest=rnd(min(c["soft_1e9"] for c in quiet if c["soft_1e9"] is not None)), highest=rnd(max(c["soft_1e9"] for c in quiet if c["soft_1e9"] is not None))), ion_minus_soft_1e9=dict(within_2_deg=sum(1 for x in pairs_soft if abs(x) <= 2), ion_lower_by_over_2=sum(1 for x in pairs_soft if x < -2), ion_higher_by_over_2=sum(1 for x in pairs_soft if x > 2))), after_window=[dict(sat=c["sat"], hemi=c["hemi"], ut=c["ut"], mlt=rnd(c["mlt"]), edge_3e10=rnd(c["edge_3e10"]), edge_4e10=rnd(c["edge_4e10"]), edge_2e11=rnd(c["edge_2e11"]), dst=c["dst"]) for c in after], quiet=dict(n=len(quiet), edge_1e10_min=rnd(min(c["edge_1e10"] for c in quiet)), edge_1e10_median=rnd(float(np.median([c["edge_1e10"] for c in quiet]))), edge_1e10_max=rnd(max(c["edge_1e10"] for c in quiet)), edge_3e10_min=rnd(min(c["edge_3e10"] for c in quiet)), edge_3e10_max=rnd(max(c["edge_3e10"] for c in quiet)), latest_ut=max(c["ut"] for c in quiet)), control_40_45_deg=control, file_floor=dict(lowest_abs_cgm_held={sat: rnd(float(np.min(np.abs(T["cgmlat"])))) for sat, T in sorted(tables.items())}), ion_drift=dict(frame_test=frame, n_pairs=len(pairs), below_50=sum(1 for q in ion_main if q["edge_300"] < 50), n_crossings=len(ion_main), lowest_edge_300=min(q["edge_300"] for q in ion_main), ion_minus_electron_3e10=dict(median=rnd(float(np.median(pairs))), within_2_deg=sum(1 for x in pairs if abs(x) <= 2), ion_lower_by_over_2=sum(1 for x in pairs if x < -2), ion_higher_by_over_2=sum(1 for x in pairs if x > 2)), quiet_lowest_edge_300=min(q["edge_300"] for q in ion_quiet)), routine_product_floors=dict(noaa_edr_marks=len(edr), noaa_edr_lowest_abs_cgm=sorted(round(abs(r["cgmlat"]), 4) for r in edr)[:4], ssusi_boundary_lowest_any_mlt=ssusi_low, ssusi_map_lowest_range_00_06=[min(r["map_lowest_00_06"] for r in ssusi_rows if r["map_lowest_00_06"] is not None), max(r["map_lowest_00_06"] for r in ssusi_rows if r["map_lowest_00_06"] is not None)], ssusi_by_file=ssusi_rows), fits=dict(gussenhoven_kp9_by_bin={str(h): round(GUSS_L0[h] + GUSS_A[h] * 9, 2) for h in (22, 23, 0, 1, 4, 5, 6, 7)}, dst_at_midnight_lat={str(x): dict(all_storms=dst_at_lat(x, "all"), march_1989_line=dst_at_lat(x, "1989")) for x in (44, 45, 48, 50)}, sector_3p5_to_4p7_minus_midnight_kp9=dict(gussenhoven=[round(guss(3.5, 9.0) - guss(0.0, 9.0), 1), round(guss(4.7, 9.0) - guss(0.0, 9.0), 1)], troyer=[round(troyer(3.5, 9.0) - troyer(0.0, 9.0), 1), round(troyer(4.7, 9.0) - troyer(0.0, 9.0), 1)]), by_mlt=[dict(mlt=m, g83_kp9=round(guss(m, 9.0), 1), t25_kp9=round(troyer(m, 9.0), 1), t25_hp30_10_33=round(troyer(m, 10.333), 1), t25_hp30_11_33=round(troyer(m, 11.333), 1)) for m in (0.5, 1.5, 2.5, 3.5, 4.5, 5.5)], yokoyama_by_dst={str(d): dict(all_storms=round(yokoyama_all(d), 1), march_1989_line=round(yokoyama_1989(d), 1)) for d in (-100, -143, -157, -180, -200, -277, -300, -339, -390, -406, -422, -589)}, dst_at_50_deg=dict(all_storms=round(-(0.11 * eb50 - 4.7e14) / 4e13), march_1989_line=round(-(0.17 * (eb50 - 1.4e16)) / 4e13)), yokoyama_at_zero_dst_deg=round(math.degrees(math.acos(math.sqrt((4.3e15 / 8e17) ** (1 / 3)))), 1)), field_lines=dict(L={str(x): round(lval(x), 2) for x in (29.8, 35.5, 40.1, 44.4, 45, 50, 55, 65)}, ilat_to_mlat_at_400km={str(x): round(ilat_to_mlat(x), 1) for x in (29.8, 35.5, 30.8, 36.5)}), indices=dict(symh_max=list(symmax), symh_min=list(symmin), hp30_max=max(v for _, v in hp), kp_max=max(v for _, v in kp), dst_hourly=[[(EPOCH + dt.timedelta(seconds=t)).strftime("%Y-%m-%dT%H:%M:%S"), v] for t, v in dst]), mlt_field_minus_centred_dipole_40_60_deg=mlt_chk, calibration_against_nasa_f18_2014=calibration(os.path.join(folder, "f18-ssj-2014-12-01-sample.csv")), other_storms=old_summ, superdarn_deposit_all_sectors=superdarn(os.path.join(folder, "SuperDARN-csv.zip")), ) with open(os.path.join(HERE, "auroral-numbers.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(numbers, f, indent=1) f.write("\n") with open(os.path.join(HERE, "auroral-main-phase.csv"), "w", encoding="utf-8", newline="\n") as f: f.write("sat,hemi,ut_edge_1e10,mlt,edge_1e10,edge_3e10,edge_4e10,edge_2e11,lowest_lat_in_file,edge_1e10_at_file_floor,dst_hour_nT,symh_nT,kp,hp30,gussenhoven83_kp,troyer25_hp30,yokoyama98_all,yokoyama98_1989,ion_ut,ion_mlt,ion_edge_300,ion_edge_500,ion_edge_1000,ion_vmax_11s,edge_6e10,edge_1e11,ut_edge_3e10,mlt_edge_3e10,soft_1e9,soft_3e9,soft_1e10,share_13p9kev_at_3e10_edge,share_13p9kev_next_2deg,peak_flux_next_2deg,floor_flux_median,floor_frac_1e10,floor_frac_2e10,floor_frac_3e10,floor_frac_4e10\n") for c in main_: q = c.get("ion") or {} f.write(",".join([c["sat"], c["hemi"], c["ut"], fmt(c["mlt"]), fmt(c["edge_1e10"]), fmt(c["edge_3e10"]), fmt(c["edge_4e10"]), fmt(c["edge_2e11"]), fmt(c["floor"]), str(int(c["at_floor"])), fmt(c["dst"], 0), fmt(c["symh"], 0), fmt(c["kp"], 3), fmt(c["hp30"], 3), fmt(c.get("g83"), 1), fmt(c.get("tr25_hp"), 1), fmt(c.get("yo98_all"), 1), fmt(c.get("yo98_89"), 1), q.get("ut", ""), fmt(q.get("mlt")), fmt(q.get("edge_300")), fmt(q.get("edge_500")), fmt(q.get("edge_1000")), fmt(q.get("vmax"), 0), fmt(c["edge_6e10"]), fmt(c["edge_1e11"]), c.get("ut_3e10", ""), fmt(c.get("mlt_3e10")), fmt(c["soft_1e9"]), fmt(c["soft_3e9"]), fmt(c["soft_1e10"]), fmt(c.get("top_share_edge")), fmt(c.get("top_share_2deg")), f'{c.get("peak_next_2deg", 0):.3g}', f'{c["floor_median"]:.3g}', fmt(c["floor_frac_1e10"]), fmt(c["floor_frac_2e10"]), fmt(c["floor_frac_3e10"]), fmt(c["floor_frac_4e10"])]) + "\n") with open(os.path.join(HERE, "auroral-crossings.csv"), "w", encoding="utf-8", newline="\n") as f: f.write("sat,hemi,ut_edge_1e10,mlt,edge_1e10,edge_3e10,edge_4e10,edge_2e11,ut_edge_2e11,mlt_edge_2e11,edge_2e9_not_counted,edge_6e9_not_counted,lowest_any_1e10,lowest_lat_in_file,edge_1e10_at_file_floor,dst_hour_nT,symh_nT,kp,hp30,gussenhoven83_kp,troyer25_kp,troyer25_hp30,yokoyama98_all,yokoyama98_1989,edge_all_energies,edge_coadd5,edge_coadd21,edge_persist1,edge_persist3,edge_6e10,edge_1e11,ut_edge_3e10,mlt_edge_3e10,soft_1e9,soft_3e9,soft_1e10\n") for r in rows: f.write(",".join([r["sat"], r["hemi"], r["ut"], fmt(r["mlt"]), fmt(r["edge_1e10"]), fmt(r["edge_3e10"]), fmt(r["edge_4e10"]), fmt(r["edge_2e11"]), r["ut_2e11"] or "", fmt(r["mlt_2e11"]), fmt(r["edge_2e9"]), fmt(r["edge_6e9"]), fmt(r["lowest_any"]), fmt(r["floor"]), str(int(r["at_floor"])), fmt(r["dst"], 0), fmt(r["symh"], 0), fmt(r["kp"], 3), fmt(r["hp30"], 3), fmt(r.get("g83"), 1), fmt(r.get("tr25_kp"), 1), fmt(r.get("tr25_hp"), 1), fmt(r.get("yo98_all"), 1), fmt(r.get("yo98_89"), 1), fmt(r["edge_all_energies"]), fmt(r["edge_coadd5"]), fmt(r["edge_coadd21"]), fmt(r["edge_persist1"]), fmt(r["edge_persist3"]), fmt(r["edge_6e10"]), fmt(r["edge_1e11"]), r.get("ut_3e10", ""), fmt(r.get("mlt_3e10")), fmt(r["soft_1e9"]), fmt(r["soft_3e9"]), fmt(r["soft_1e10"])]) + "\n") with open(os.path.join(HERE, "auroral-other-storms.csv"), "w", encoding="utf-8", newline="\n") as f: keys = ["storm", "sat", "hemi", "ut", "mlt", "edge_1e10", "edge_3e10", "edge_4e10", "edge_2e11", "floor", "dst", "edge_3e10_box_off", "edge_4e10_box_off", "soft_1e9", "soft_3e9"] f.write(",".join(keys) + "\n") for r in old_rows: f.write(",".join("" if r.get(k) is None else str(r[k]) for k in keys) + "\n") dump_counts(tables, os.path.join(HERE, "auroral-raw-counts.txt")) dump_counts_1989(folder, os.path.join(HERE, "auroral-raw-counts-1989.txt")) print(json.dumps(numbers["main_phase"], indent=1)) print(json.dumps({k: v for k, v in numbers["soft_band"].items() if k != "control_40_45_deg"}, indent=1)) if __name__ == "__main__": main()