"""Pre-registered test: claude/onkayit-supernova-yol.md (SHA-256 5eedf518...f8c8eb, 18 Nov 2026 15:45 UTC+3).
Sections 1-5 implemented as written. Implementation choices not fixed in the pre-registration are marked IMPL."""
import sys, json
import numpy as np
from scipy.integrate import quad

DATA = sys.argv[1]
c = 299792.458
OM = 0.3153
C = 5/np.log(10)*0.08                       # 0.1737 mag
rng = np.random.default_rng(20261118)

# ---------- supernovae
d = np.genfromtxt(DATA+'/pantheon.dat', names=True, dtype=None, encoding=None)
d = d[d['USED_IN_SH0ES_HF'] == 1]
cids = sorted(set(d['CID']))
rows = []
for cid in cids:
    s = d[d['CID'] == cid]
    w = 1/s['MU_SH0ES_ERR_DIAG']**2
    mu = np.sum(w*s['MU_SH0ES'])/np.sum(w); err = 1/np.sqrt(np.sum(w))
    rows.append(dict(cid=cid, zhd=s['zHD'].mean(), zcmb=s['zCMB'].mean(), zhel=s['zHEL'].mean(),
                     mu=mu, err=err, ra=s['RA'].mean(), dec=s['DEC'].mean()))
def radec_to_gal(ra, dec):
    ra, dec = np.radians(ra), np.radians(dec)
    ra_gp, dec_gp, l_cp = np.radians(192.85948), np.radians(27.12825), np.radians(122.93192)
    sb = np.sin(dec)*np.sin(dec_gp)+np.cos(dec)*np.cos(dec_gp)*np.cos(ra-ra_gp)
    b = np.arcsin(sb)
    y = np.cos(dec)*np.sin(ra-ra_gp); x = np.sin(dec)*np.cos(dec_gp)-np.cos(dec)*np.sin(dec_gp)*np.cos(ra-ra_gp)
    l = (l_cp-np.arctan2(y, x)) % (2*np.pi)
    return np.degrees(l), np.degrees(b)
for r in rows:
    r['l'], r['b'] = radec_to_gal(r['ra'], r['dec'])
n_all = len(rows)
rows = [r for r in rows if abs(r['b']) > 10]
print(f'SNe: {n_all} unique in SH0ES Hubble flow, {len(rows)} after |b|>10 cut')

# ---------- 2MRS galaxies
gl, gb, cz = [], [], []
for line in open(DATA+'/asu.tsv', encoding='utf-8', errors='replace'):
    if line.startswith('#') or not line.strip(): continue
    p = line.rstrip('\n').split('\t')
    if p[0] in ('ID', '') or p[0].startswith('-'): continue
    try: L_, B_, V_ = float(p[4]), float(p[5]), float(p[25])
    except ValueError: continue
    gl.append(L_); gb.append(B_); cz.append(V_)
gl, gb, cz = map(np.array, (gl, gb, cz))
# IMPL: heliocentric cz -> CMB frame with the Planck 2018 dipole (369.82 km/s toward l=264.021, b=48.253)
def unit(l, b):
    l, b = np.radians(l), np.radians(b); return np.array([np.cos(b)*np.cos(l), np.cos(b)*np.sin(l), np.sin(b)])
dip = unit(264.021, 48.253)
G = unit(gl, gb)
zg = (cz + 369.82*(dip @ G))/c
keep = np.abs(gb) > 10
G, zg = G[:, keep], zg[keep]
print(f'2MRS: {len(gl)} galaxies read, {keep.sum()} with |b|>10')

# IMPL: unmasked solid angle of each cone measured with random points on the sphere
N_R = 400000
u = rng.uniform(-1, 1, N_R); ph = rng.uniform(0, 2*np.pi, N_R)
R = np.array([np.sqrt(1-u**2)*np.cos(ph), np.sqrt(1-u**2)*np.sin(ph), u])
R_unmasked = np.abs(np.degrees(np.arcsin(R[2]))) > 10
frac_sky = R_unmasked.mean()

def delta(r, zkey, cone):
    zmax = min(r[zkey], 0.05)
    shell = (zg > 0.003) & (zg < zmax)
    n_sky = shell.sum()
    v = unit(r['l'], r['b'])
    in_cone = (v @ G[:, shell]) > np.cos(np.radians(cone))
    cone_R = (v @ R) > np.cos(np.radians(cone))
    cone_frac = (cone_R & R_unmasked).sum()/N_R            # unmasked cone solid angle / 4pi
    expected = n_sky*cone_frac/frac_sky
    return in_cone.sum()/expected - 1, zmax/r[zkey]

def chi(z):
    return quad(lambda x: 1/np.sqrt(OM*(1+x)**3+1-OM), 0, z)[0]
def mu_model(z, zhel):
    return 5*np.log10((1+zhel)*c*chi(z)) + 25        # H0 = 1 km/s/Mpc; offset a absorbs H0

def fit(dmu, x, sig):
    A = np.vstack([np.ones_like(x), -C*x]).T
    W = 1/sig**2
    cov = np.linalg.inv(A.T @ (A*W[:, None])); p = cov @ (A.T @ (W*dmu))
    return p, np.sqrt(np.diag(cov))

def run(zkey, cone, boot=True, label=''):
    z = np.array([r[zkey] for r in rows]); zhel = np.array([r['zhel'] for r in rows])
    mu = np.array([r['mu'] for r in rows]); err = np.array([r['err'] for r in rows])
    dm = mu - np.array([mu_model(a, b) for a, b in zip(z, zhel)])
    dl = np.array([delta(r, zkey, cone) for r in rows]); dlt, f = dl[:, 0], dl[:, 1]
    x = f*dlt; sig = np.sqrt(err**2+0.10**2)
    (a, K), (ea, eK) = fit(dm, x, sig)
    out = dict(label=label, z=zkey, cone=cone, N=len(rows), K=K, eK=eK, delta_sd=float(np.std(dlt)), x_sd=float(np.std(x)))
    if boot:
        Ks = []
        for _ in range(1000):
            i = rng.integers(0, len(rows), len(rows)); Ks.append(fit(dm[i], x[i], sig[i])[0][1])
        Ks = np.array(Ks); out['eK_boot'] = float(np.std(Ks)); out['K95_upper_boot'] = float(np.percentile(Ks, 95))
    for nm, m in (('lo', z < 0.05), ('hi', z >= 0.05)):
        (aa, kk), (_, ek) = fit(dm[m], x[m], sig[m]); out['K_'+nm] = kk; out['eK_'+nm] = ek; out['N_'+nm] = int(m.sum())
    out['resid_sd'] = float(np.std(dm - a + C*K*x))
    return out

res = [run('zhd', 5, True, 'PRIMARY'), run('zcmb', 5, True, 'secondary zCMB'),
       run('zhd', 3, False, 'secondary cone 3'), run('zhd', 8, False, 'secondary cone 8')]
for o in res:
    print(json.dumps({k: (round(v, 4) if isinstance(v, float) else v) for k, v in o.items()}, ensure_ascii=False))
json.dump(res, open('sonuc.json', 'w'), indent=1)
