Spaces:
Runtime error

File size: 7,031 Bytes
a3b68cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# ============================================================
# A5: PREPROCESS worker (written to kaksha_data/ so Notebook B gets the identical code)
#   mask other KOIs on same star -> wotan biweight (window = 3x duration, min 0.5d)
#   -> clip upward outliers -> fold on catalog ephemeris
#   -> views: global(201) local(61) secondary(61) odd(61) even(61)
#   -> physics scalars (odd/even, secondary, shape, duration-vs-density, radius, depth scatter)
# ============================================================
import numpy as np, warnings
from wotan import flatten
warnings.filterwarnings("ignore")

G_BINS, L_BINS, L_HALF = 201, 61, 2.0

def fold(t, period, t0):
    return ((t - t0 + 0.5 * period) % period) / period - 0.5   # phase in [-0.5, 0.5), transit at 0

def binned_view(phase, flux, lo, hi, nbins):
    edges = np.linspace(lo, hi, nbins + 1)
    idx = np.digitize(phase, edges) - 1
    ok = (idx >= 0) & (idx < nbins)
    sums = np.bincount(idx[ok], weights=flux[ok], minlength=nbins)
    cnts = np.bincount(idx[ok], minlength=nbins)
    view = np.full(nbins, np.nan); m = cnts > 0
    view[m] = sums[m] / cnts[m]
    if m.sum() == 0: return np.zeros(nbins, np.float32), 0.0
    if (~m).any():                                   # linear interpolation over empty bins (Yu+19)
        x = np.arange(nbins); view[~m] = np.interp(x[~m], x[m], view[m])
    return view.astype(np.float32), float(m.mean())

def normalize(view):
    """Astronet normalisation: median -> 0, minimum -> -1."""
    v = view - np.nanmedian(view)
    mn = np.nanmin(v)
    return (v / abs(mn)).astype(np.float32) if mn < 0 else v.astype(np.float32)

def mask_other_transits(t, others, pad=1.5):
    m = np.ones(len(t), bool)
    for (p, e, d) in others:
        ph = fold(t, p, e) * p
        m &= np.abs(ph) > pad * d / 2.0
    return m

