"""Reproduce every headline number of S0 News research note 001 from its Drive CSVs (rules: RULES_reproduce.txt). Run: python3 -I 01_reproduce_s0.py (reads the downloads as data; writes ../out/01_reproduce_s0.txt)""" import csv, hashlib, os, sys, math, statistics HERE = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, HERE) import stats_lib as st BASE = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.dirname(HERE) # hosted copy: the root folder is the first argument S = os.path.join(BASE, 'downloads', 's0-drive-001') OUT = os.path.join(BASE, 'out', '01_reproduce_s0.txt') lines = [] def say(*a): s = ' '.join(str(x) for x in a); lines.append(s); print(s) def sha(p): return hashlib.sha256(open(p, 'rb').read()).hexdigest() say('# 01_reproduce_s0.py output') say('rules', sha(os.path.join(HERE, 'RULES_reproduce.txt')), 'RULES_reproduce.txt') say('code ', sha(os.path.abspath(__file__)), os.path.basename(__file__)) say('lib ', sha(os.path.join(HERE, 'stats_lib.py')), 'stats_lib.py') for f in sorted(os.listdir(S)): if f.endswith('.csv') or f.endswith('.md'): say('data ', sha(os.path.join(S, f)), f) def rd(name): return list(csv.DictReader(open(os.path.join(S, name), encoding='utf-8'))) T = lambda v: str(v).strip().upper() == 'TRUE' # R1 inv = rd('episodes_inventory.csv') say('\n## R1 inventory') say('rows', len(inv), '| clean_5d', sum(T(r['clean_5d']) for r in inv), '| analyzable_A_ns_f1', sum(T(r['analyzable_A_ns_f1']) for r in inv), '| analyzable_A_tec', sum(T(r['analyzable_A_tec']) for r in inv), '| analyzable_B', sum(T(r['analyzable_B']) for r in inv), '| early_ns', sum(T(r['early_window_ns_f1']) for r in inv), '| early_tec', sum(T(r['early_window_tec']) for r in inv)) say('contaminated', sum(T(r['contaminated']) for r in inv), '| ICME (R&C)', sum(r['driver'] == 'ICME (R&C)' for r in inv), '| flare_flag', sum(T(r['flare_flag']) for r in inv), '| flare>=M5', sum(T(r['flare_ge_M5_in_window']) for r in inv), '| SPE', sum(T(r['spe_flag']) for r in inv)) from collections import Counter say('peak Kp notation counts', dict(sorted(Counter(r['peak_kp_notation'] for r in inv).items()))) say('peak Kp >= 6+ (6.333):', sum(float(r['peak_kp']) >= 6.33 for r in inv), '| peak exactly 6- :', sum(r['peak_kp_notation'] == '6-' for r in inv)) say('quiet days: mean per episode', round(statistics.mean(int(r['n_quiet_days']) for r in inv), 2), '| total', sum(int(r['n_quiet_days']) for r in inv), '| episodes with < 5 quiet days', [r['episode_id'] for r in inv if int(r['n_quiet_days']) < 5]) dur = [int(r['storm_duration_h']) for r in inv] say('storm duration h: median', st.median(dur), 'range', min(dur), max(dur)) def km_report(label, rows, tcol, ecol): t = [float(r[tcol]) for r in rows]; e = [T(r[ecol]) for r in rows] med = st.km_median(t, e); ci = st.km_median_bc_ci(t, e) boots = st.bootstrap(lambda smp: st.km_median([x[0] for x in smp], [x[1] for x in smp]), list(zip(t, e))) nr = sum(b is None for b in boots); fin = sorted(b for b in boots if b is not None) # bootstrap percentile CI treating "not reached" as +infinity allb = sorted([b if b is not None else float('inf') for b in boots]) lo = allb[int(0.025 * len(allb))]; hi = allb[int(0.975 * len(allb)) - 1] curve = st.km(t, e) say(f'{label}: n={len(t)} recovered={sum(e)} ({100*sum(e)/len(t):.1f}%) KM median={med} h | BC 95% CI {ci} | bootstrap 95% CI [{lo}, {hi}] (not reached in {nr}/2000) | plain median of times {st.median(t)} | S(48)={st.km_S_at(curve,48):.3f} S(72)={st.km_S_at(curve,72):.3f} S(79)={st.km_S_at(curve,79):.3f} S(106)={st.km_S_at(curve,106):.3f} S(119)={st.km_S_at(curve,119):.3f}') return t, e, curve # R2 say('\n## R2 pipeline A, NS f1') A = rd('PipelineA_NS_f1_Trec.csv') Ak = [r for r in A if T(r['in_km_all'])] tA, eA, cA = km_report('A NS f1 all', Ak, 'T_rec_h', 'recovered') km_report('A NS f1 clean_5d', [r for r in Ak if T(r['clean_5d'])], 'T_rec_h', 'recovered') say('censor_reason counts', dict(Counter(r['censor_reason'] for r in Ak if not T(r['recovered'])))) say('recovered at T_rec = 0 h:', [r['episode_id'] for r in Ak if T(r['recovered']) and float(r['T_rec_h']) == 0]) say('pooled-band episodes (n_sameUT_bins = 0):', [(r['episode_id'], r['n_quiet_days_with_data'], r['T_rec_h'], r['recovered']) for r in Ak if int(r['n_sameUT_bins']) == 0]) say('episodes with < 24 same-UT bins:', [(r['episode_id'], r['n_sameUT_bins']) for r in Ak if int(r['n_sameUT_bins']) < 24]) say('alternative MAD rule (columns T_rec_MAD_h / recovered_MAD, not described in the note): recovered', sum(T(r['recovered_MAD']) for r in Ak), 'of', len(Ak), [(r['episode_id'], r['T_rec_MAD_h']) for r in Ak if T(r['recovered_MAD'])]) tau = [float(r['tau_fit_h']) for r in Ak if r['tau_fit_h']] say('tau_fit_h (not described in the note): n', len(tau), '| at the 1000 h bound', sum(x > 999 for x in tau), '| median', round(st.median(tau), 1)) say('KM recovered-episode T_rec values (sorted):', sorted(float(r['T_rec_h']) for r in Ak if T(r['recovered']))) # R3 say('\n## R3 pipeline A, TEC') AT = rd('PipelineA_TEC_Trec.csv') ATk = [r for r in AT if T(r['in_km_all'])] tT, eT, cT = km_report('A TEC all', ATk, 'T_rec_h', 'recovered') km_report('A TEC clean_5d', [r for r in ATk if T(r['clean_5d'])], 'T_rec_h', 'recovered') say('TEC episodes with no post-t0 samples (n_valid_post_h = 0):', [r['episode_id'] for r in ATk if r['n_valid_post_h'] in ('0', '0.0')]) say('TEC censor reasons', dict(Counter(r['censor_reason'] for r in ATk if not T(r['recovered'])))) # R4 say('\n## R4 pipeline B') Bp = rd('PipelineB_NS_f1_TEC_Trec.csv') say('columns:', list(Bp[0].keys())) Bk = [r for r in Bp if T(r['in_pipelineB'])] km_report('B NS f1 all', Bk, 'ns_f1_T_rec_h', 'ns_f1_recovered') km_report('B TEC all', Bk, 'tec_T_rec_h', 'tec_recovered') km_report('B NS f1 clean_5d', [r for r in Bk if T(r['clean_5d'])], 'ns_f1_T_rec_h', 'ns_f1_recovered') km_report('B TEC clean_5d', [r for r in Bk if T(r['clean_5d'])], 'tec_T_rec_h', 'tec_recovered') km_report('B NS f1 excl. G003,G023,G025', [r for r in Bk if r['episode_id'] not in ('G003', 'G023', 'G025')], 'ns_f1_T_rec_h', 'ns_f1_recovered') # R5 say('\n## R5 TABLE1 and KM_curves') for r in rd('TABLE1_KM_summary.csv'): say('TABLE1:', r) kc = rd('KM_curves.csv') say('KM_curves columns', list(kc[0].keys()), 'rows', len(kc)) def check_curve(key_fn, curve, label): mine = {t: S for (t, S, _, d, _) in curve if d > 0} theirs = [(float(r['t_h']), float(r['frac_still_disturbed'])) for r in kc if key_fn(r)] bad = [(t, s, mine.get(t)) for (t, s) in theirs if t in mine and abs(mine[t] - s) > 5e-4] missing = [t for (t, s) in theirs if t not in mine and t != 0] say(f'KM_curves {label}: {len(theirs)} rows; mismatches {bad[:5]}; times not in our curve {missing[:10]}') try: check_curve(lambda r: r['pipeline'] == 'A' and r['signal'] == 'NS f1' and r['subset'] == 'all analyzable', cA, 'A NS f1 all') check_curve(lambda r: r['pipeline'] == 'A' and r['signal'] == 'TEC' and r['subset'] == 'all analyzable', cT, 'A TEC all') except KeyError as ex: say('KM_curves layout differs:', ex, kc[:3]) # R6 say('\n## R6 early window, Wilcoxon and Holm') ew = rd('early_window_per_episode.csv') say('columns', list(ew[0].keys()), 'rows', len(ew)) sig_col = 'signal' ps = {} for sig in sorted(set(r[sig_col] for r in ew)): rows = [r for r in ew if r[sig_col] == sig] diffs = [float(r['diff']) for r in rows] W, p, meth = st.wilcoxon_signed_rank(diffs, 'greater') ps[sig] = p say(f'{sig}: n={len(diffs)} W+={W} p_one_sided={p:.4g} ({meth}) | median diff {st.median(diffs):.4f} | median of median|z| {st.median([d + 0.6745 for d in diffs]):.4f} | n diff>0: {sum(d > 0 for d in diffs)}') adj = st.holm(list(ps.values())) say('Holm:', dict(zip(ps.keys(), [f'{a:.3g}' for a in adj]))) for r in rd('TABLE_early_window_Holm.csv'): say('TABLE_early_window_Holm:', r) # R7 say('\n## R7 first-day shift') ewA = [r for r in A if r['early_dev_0_24h_median'] and any(x['episode_id'] == r['episode_id'] and x[sig_col].startswith('NS') for x in ew)] dev = [float(r['early_dev_0_24h_median']) for r in ewA] say('n', len(dev), '| median', round(st.median(dev), 4), '| IQR', round(st.quantile7(dev, 0.25), 4), round(st.quantile7(dev, 0.75), 4), '| positive', sum(d > 0 for d in dev), '| negative', [(r['episode_id'], r['early_dev_0_24h_median']) for r in ewA if float(r['early_dev_0_24h_median']) <= 0]) say('two-sided sign-test tail P(>=40 of 41 positive | p=0.5) =', f'{2*st.binom_tail_ge(max(sum(d>0 for d in dev), len(dev)-sum(d>0 for d in dev)), len(dev)):.3g}') nsrows = {r['episode_id']: r for r in ew if r[sig_col].startswith('NS')} mism = [(r['episode_id']) for r in ewA if abs(float(r['early_absz_0_24h_median']) - (float(nsrows[r['episode_id']]['diff']) + 0.6745)) > 1e-6] say('early_window NS rows vs PipelineA early_absz: mismatches', mism) mads = [float(r['quiet_mad_sd']) for r in Ak] say('quiet_mad_sd (Hz): median', round(st.median(mads), 4), 'range', round(min(mads), 4), round(max(mads), 4), '| first-day shift / quiet_mad_sd: median', round(st.median([float(r['early_dev_0_24h_median']) / float(r['quiet_mad_sd']) for r in ewA]), 3)) # R8 say('\n## R8 pipelines A vs B, NS f1, per episode') Bd = {r['episode_id']: r for r in Bk} both = [r for r in Ak if r['episode_id'] in Bd] agree_rec = sum(T(r['recovered']) == T(Bd[r['episode_id']]['ns_f1_recovered']) for r in both) both_rec = [(r['episode_id'], float(r['T_rec_h']), float(Bd[r['episode_id']]['ns_f1_T_rec_h'])) for r in both if T(r['recovered']) and T(Bd[r['episode_id']]['ns_f1_recovered'])] say('episodes in both:', len(both), '| same recovered flag:', agree_rec, '| A recovered & B not:', sum(T(r['recovered']) and not T(Bd[r['episode_id']]['ns_f1_recovered']) for r in both), '| B recovered & A not:', sum((not T(r['recovered'])) and T(Bd[r['episode_id']]['ns_f1_recovered']) for r in both)) say('both recovered (id, A T_rec, B T_rec):', both_rec) say('|A - B| T_rec where both recovered: median', st.median([abs(a - b) for _, a, b in both_rec]) if both_rec else None) say('per-episode A vs B T_rec (id, A, recA, B, recB):', [(r['episode_id'], r['T_rec_h'], 'R' if T(r['recovered']) else 'c', Bd[r['episode_id']]['ns_f1_T_rec_h'], 'R' if T(Bd[r['episode_id']]['ns_f1_recovered']) else 'c') for r in both]) # R9 say('\n## R9 NS f1 vs TEC in pipeline A, per episode') Td = {r['episode_id']: r for r in ATk} pairs = [(r, Td[r['episode_id']]) for r in Ak if r['episode_id'] in Td] f1_later = tec_later = same = unclear = 0 for f, tc in pairs: tf, ef = float(f['T_rec_h']), T(f['recovered']); tt, et = float(tc['T_rec_h']), T(tc['recovered']) if ef and et: if tf > tt: f1_later += 1 elif tf < tt: tec_later += 1 else: same += 1 elif ef and not et: if tt >= tf: tec_later += 1 else: unclear += 1 elif et and not ef: if tf >= tt: f1_later += 1 else: unclear += 1 else: unclear += 1 say('pairs', len(pairs), '| f1 later', f1_later, '| TEC later', tec_later, '| tie', same, '| undetermined (censoring)', unclear) def diff_med(smp): a = st.km_median([x[0] for x in smp], [x[1] for x in smp]); b = st.km_median([x[2] for x in smp], [x[3] for x in smp]) if a is None: a = 1e9 if b is None: b = 1e9 return a - b rows9 = [(float(f['T_rec_h']), T(f['recovered']), float(tc['T_rec_h']), T(tc['recovered'])) for f, tc in pairs] bd = sorted(st.bootstrap(diff_med, rows9)) say('KM median f1 - TEC (paired bootstrap over episodes, 2000, seed 20261106): observed', diff_med(rows9), '| 95% CI', bd[49], bd[1949], '| share of resamples <= 0:', sum(x <= 0 for x in bd) / len(bd)) # R10 say('\n## R10 epoch composites') for name in ('epoch_composite_NS_f1.csv', 'epoch_composite_TEC.csv'): ec = rd(name) say(name, 'columns', list(ec[0].keys()), 'rows', len(ec)) hcol = 'hours_from_t0' at0 = [r for r in ec if float(r[hcol]) == 0] say(' at t0:', at0[0] if at0 else None) for h in (-24, 13, 24, 48, 71, 72, 96, 120): rr = [r for r in ec if float(r[hcol]) == h] if rr: say(f' h={h}:', {k: rr[0][k] for k in rr[0] if k in ('mean_anomaly_all', 'se_all', 'n_all', 'mean_anomaly_clean_5d', 'n_clean_5d')}) vals = [(float(r['mean_anomaly_all']), float(r[hcol])) for r in ec if r['mean_anomaly_all'] not in ('', 'nan') and -24 <= float(r[hcol]) <= 71] say(' min over -24..71:', min(vals), '| max:', max(vals)) open(OUT, 'w', encoding='utf-8', newline='\n').write('\n'.join(lines) + '\n')