# ============================================================ # B8: DETECTION + VETTING LIBRARY (TLS search, iterative masking, view adapter, rate-limited TESS fetch) # ============================================================ import os, time, threading, numpy as np from wotan import flatten from transitleastsquares import transitleastsquares, transit_mask class RateLimiter: def __init__(self, rate): self.rate, self.tok, self.t, self.lock = rate, rate, time.monotonic(), threading.Lock() def acquire(self): while True: with self.lock: now = time.monotonic(); self.tok = min(self.rate, self.tok + (now - self.t) * self.rate); self.t = now if self.tok >= 1: self.tok -= 1; return time.sleep(0.05) MAST_LIMITER = RateLimiter(3.0) # lightkurve searches are heavy MAST queries; stay well under 10/s def fetch_tess_sector(tic, cache_dir, sector=None, retries=3): """One SPOC 2-min sector for a TIC via lightkurve (rate limited, cached as npz).""" import lightkurve as lk os.makedirs(cache_dir, exist_ok=True) out = f"{cache_dir}/TIC{tic}_{sector if sector else 'first'}.npz" if os.path.exists(out): z = np.load(out); return z["time"], z["flux"], int(z["sector"]) for k in range(retries): try: MAST_LIMITER.acquire() sr = lk.search_lightcurve(f"TIC {tic}", mission="TESS", author="SPOC", exptime=120, sector=sector) if len(sr) == 0: return None MAST_LIMITER.acquire() lc = sr[0].download(quality_bitmask="default").remove_nans().normalize() t, f = lc.time.value.astype(np.float64), lc.flux.value.astype(np.float64) sec = int(lc.meta.get("SECTOR", -1)) np.savez_compressed(out, time=t, flux=f, sector=sec); return t, f, sec except Exception: time.sleep(3 * (k + 1)) return None def detrend(t, f, window=0.5): flat = flatten(t, f, method="biweight", window_length=window, break_tolerance=0.5, edge_cutoff=0.0) ok = np.isfinite(flat); t, flat = t[ok], flat[ok] sig = 1.4826 * np.median(np.abs(flat - np.median(flat))); ok = flat < 1 + 4 * sig return t[ok], flat[ok] def bin_lc(t, f, dt_minutes): dt = dt_minutes / 1440.0; edges = np.arange(t.min(), t.max() + dt, dt) idx = np.digitize(t, edges) - 1; n = len(edges) - 1 s = np.bincount(idx, weights=f, minlength=n); c = np.bincount(idx, minlength=n); ts = np.bincount(idx, weights=t, minlength=n) m = c > 0; return ts[m] / c[m], s[m] / c[m] def tls_search(t, f, period_min=0.5, period_max=30, oversampling=2, **kw): model = transitleastsquares(t, f) return model.power(period_min=period_min, period_max=period_max, oversampling_factor=oversampling, duration_grid_step=1.1, use_threads=os.cpu_count(), show_progress_bar=False, **kw) def iterative_search(t, f, max_planets=5, sde_min=8.0, period_max=30, deadline=None, mask_factor=1.8): """Multi-planet search: TLS -> mask in-transit points -> repeat (Hippke & Heller 2019 recipe).""" found = []; tt, ff = t.copy(), f.copy() for i in range(max_planets): if deadline and time.time() > deadline: break if len(tt) < 200: break r = tls_search(tt, ff, period_max=min(period_max, (tt.max() - tt.min()) / 2)) if not np.isfinite(r.SDE) or r.SDE < sde_min: break found.append({"iteration": i + 1, "period": float(r.period), "t0": float(r.T0), "duration_h": float(r.duration * 24), "depth_ppm": float((1 - r.depth) * 1e6), "sde": float(r.SDE), "snr": float(r.snr), "transit_count": int(r.transit_count), "distinct_transit_count": int(r.distinct_transit_count), "odd_even_mismatch": float(r.odd_even_mismatch), "rp_rs": float(r.rp_rs), "periods": r.periods.tolist()[::4], "power": r.power.tolist()[::4]}) m = transit_mask(tt, r.period, mask_factor * r.duration, r.T0); tt, ff = tt[~m], ff[~m] return found def build_views_from_signal(t, flat, period, t0, dur_h, srho=np.nan, srad=np.nan, steff=np.nan, slogg=np.nan, mag=np.nan, others=()): """Adapter: (detrended LC, ephemeris) -> exactly the training schema (views + scalars).""" import prep_worker_b as pw row = {"kepoi_name": "signal", "kepid": 0, "koi_period": period, "koi_time0bk": t0, "koi_duration": dur_h, "koi_srho": srho, "koi_srad": srad, "koi_steff": steff, "koi_slogg": slogg, "koi_kepmag": mag} return pw.process_arrays(t, flat, row, list(others))