"""Test 1 (RULES_hcs_list.txt): rebuild the thesis's HCS crossing lists from OMNI. usage: py -3.12 -I hcs_list.py Needs numpy. Reads OMNI files as data only. """ import datetime as dt import json import os import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import numpy as np # noqa: E402 import common as C # noqa: E402 D = dt.date dl, outdir = sys.argv[1], sys.argv[2] os.makedirs(outdir, exist_ok=True) dates, gse, gsm = C.read_omni_daily(os.path.join(dl, 'omni', 'omni_01_av.dat'), 1999, 2024) P1 = (D(2000, 8, 31), D(2007, 4, 30)) P1yrs = (D(2000, 1, 1), D(2007, 12, 31)) P2 = (D(2010, 1, 1), D(2023, 12, 31)) def thr_for(period, series=gse): dd, b = C.subset(dates, series, *period) return 0.5 * np.nanmean(np.abs(b)), np.nanmean(np.abs(b)) res = {'note': 'Reconstruction of Peterson (2026) Chapter 3 crossing lists from OMNI daily By GSE'} # --- thresholds thr_P2, mabs_P2 = thr_for(P2) thr_P1yrs, mabs_P1yrs = thr_for(P1yrs) res['threshold'] = {'P2_2010_2023': {'mean_abs_By': mabs_P2, 'thr': thr_P2, 'thesis': 1.12}, 'P1yrs_2000_2007': {'mean_abs_By': mabs_P1yrs, 'thr': thr_P1yrs}} # --- worked example: window conventions on 2010-02-16 and 2010-03-01 (within P2 series) dd2, b2 = C.subset(dates, gse, *P2) ex = {} for day, want in [(D(2010, 2, 16), (5.32, 3.21)), (D(2010, 3, 1), (1.77, 1.15))]: t = dd2.index(day) row = {'thesis_before_after': want, 'By_t-1': float(b2[t - 1]), 'By_t': float(b2[t])} for name, ((b0, b1), (a0, a1)) in C.WINDOWS.items(): row[name] = (round(C.window_mean_abs(b2, t + b0, t + b1), 3), round(C.window_mean_abs(b2, t + a0, t + a1), 3)) ex[str(day)] = row res['worked_example'] = ex # choose window convention per the rules def matches(name): for day, row in ex.items(): tb, ta = row['thesis_before_after'] ob, oa = row[name] if abs(ob - tb) > 0.02 or abs(oa - ta) > 0.02: return False return True win = 'W1' if not matches('W1'): for name in ('W2', 'W3', 'W4'): if matches(name): win = name break res['window_convention_used'] = win res['window_matches'] = {name: matches(name) for name in C.WINDOWS} def summarise(period, thr, rule, win, label): dd, b = C.subset(dates, gse, *period) cr = C.detect_crossings(dd, b, thr, rule=rule, win=win) ta = sum(c['direction'] == 'T-A' for c in cr) at = sum(c['direction'] == 'A-T' for c in cr) el = C.eligible(cr, dd, 40) gaps = np.diff([c['index'] for c in cr]) near = int(np.sum(gaps <= 5)) s = {'period': [str(period[0]), str(period[1])], 'rule': rule, 'window': win, 'threshold_nT': round(float(thr), 4), 'n': len(cr), 'T-A': ta, 'A-T': at, 'eligible40': {'n': len(el), 'T-A': sum(c['direction'] == 'T-A' for c in el), 'A-T': sum(c['direction'] == 'A-T' for c in el)}, 'pairs_within_5_days': near} if len(gaps) > 1: vals, counts = np.unique(gaps, return_counts=True) s['intercrossing'] = {'n_gaps': int(len(gaps)), 'mean': float(gaps.mean()), 'se': float(gaps.std(ddof=1) / np.sqrt(len(gaps))), 'sd': float(gaps.std(ddof=1)), 'median': float(np.median(gaps)), 'mode': int(vals[np.argmax(counts)]), 'min': int(gaps.min()), 'max': int(gaps.max())} return s, cr, dd out_lists = {} for rule in ('A', 'B'): for (label, period, thr) in (('P1', P1, thr_P1yrs), ('P1yrs', P1yrs, thr_P1yrs), ('P2', P2, thr_P2)): s, cr, dd = summarise(period, thr, rule, win, label) res[f'{label}_rule{rule}'] = s out_lists[(label, rule)] = (cr, dd) # --- summer subsets (rule A, chosen window) def summer(label, start_md, end_md, margin): cr, dd = out_lists[(label, 'A')] el = C.eligible(cr, dd, 40) s0 = dt.date(2001, *start_md) + dt.timedelta(days=margin) e0 = dt.date(2001, *end_md) - dt.timedelta(days=margin) sel = [c for c in el if C.in_season(c['date'], (s0.month, s0.day), (e0.month, e0.day))] return {'window': [f'{s0.month:02d}-{s0.day:02d}', f'{e0.month:02d}-{e0.day:02d}'], 'n': len(sel), 'T-A': sum(c['direction'] == 'T-A' for c in sel), 'A-T': sum(c['direction'] == 'A-T' for c in sel)} res['summer'] = { 'USA_15Mar_15Sep_with40': summer('P2', (3, 15), (9, 15), 40), 'USA_15Mar_15Sep_no_margin': summer('P2', (3, 15), (9, 15), 0), 'thesis_USA': {'n': 87, 'T-A': 47, 'A-T': 40}, 'Canada_1Apr_1Oct_with40': summer('P2', (4, 1), (10, 1), 40), 'Canada_1Apr_1Oct_no_margin': summer('P2', (4, 1), (10, 1), 0), 'thesis_Canada': {'n': 90, 'T-A': 48, 'A-T': 42}, 'UK_1Apr_1Oct_with40': summer('P1', (4, 1), (10, 1), 40), 'UK_1Apr_1Oct_no_margin': summer('P1', (4, 1), (10, 1), 0), 'thesis_UK': {'n': 39, 'T-A': 22, 'A-T': 17}, } # --- crossings per year (P2, eligible) cr, dd = out_lists[('P2', 'A')] el = C.eligible(cr, dd, 40) per_year = {} for c in el: per_year[c['date'].year] = per_year.get(c['date'].year, 0) + 1 res['P2_eligible_per_year'] = per_year # --- By statistics def bystats(period): dd, b = C.subset(dates, gse, *period) v = b[~np.isnan(b)] pos, neg = v[v > 0], v[v < 0] r1 = np.corrcoef(v[:-1], v[1:])[0, 1] # r1 on the full daily series with gaps handled pairwise x0, x1 = b[:-1], b[1:] ok = ~(np.isnan(x0) | np.isnan(x1)) r1p = np.corrcoef(x0[ok], x1[ok])[0, 1] return {'n_days_valid': int(len(v)), 'n_days': len(b), 'pct_lt_-3': round(100 * np.mean(v < -3), 2), 'pct_gt_3': round(100 * np.mean(v > 3), 2), 'mean': round(float(v.mean()), 3), 'se': round(float(v.std(ddof=1) / np.sqrt(len(v))), 3), 'mean_pos': round(float(pos.mean()), 3), 'se_pos': round(float(pos.std(ddof=1) / np.sqrt(len(pos))), 3), 'mean_neg': round(float(neg.mean()), 3), 'se_neg': round(float(neg.std(ddof=1) / np.sqrt(len(neg))), 3), 'r1_pairwise': round(float(r1p), 3)} res['By_stats'] = {'P1yrs_2000_2007': bystats(P1yrs), 'P1': bystats(P1), 'P2_2010_2023': bystats(P2), 'thesis': {'2000-2007': {'pct_lt_-3': 17, 'pct_gt_3': 18, 'mean': '0.11+/-0.06', 'mean_pos': '2.75+/-0.05', 'mean_neg': '-2.70+/-0.05'}, '2010-2023': {'pct_lt_-3': 12, 'pct_gt_3': 11, 'mean': '-0.08+/-0.04', 'mean_pos': '2.24+/-0.03', 'mean_neg': '-2.27+/-0.03', 'r1': 0.548}}} # --- By extrema 2010-2023 def extrema(series): dd, b = C.subset(dates, series, *P2) n = len(b) mx, mn = [], [] for t in range(n): v = b[t] if np.isnan(v): continue lo, hi = max(0, t - 3), min(n, t + 4) seg = b[lo:hi] if v >= 3 and v == np.nanmax(seg): mx.append(t) if v <= -3 and v == np.nanmin(seg): mn.append(t) allx = np.array(sorted(mx + mn)) g = np.diff(allx) vals, counts = np.unique(g, return_counts=True) return {'maxima': len(mx), 'minima': len(mn), 'inter_mean': round(float(g.mean()), 2), 'inter_se': round(float(g.std(ddof=1) / np.sqrt(len(g))), 2), 'inter_sd': round(float(g.std(ddof=1)), 2), 'inter_mode': int(vals[np.argmax(counts)])} res['extrema_2010_2023'] = {'GSM': extrema(gsm), 'GSE': extrema(gse), 'thesis': {'GSM': {'minima': 273, 'maxima': 252, 'inter': '9.7+/-0.3, sd 6.3, mode 9'}, 'GSE': {'minima': 291, 'maxima': 264, 'inter': '9.2+/-0.4, sd 5.6, mode 8'}}} # --- secondary: daily means from hourly files, rule A, chosen window hd = C.read_omni_hourly_daily_means(os.path.join(dl, 'omni'), list(range(2000, 2008)) + list(range(2010, 2024))) sec = {} for label, period in (('P1', P1), ('P2', P2)): dd = C.daterange(*period) b = np.array([hd.get(d, np.nan) for d in dd]) base = P1yrs if label == 'P1' else P2 bb = np.array([hd.get(d, np.nan) for d in C.daterange(*base)]) thr = 0.5 * np.nanmean(np.abs(bb)) cr = C.detect_crossings(dd, b, thr, rule='A', win=win) el = C.eligible(cr, dd, 40) sec[label] = {'thr': round(float(thr), 4), 'n': len(cr), 'T-A': sum(c['direction'] == 'T-A' for c in cr), 'A-T': sum(c['direction'] == 'A-T' for c in cr), 'eligible40': len(el)} res['secondary_hourly_means_ruleA'] = sec with open(os.path.join(outdir, 'hcs_list_results.json'), 'w', encoding='utf-8', newline='\n') as f: json.dump(res, f, indent=1, default=str) # crossing lists (rule A, chosen window), CSV for label in ('P1', 'P1yrs', 'P2'): cr, dd = out_lists[(label, 'A')] with open(os.path.join(outdir, f'hcs_crossings_{label}.csv'), 'w', encoding='utf-8', newline='\n') as f: f.write('date,direction,mean_abs_By_before_nT,mean_abs_By_after_nT\n') for c in cr: f.write(f"{c['date']},{c['direction']},{c['before']:.3f},{c['after']:.3f}\n") print(json.dumps(res, indent=1, default=str))