def compute_views_and_scalars(t, flat, row, others):
    """Core: (already-detrended arrays, ephemeris row, other signals) -> views + scalars.
    Shared by training (process_koi) and inference (Notebook B) so both use identical code."""
    P, T0, dur_d = float(row["koi_period"]), float(row["koi_time0bk"]), float(row["koi_duration"]) / 24.0
    keep = mask_other_transits(t, others); t, flat = t[keep], flat[keep]
    ph = fold(t, P, T0)
    dur_ph = dur_d / P
    half = min(0.5, L_HALF * dur_ph)
    gv, g_cov = binned_view(ph, flat, -0.5, 0.5, G_BINS)
    lv, l_cov = binned_view(ph, flat, -half, half, L_BINS)
    ph_sec = ((ph + 1.0) % 1.0) - 0.5                       # secondary: phase 0.5 -> 0
    sv, _ = binned_view(ph_sec, flat, -half, half, L_BINS)
    epoch_n = np.floor((t - T0 + 0.5 * P) / P).astype(int)
    odd, even = epoch_n % 2 == 1, epoch_n % 2 == 0
    ov, _ = binned_view(ph[odd], flat[odd], -half, half, L_BINS)
    ev, _ = binned_view(ph[even], flat[even], -half, half, L_BINS)

    in_tr = np.abs(ph) < 0.5 * dur_ph
    out_tr = (np.abs(ph) > 1.5 * dur_ph) & (np.abs(ph) < 4 * dur_ph)
    noise = np.nanstd(flat[out_tr]) if out_tr.sum() > 20 else np.nanstd(flat)
    depth = 1 - np.nanmedian(flat[in_tr]) if in_tr.sum() > 5 else 0.0
    n_in = max(1, in_tr.sum())
    snr = depth / max(noise / np.sqrt(n_in), 1e-9)
    d_odd = 1 - np.nanmedian(flat[in_tr & odd]) if (in_tr & odd).sum() > 3 else depth
    d_even = 1 - np.nanmedian(flat[in_tr & even]) if (in_tr & even).sum() > 3 else depth
    oe_sigma = abs(d_odd - d_even) / max(noise / np.sqrt(max(1, n_in / 2)) * np.sqrt(2), 1e-9)
    in_sec = np.abs(ph_sec) < 0.5 * dur_ph
    sec_depth = 1 - np.nanmedian(flat[in_sec]) if in_sec.sum() > 5 else 0.0
    sec_sigma = sec_depth / max(noise / np.sqrt(max(1, in_sec.sum())), 1e-9)
    per_tr = []
    for k in np.unique(epoch_n[in_tr]):
        mm = in_tr & (epoch_n == k)
        if mm.sum() >= 3: per_tr.append(1 - np.nanmedian(flat[mm]))
    per_tr = np.array(per_tr); n_transits = len(per_tr)
    depth_scatter = (np.std(per_tr) / max(abs(depth), 1e-9)) if n_transits >= 3 else 0.0
    max_single_frac = (per_tr.max() / max(per_tr.sum(), 1e-9)) if n_transits >= 2 else 1.0
    shoulder = (np.abs(ph) > 0.35 * dur_ph) & (np.abs(ph) < 0.5 * dur_ph)
    d_should = 1 - np.nanmedian(flat[shoulder]) if shoulder.sum() > 3 else depth
    vshape = np.clip(d_should / max(abs(depth), 1e-9), 0, 2)
    srho = row.get("koi_srho", np.nan)
    if srho is not None and np.isfinite(srho) and srho > 0:
        exp_dur_h = 13.0 * (P / 365.25) ** (1 / 3) * srho ** (-1 / 3)   # solar-density scaling
        dur_ratio = (dur_d * 24) / exp_dur_h
    else:
        dur_ratio = np.nan
    srad = row.get("koi_srad", np.nan); srad = np.nan if srad is None else srad
    rp_rs = np.sqrt(max(depth, 0))
    rp_earth = rp_rs * srad * 109.2 if np.isfinite(srad) else np.nan

    return {
        "global_view": normalize(gv), "local_view": normalize(lv), "secondary_view": normalize(sv),
        "odd_view": normalize(ov), "even_view": normalize(ev),
        "per_transit_depths_ppm": (per_tr * 1e6).tolist(),
        "scalars": {
            "period": P, "duration_h": dur_d * 24, "depth_ppm": depth * 1e6, "snr": snr,
            "n_transits": n_transits, "oe_sigma": oe_sigma, "sec_depth_ppm": sec_depth * 1e6,
            "sec_sigma": sec_sigma, "depth_scatter": depth_scatter, "max_single_frac": max_single_frac,
            "vshape": vshape, "dur_ratio": dur_ratio, "rp_rs": rp_rs, "rp_earth": rp_earth,
            "global_cov": g_cov, "local_cov": l_cov, "noise_ppm": noise * 1e6,
            "steff": row.get("koi_steff", np.nan), "slogg": row.get("koi_slogg", np.nan),
            "srad": srad, "kepmag": row.get("koi_kepmag", np.nan),
        },
    }

def process_arrays(t, flat, row, others):
    """Inference entry point (Notebook B): caller has already detrended."""
    return compute_views_and_scalars(np.asarray(t, float), np.asarray(flat, float), row, list(others))

def process_koi(args):
    """Training entry point: args = (npz_path, row_dict, others_list). Returns dict or None."""
    npz_path, row, others = args
    try:
        z = np.load(npz_path); t, f = z["time"].astype(np.float64), z["flux"].astype(np.float64)
        P, dur_d = float(row["koi_period"]), float(row["koi_duration"]) / 24.0
        if len(t) < 500 or not np.isfinite(P) or P <= 0: return None
        keep = mask_other_transits(t, others); t, f = t[keep], f[keep]
        win = max(0.5, 3.0 * dur_d)
        flat = flatten(t, f, method="biweight", window_length=win, break_tolerance=0.5, edge_cutoff=0.0)
        ok = np.isfinite(flat); t, flat = t[ok], flat[ok]
        sig = 1.4826 * np.nanmedian(np.abs(flat - np.nanmedian(flat)))
        ok = flat < 1 + 4 * sig; t, flat = t[ok], flat[ok]           # clip upward outliers only
        if len(t) < 500: return None
        out = compute_views_and_scalars(t, flat, row, [])            # others already masked above
        out["kepoi_name"] = row["kepoi_name"]; out["kepid"] = int(row["kepid"])
        return out
    except Exception as e:
        return {"error": f"{type(e).__name__}: {str(e)[:100]}", "kepoi_name": row.get("kepoi_name")}