#!/usr/bin/env python3 """Draw matched storm-free placebo starts for note 002's storms (rules: RULES_placebo.txt). Usage: python3 -I select_placebo.py [--min-sep-days N] [--report-only] For each storm, in inventory order: candidates = 3-hour bin starts t with the same UT hour as the storm's t0, no Kp >= 5- in any bin starting in [t - 72 h, t + 168 h), t within 2014-01-01 .. 2025-12-24 21:00, and |t - t0| <= W days, W = 30, then 45, 60 if none; not closer than min-sep days (default 3) to a placebo already drawn. One is drawn uniformly with random.Random(20261106). Pseudo storm start = t - storm_to_t0_h of the matched storm (for the quiet-day exclusion). Quiet days: the note's rule (GFZ Q1-Q10, any flag; |noon - t| <= 15 d; calendar dates from date(start - 1 d) to date(t + 5 d) excluded; nearest first; ties: better GFZ rank, then later date; at most 10). Also writes the union of UT days needed (placebos and all 119 storms) to out_dates.txt. """ import csv import datetime as dt import os import random import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import kp_lib # noqa: E402 SEED = 20261106 WINDOWS = (30, 45, 60) LO = dt.datetime(2014, 1, 1) HI = dt.datetime(2025, 12, 24, 21) P = lambda s: dt.datetime.strptime(s, "%Y-%m-%dT%H:%MZ") # noqa: E731 def select_quiet(qdays, t0, start): lo = (start - dt.timedelta(days=1)).date() hi = (t0 + dt.timedelta(days=5)).date() c = [] for d, (rank, flag) in qdays.items(): mid = dt.datetime(d.year, d.month, d.day, 12) off = (mid - t0).total_seconds() / 86400.0 if abs(off) > 15 + 1e-9: continue if lo <= d <= hi: continue c.append((abs(off), int(rank[1:]), -d.toordinal(), d, off, rank, flag)) c.sort() return [(x[3], x[4], x[5], x[6]) for x in c[:10]] def days_between(a, b): """UT dates whose files are needed to cover [a, b].""" out = [] d = a.date() while d <= b.date(): out.append(d) d += dt.timedelta(days=1) return out def main(): kp_path, qd_dir, inv_path, qsel_path, out_csv, out_dates = sys.argv[1:7] min_sep = 3.0 if "--min-sep-days" in sys.argv: min_sep = float(sys.argv[sys.argv.index("--min-sep-days") + 1]) report_only = "--report-only" in sys.argv ts, ks, _ = kp_lib.load_kp(kp_path) qdays, _ = kp_lib.load_qdays(qd_dir, range(2013, 2027)) pre = [0] for k in ks: pre.append(pre[-1] + (1 if k >= kp_lib.KP5M else 0)) elig = [i for i, t in enumerate(ts) if LO <= t <= HI and i - 24 >= 0 and i + 56 <= len(ks) and pre[i + 56] - pre[i - 24] == 0] with open(inv_path, encoding="utf-8", newline="") as f: inv = list(csv.DictReader(f)) with open(qsel_path, encoding="utf-8", newline="") as f: qsel = list(csv.DictReader(f)) rng = random.Random(SEED) drawn = [] rows = [] for r in inv: t0 = P(r["t0_utc"]) pick = None used_w = None for w in WINDOWS: cands = [ts[i] for i in elig if ts[i].hour == t0.hour and abs((ts[i] - t0).total_seconds()) <= w * 86400 and all(abs((ts[i] - d).total_seconds()) >= min_sep * 86400 for d in drawn)] if cands: pick = cands[rng.randrange(len(cands))] used_w = w break if pick is None: rows.append({"storm_id": r["storm_id"], "storm_t0_utc": r["t0_utc"], "placebo_t0_utc": "", "window_days": "", "n_candidates": 0}) continue drawn.append(pick) start = pick - dt.timedelta(hours=float(r["storm_to_t0_h"])) q = select_quiet(qdays, pick, start) rows.append({"storm_id": r["storm_id"], "storm_t0_utc": r["t0_utc"], "placebo_t0_utc": pick.strftime("%Y-%m-%dT%H:%MZ"), "pseudo_start_utc": start.strftime("%Y-%m-%dT%H:%MZ"), "offset_days": round((pick - t0).total_seconds() / 86400.0, 3), "window_days": used_w, "n_candidates": len(cands), "storm_window_h": r["window_h"], "n_quiet": len(q), "quiet_days": ";".join(x[0].isoformat() for x in q)}) n_ok = sum(1 for x in rows if x["placebo_t0_utc"]) # union of days needed need_p, need_s = set(), set() for x in rows: if not x["placebo_t0_utc"]: continue t = P(x["placebo_t0_utc"]) need_p.update(days_between(t - dt.timedelta(hours=24), t + dt.timedelta(hours=168))) need_p.update(dt.date.fromisoformat(d) for d in x["quiet_days"].split(";") if d) for r in inv: t0 = P(r["t0_utc"]) need_s.update(days_between(t0 - dt.timedelta(hours=24), t0 + dt.timedelta(hours=float(r["window_h"])))) for q in qsel: need_s.add(dt.date.fromisoformat(q["quiet_date"])) union = need_p | need_s print("placebos drawn: %d of %d (min separation %.0f d)" % (n_ok, len(inv), min_sep)) print("windows used:", {w: sum(1 for x in rows if x.get("window_days") == w) for w in WINDOWS}) print("days needed: placebos %d, storms %d, union %d (of 4383)" % (len(need_p), len(need_s), len(union))) print("approx size at 0.34 MB/file: %.2f GB" % (len(union) * 0.34 / 1024)) if report_only: return keys = ["storm_id", "storm_t0_utc", "placebo_t0_utc", "pseudo_start_utc", "offset_days", "window_days", "n_candidates", "storm_window_h", "n_quiet", "quiet_days"] with open(out_csv, "w", encoding="utf-8", newline="\n") as f: w = csv.DictWriter(f, fieldnames=keys, lineterminator="\n") w.writeheader() for x in rows: w.writerow({k: x.get(k, "") for k in keys}) with open(out_dates, "w", encoding="utf-8", newline="\n") as f: for d in sorted(union): f.write(d.isoformat() + "\n") if __name__ == "__main__": main()