#!/usr/bin/env python3 """RULES_C_low_latitude_aef.txt: the authors' own BGL and PRL data (Mendeley doi:10.17632/mfb55f2wwd.2, CC BY 4.0). Usage: python3 -I c_low_latitude.py EXTRACTED_DIR FW2023_24_DIR OUT_DIR Needs numpy and pandas. Reads the data files as data. Writes OUT_DIR/C_low_latitude.json and OUT_DIR/C_daily_means.csv. """ import json import os import sys import numpy as np import pandas as pd sys.stdout.reconfigure(encoding="utf-8") EX, FW, OUT = sys.argv[1], sys.argv[2], sys.argv[3] BASE = os.path.join(EX, "AEF_VLF_Data_10May2024-Geomagnetic-Storm") DAYS = ["05082024", "05092024", "05102024", "05112024", "05122024", "05132024", "05142024"] res = {"C0": {}, "C1": {}, "C3": {}, "C4": {}, "C5": {}} def day_of(tag): return pd.Timestamp(f"{tag[4:8]}-{tag[0:2]}-{tag[2:4]}") # ---------- C1: 5-min means in file time ---------- def prl_5min(tag): p = os.path.join(BASE, "EFM-Data", "PRL", f"skbu-{tag}.efm") df = pd.read_csv(p, header=None, names=["t", "v", "flag"], dtype={"t": str}, on_bad_lines="skip") n_all = len(df) df = df[df["flag"] == 0] sec = df["t"].str.slice(0, 2).astype(int) * 3600 + df["t"].str.slice(3, 5).astype(int) * 60 + df["t"].str.slice(6, 8).astype(int) bins = (sec // 300).astype(int) m = df.groupby(bins)["v"].mean() idx = day_of(tag) + pd.to_timedelta(m.index * 300, unit="s") return pd.Series(m.values, index=idx), n_all, n_all - len(df) def bgl_5min(tag): p = os.path.join(BASE, "EFM-Data", "BGL", f"{tag}.txt") df = pd.read_csv(p, sep=r"\s+", header=None, names=["i", "v"]) idx = day_of(tag) + pd.to_timedelta(df["i"] * 60, unit="s") s = pd.Series(df["v"].values, index=idx) return s.resample("5min").mean() prl_parts, bgl_parts, dropped = [], [], {} for tag in DAYS: s, n, nd = prl_5min(tag) prl_parts.append(s) dropped[tag] = [int(n), int(nd)] bgl_parts.append(bgl_5min(tag)) prl_raw = pd.concat(prl_parts).sort_index() bgl_raw = pd.concat(bgl_parts).sort_index() res["C1"]["prl_samples_and_flagged_per_file"] = dropped # ---------- C0: calibration against the paper's Fig. 4 ---------- FIGPATH = os.path.join(OUT, "E_fig4_curves.json") fig = json.load(open(FIGPATH, encoding="utf-8")) if os.path.exists(FIGPATH) else None if fig is None: print("E_fig4_curves.json not found: using the calibration stored below") def fig_series(name): """Fig. 4's points, indexed by the start of the 5-min interval each one shows. The figure plots each 5-min mean at the END of its interval (its first point of a day is at 00:05), so a point at t is the mean of [t - 5 min, t), which is our data bin labelled t - 5 min (RULES_C_amendment_alignment.txt; the first run compared it with the bin after).""" tv = fig[name] t = [pd.Timestamp("2024-05-01") + pd.to_timedelta((d - 1) * 86400, unit="s") for d, _ in tv] s = pd.Series([v for _, v in tv], index=pd.DatetimeIndex(t)) s = s.groupby(s.index.round("5min")).mean() s.index = s.index - pd.Timedelta(minutes=5) return s # E_fig4_curves.json is made by e_figures.py from the preprint PDF, which only the site's owner could download (SSRN # refused our client). Without it, the calibration found on 2026-11-15 (after the alignment correction) is used: file # clock India time, UT + 5.5 h, at both stations; PRL figure = -0.073 + 999.954 x kV/m, BGL figure = 120.015 + 1000.019 x # file value, both r = 1.000. C3's ranks depend only on the clock. STORED = {"PRL": (1.0, "file=IST(UT+5.5h)", pd.Timedelta(hours=-5.5), -0.07323, 999.954346), "BGL": (1.0, "file=IST(UT+5.5h)", pd.Timedelta(hours=-5.5), 120.015139, 1000.018868)} cal = {} for name, raw in (("PRL", prl_raw), ("BGL", bgl_raw)): if fig is None: best = STORED[name] cal[f"{name}_chosen"] = best[1] + " (stored calibration)" if best[0] < 0.8: cal[f"{name}_STOP"] = "r < 0.8 for both clocks" r = raw.copy() r.index = r.index + best[2] cal[f"{name}_series"] = (best[3] + best[4] * r) continue f = fig_series(name) best = None for label, shift in (("file=UT", pd.Timedelta(0)), ("file=IST(UT+5.5h)", pd.Timedelta(hours=-5.5))): r = raw.copy() r.index = r.index + shift j = pd.concat([f.rename("fig"), r.rename("dat")], axis=1).dropna() j = j["2024-05-09 00:00":"2024-05-12 16:00"] if len(j) < 50: cal[f"{name} {label}"] = {"n": int(len(j))} continue b, a = np.polyfit(j["dat"], j["fig"], 1) rr = float(np.corrcoef(j["dat"], j["fig"])[0, 1]) resid = j["fig"] - (a + b * j["dat"]) cal[f"{name} {label}"] = {"n": int(len(j)), "r": round(rr, 4), "a": round(float(a), 6), "b": round(float(b), 6), "rms_resid_Vm": round(float(np.sqrt((resid ** 2).mean())), 2)} if best is None or rr > best[0]: best = (rr, label, shift, a, b) cal[f"{name}_chosen"] = best[1] if best[0] < 0.8: cal[f"{name}_STOP"] = "r < 0.8 for both clocks" r = raw.copy() r.index = r.index + best[2] cal[f"{name}_series"] = (best[3] + best[4] * r) res["C0"] = {k: v for k, v in cal.items() if not k.endswith("_series")} prl = cal["PRL_series"] bgl = cal["BGL_series"] # PRL 5-min means in UT on the paper's scale (V/m), for the page's chart; derived from the authors' CC BY 4.0 data with open(os.path.join(OUT, "C_prl_5min.csv"), "w", encoding="utf-8", newline="\n") as fh: fh.write("utc,pg_Vm\n") for t, v in prl.items(): fh.write(f"{t:%Y-%m-%d %H:%M},{v:.1f}\n") # ---------- C2: crude screen ---------- def screen(s): bad_hours = s[(s < 0) | (s > 1000)].index.floor("1h").unique() return s[~s.index.floor("1h").isin(bad_hours)] # ---------- C3: test ---------- def stats(s, d): pre = s[d + pd.Timedelta(minutes=45): d + pd.Timedelta(hours=2, minutes=40)] post = s[d + pd.Timedelta(hours=2, minutes=45): d + pd.Timedelta(hours=5, minutes=40)] if len(pre.dropna()) < 0.8 * 24 or len(post.dropna()) < 0.8 * 36: return None return {"S1_level_change": round(float(post.mean() - pre.mean()), 1), "S2_post_sd": round(float(post.std()), 1), "S3_sd_change": round(float(post.std() - pre.std()), 1), "pre_mean": round(float(pre.mean()), 1), "post_mean": round(float(post.mean()), 1)} for scr_label, f in (("all", lambda s: s), ("screened", screen)): for name, s0 in (("PRL", prl), ("BGL", bgl)): s = f(s0) table = {} for tag in DAYS: d = day_of(tag) table[str(d.date())] = stats(s, d) ranks = {} for k in ("S1_level_change", "S2_post_sd", "S3_sd_change"): vals = {dd: v[k] for dd, v in table.items() if v} if "2024-05-11" in vals: order = sorted(vals, key=lambda x: -vals[x]) ranks[k] = [order.index("2024-05-11") + 1, len(order)] res["C3"][f"{name}_{scr_label}"] = {"days": table, "rank_of_11May": ranks} # ---------- C4: daily means ---------- rows = [] for scr_label, f in (("all", lambda s: s), ("screened", screen)): for name, s0 in (("PRL", prl), ("BGL", bgl)): s = f(s0) dm = s.groupby(s.index.floor("1D")).agg(["mean", "count"]) for d, r in dm.iterrows(): rows.append({"station": name, "screen": scr_label, "day": str(d.date()), "mean_Vm": round(float(r["mean"]), 1), "n5min": int(r["count"])}) m = {str(d.date()): float(r["mean"]) for d, r in dm.iterrows()} if all(k in m for k in ("2024-05-09", "2024-05-10", "2024-05-11")): res["C4"][f"{name}_{scr_label}_11May_vs_mean_9_10_pct"] = round(100 * (m["2024-05-11"] / ((m["2024-05-09"] + m["2024-05-10"]) / 2) - 1), 1) pd.DataFrame(rows).to_csv(os.path.join(OUT, "C_daily_means.csv"), index=False, lineterminator="\n") res["C4"]["daily_means"] = rows # authors' May 2024 fair-weather hourly means (IST hours 1..24 -> UT) for name in ("PRL", "BGL"): p = os.path.join(FW, "EFM100-Data_FairWeather_2023-24", name, "Monthly", f"{name}-May-2024-FW-AEF.txt") vals = [] for line in open(p, encoding="utf-8", errors="replace"): q = line.split() if q and q[0].isdigit(): vals.append((int(q[0]), float(q[1]), float(q[2]))) res["C4"][f"{name}_FW_May2024_mean_of_hourly"] = round(sum(v for _, v, _ in vals) / len(vals), 1) res["C4"][f"{name}_FW_May2024_median_stderr"] = float(np.median([e for _, _, e in vals])) # ---------- C5: VLF ---------- vl = {} for tag in ("10052024", "11052024", "12052024"): p = os.path.join(BASE, "VLF-Sferics", f"sph-{tag}-7-9khz.txt") df = pd.read_csv(p, sep=r"\s+", comment="#", header=None, names=["h", "a7", "a9"]) df["m"] = (df["h"] * 60).round().astype(int) vl[tag] = df.set_index("m")[["a7", "a9"]] common = vl["10052024"].index.intersection(vl["11052024"].index).intersection(vl["12052024"].index) res["C5"]["common_minutes"] = int(len(common)) for tag, df in vl.items(): res["C5"][f"mean_dB_{tag}"] = {c: round(float(df.loc[common, c].mean()), 2) for c in ("a7", "a9")} d11 = vl["11052024"].reindex(range(1440)) for c in ("a7", "a9"): run = d11[c].rolling(30, min_periods=24).mean() i = int(run.idxmax()) ex = run.copy() ex[(ex.index >= 5 * 60) & (ex.index < 9 * 60 + 30)] = np.nan # windows ending inside 05-09 UT excluded j = int(ex.idxmax()) res["C5"][f"{c}_11May_max30_end_UT_h"] = {"all": round(i / 60, 2), "excl_05_09": round(j / 60, 2), "values_dB": [round(float(run[i]), 2), round(float(ex[j]), 2)]} json.dump(res, open(os.path.join(OUT, "C_low_latitude.json"), "w", encoding="utf-8", newline="\n"), indent=1, default=str) print(json.dumps(res, indent=1, default=str)[:15000])