#!/usr/bin/env python3 """Reproduce note 002's headline numbers from its own Drive CSVs (read as data). Usage: python3 -I reproduce_note.py """ import csv import json import os import statistics import sys def read(path): with open(path, encoding="utf-8", newline="") as f: return list(csv.DictReader(f)) def km(times, events): """Product-limit estimate. Returns list of (t, S after t, n_at_risk, d).""" data = sorted(zip(times, events)) ts = sorted(set(t for t, e in data if e)) s = 1.0 out = [] for t in ts: n = sum(1 for x, _ in data if x >= t) d = sum(1 for x, e in data if e and x == t) s *= 1.0 - d / n out.append((t, s, n, d)) return out def surv_at(curve, t): s = 1.0 for x, sv, _, _ in curve: if x <= t: s = sv else: break return s def km_median(curve): for x, sv, _, _ in curve: if sv <= 0.5: return x return None def pct(vals, q): """Linear-interpolation percentile (numpy's default).""" v = sorted(vals) if not v: return None k = (len(v) - 1) * q f = int(k) c = min(f + 1, len(v) - 1) return v[f] + (v[c] - v[f]) * (k - f) def main(): d, out_path = sys.argv[1], sys.argv[2] inv = read(os.path.join(d, "storm_inventory.csv")) rec = read(os.path.join(d, "recovery_times.csv")) kms = {r["band"]: r for r in read(os.path.join(d, "km_summary.csv"))} kmc = read(os.path.join(d, "km_curves.csv")) sea = read(os.path.join(d, "sea_strip.csv")) res = {} # 1. inventory res["n_storms"] = len(inv) res["n_merge"] = sum(1 for r in inv if float(r["merge_count"] or 0) > 0) res["n_censor_time_filled"] = sum(1 for r in inv if r["censor_time_utc"].strip()) phases = {} for r in inv: phases[r["solar_phase"]] = phases.get(r["solar_phase"], 0) + 1 res["phases"] = phases res["storm_to_t0_h_median"] = statistics.median(float(r["storm_to_t0_h"]) for r in inv) res["window_h_lt168"] = sum(1 for r in inv if float(r["window_h"]) < 168) t0_hours = {} for r in inv: h = int(r["t0_utc"][11:13]) t0_hours[h] = t0_hours.get(h, 0) + 1 res["t0_ut_hours"] = dict(sorted(t0_hours.items())) res["kp_peak_codes"] = {} for r in inv: res["kp_peak_codes"][r["kp_peak_code"]] = res["kp_peak_codes"].get(r["kp_peak_code"], 0) + 1 # 2-3. KM per band bands = {} for b in ["N30", "S30", "NS30", "N50", "S50", "NS50", "N70", "S70", "NS70"]: rows = [r for r in rec if r["band"] == b] t = [float(r["T_rec_h"]) for r in rows] e = [r["recovered"] == "TRUE" for r in rows] curve = km(t, e) cens = {} for r in rows: if r["recovered"] != "TRUE": cens[r["censor_reason"]] = cens.get(r["censor_reason"], 0) + 1 info = { "n": len(rows), "recovered": sum(e), "censor_reasons": cens, "n_Trec0": sum(1 for x, ev in zip(t, e) if ev and x == 0), "km_median_h": km_median(curve), "S": {str(h): round(surv_at(curve, h), 4) for h in (0, 12, 24, 48, 72, 96, 120, 144, 156, 167, 168)}, "note_km_summary": {k: kms[b][k] for k in ("km_median_T_rec_h", "still_disturbed_24h", "still_disturbed_48h", "still_disturbed_72h", "still_disturbed_96h", "n_recovered", "n_in_band_at_t0")}, } # observed (not extrapolated): storms followed >= h and still out at h for h in (96, 120, 144): known_out = sum(1 for x, ev in zip(t, e) if x > h) # recovered after h, or censored after h unknown = sum(1 for x, ev in zip(t, e) if (not ev) and x <= h) info["observed_still_out_at_%d" % h] = known_out info["censored_before_%d" % h] = unknown # compare curve with km_curves.csv ref = [(float(r["hours_after_t0"]), float(r["fraction_still_disturbed"])) for r in kmc if r["band"] == b] maxdiff = 0.0 for x, sv in ref: maxdiff = max(maxdiff, abs(surv_at(curve, x) - sv) if x > 0 or sv < 1 else 0) info["max_abs_diff_vs_km_curves"] = round(maxdiff, 5) # SYM-H at recovery sy = [float(r["symh_at_recovery_nT"]) for r in rows if r["recovered"] == "TRUE" and r["symh_at_recovery_nT"].strip()] info["symh_at_recovery"] = {"n": len(sy), "median": round(statistics.median(sy), 2) if sy else None, "q25": round(pct(sy, 0.25), 2) if sy else None, "q75": round(pct(sy, 0.75), 2) if sy else None} sy0 = [float(r["symh_at_t0_nT"]) for r in rows if r["symh_at_t0_nT"].strip()] info["symh_at_t0_median_over_storms"] = round(statistics.median(sy0), 2) if sy0 else None dt24 = [float(r["dTEC_pct_median_0_24h"]) for r in rows if r["dTEC_pct_median_0_24h"].strip()] info["n_negative_dTEC_0_24h"] = sum(1 for x in dt24 if x < 0) info["n_dTEC_0_24h"] = len(dt24) bands[b] = info res["bands"] = bands # 6-7. epoch strip strip = {} for r in sea: strip.setdefault(r["series"], {})[int(r["hours_from_t0"])] = (int(r["n"]), float(r["median"]), float(r["q25"]), float(r["q75"])) pick = {} for s in ("NS30", "NS50", "NS70", "SYMH", "N50", "S50"): if s in strip: pick[s] = {str(h): strip[s].get(h) for h in (-24, -1, 0, 1, 5, 12, 24, 48, 72, 96, 120, 144, 167)} res["strip"] = pick # minimum of NS50 and NS70 median and where for s in ("NS30", "NS50", "NS70", "SYMH"): hs = [h for h in strip[s] if h >= 0] hmin = min(hs, key=lambda h: strip[s][h][1]) res.setdefault("strip_min", {})[s] = (hmin, strip[s][hmin]) # first hour at or after t0 where NS50 median >= -1 %, and stays within +-2 % thereafter s = strip["NS50"] res["NS50_first_hour_median_ge_minus1"] = next((h for h in sorted(s) if h >= 0 and s[h][1] >= -1.0), None) later = [h for h in sorted(s) if h >= 0] stay = None for h in later: if all(abs(s[k][1]) <= 2.0 for k in later if k >= h): stay = h break res["NS50_median_within_2pct_from_hour"] = stay # SYM-H strip at t0-24 and min with open(out_path, "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1) print(json.dumps(res, indent=1)) if __name__ == "__main__": main()