#!/usr/bin/env python3 """Section H of the rules: trying to break the 0.268-d candidate. Usage: python -I tess_candidate.py """ import csv import importlib.util import json import math import os import sys import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) def load(name): spec = importlib.util.spec_from_file_location(name, os.path.join(HERE, name + ".py")) m = importlib.util.module_from_spec(spec) spec.loader.exec_module(m) return m tp = load("tess_period") tn = load("tess_neighbour") tf = load("tess_followup") G, MSUN, RSUN, DAY = 6.674e-8, 1.989e33, 6.957e10, 86400.0 def prepared(folder, s, P_eb, centre=None, radius=1.5): hdus, tab, _ = tp.load_sector(folder, s) t, f, sky, c, good = tp.sector_photometry(hdus, tab, radius=radius, centre=centre) lab = tp.orbits(t) y4 = tp.detrend_rm(t, f, lab, width=4.0) tb, yb, _ = tp.bin30(t, y4) rb = tf.prewhiten(tb, yb, P_eb) labb = tp.orbits(tb) hb = tp.detrend_rm(tb, rb, labb, width=1.0) return tb, hb, labb def amp_at(t, y, P): arg = 2 * np.pi * (t - t.mean()) / P X = np.column_stack([np.cos(arg), np.sin(arg), np.ones_like(t)]) co, *_ = np.linalg.lstsq(X, y, rcond=None) return float(math.hypot(co[0], co[1])) def best_period(t, y, grid): arg = 2 * np.pi * np.outer(1.0 / grid, t - t.mean()) c, s = np.cos(arg), np.sin(arg) y0 = y - y.mean() yc, ys = c @ y0, s @ y0 cc, ss, cs = np.sum(c * c, axis=1), np.sum(s * s, axis=1), np.sum(c * s, axis=1) d = cc * ss - cs**2 a = (yc * ss - ys * cs) / d b = (ys * cc - yc * cs) / d amp = np.sqrt(a * a + b * b) i = int(np.argmax(amp)) return float(grid[i]), float(amp[i]), amp def main(): folder, gaia_csv, outdir = sys.argv[1:4] neigh = json.load(open(os.path.join(outdir, "tess_neighbour.json"), encoding="utf-8")) foll = json.load(open(os.path.join(outdir, "tess_followup.json"), encoding="utf-8")) P_eb = float(neigh["F1"]["P_incoherent_pairs"]) res = {"note": "Section H, added after seeing section G. Not blind. Candidate only.", "P_eb_used": P_eb} data = {s: prepared(folder, s, P_eb) for s in tp.SECTORS} # H1 h1 = {} grid = np.arange(0.25, 0.29, 0.00001) rng = np.random.default_rng(20261105) for a, b in ((62, 63), (89, 90)): t = np.concatenate([data[a][0], data[b][0]]) y = np.concatenate([data[a][1], data[b][1]]) P, A, amp = best_period(t, y, grid) # block bootstrap of 1-d blocks within the pair idx = np.floor((t - t[0])).astype(int) groups = [np.where(idx == k)[0] for k in np.unique(idx)] boots = [] for _ in range(1000): pick = rng.integers(0, len(groups), len(groups)) sel = np.concatenate([groups[k] for k in pick]) # keep times in place so phase is meaningful sg = np.arange(P - 0.003, P + 0.003, 0.00002) pb, ab, _ = best_period(t[sel], y[sel], sg) boots.append(pb) boots = np.array(boots) h1["%d+%d" % (a, b)] = { "P_d": P, "P_hours": P * 24, "amp": A, "bootstrap_P_median": float(np.median(boots)), "bootstrap_P_16_84": [float(np.percentile(boots, 16)), float(np.percentile(boots, 84))], "rayleigh_resolution_d": float(P * P / (t[-1] - t[0])), "peak_alias_list": tp.peaks(1 / grid[::-1], amp[::-1], 3), } res["H1"] = h1 P0 = h1["62+63"]["P_d"] # H2 h2 = {} for a, b in ((9, 10), (36, 37), (62, 63), (89, 90)): t = np.concatenate([data[a][0], data[b][0]]) y = np.concatenate([data[a][1], data[b][1]]) A0 = amp_at(t, y, P0) ctrl = [] for f in np.linspace(1 / 0.40, 1 / 0.20, 200): if abs(f - 1 / P0) < 0.02: continue ctrl.append(amp_at(t, y, 1 / f)) ctrl = np.array(ctrl) h2["%d+%d" % (a, b)] = { "amp_at_P0": A0, "control_median": float(np.median(ctrl)), "control_p99": float(np.percentile(ctrl, 99)), "ratio_to_median": float(A0 / np.median(ctrl)), } res["H2"] = h2 # H3 position h3 = {} rows = list(csv.DictReader(open(gaia_csv, encoding="utf-8"))) for s in (62, 63, 89, 90): hdus, tab, _ = tp.load_sector(folder, s) ap = hdus[2][0] cube = np.array(tab["FLUX"], dtype=float) ny, nx = cube.shape[1:] t = np.array(tab["TIME"], dtype=float) q = np.array(tab["QUALITY"], dtype=int) good = np.isfinite(t) & (q == 0) t, cube = t[good], cube[good] sky = np.nanmedian(cube, axis=(1, 2)) ok = sky <= np.nanpercentile(sky, 95) t, cube, sky = t[ok], cube[ok], sky[ok] cube = cube - sky[:, None, None] idx = np.floor((t - t[0]) * 48).astype(int) u, inv = np.unique(idx, return_inverse=True) cnt = np.bincount(inv) tb = np.bincount(inv, weights=t) / cnt labb = tp.orbits(tb) Ps = foll["G2"][str(s)]["period_d"] # phase from the target aperture tt, yy, _ = data[s] arg = 2 * np.pi * (tb - tt.mean()) / Ps argt = 2 * np.pi * (tt - tt.mean()) / Ps Xt = np.column_stack([np.cos(argt), np.sin(argt)]) co = np.linalg.lstsq(Xt, yy - yy.mean(), rcond=None)[0] phi = math.atan2(co[1], co[0]) tmpl = np.cos(arg - phi) A = np.zeros((ny, nx)) for j in range(ny): for i in range(nx): v = cube[:, j, i] if not np.all(np.isfinite(v)): v = np.nan_to_num(v, nan=np.nanmedian(v)) vb = np.bincount(inv, weights=v) / cnt vb = tp.detrend_rm(tb, vb, labb, width=1.0) A[j, i] = 2 * np.mean((vb - vb.mean()) * tmpl) cx, cy = tp.pixel_of(ap, tp.TARGET_RA, tp.TARGET_DEC) j, i = np.unravel_index(np.argmax(A), A.shape) x0, y0 = int(i), int(j) lox, loy = max(0, x0 - 3), max(0, y0 - 3) box = A[loy : y0 + 4, lox : x0 + 4] fit = tn.gauss2d_fit(box, float(x0 - lox), float(y0 - loy)) fx, fy = fit["x"] + lox, fit["y"] + loy ra, de = tn.world_of(ap, fx, fy) dx = (ra - tp.TARGET_RA) * math.cos(math.radians(tp.TARGET_DEC)) * 3600 dy = (de - tp.TARGET_DEC) * 3600 near = [] for r in rows: d = math.hypot((float(r["ra"]) - ra) * math.cos(math.radians(de)) * 3600, (float(r["dec"]) - de) * 3600) if d <= 21 and r.get("phot_g_mean_mag"): near.append((float(r["phot_g_mean_mag"]), round(d, 1), round(float(r["sep_arcsec"]), 1), r["source_id"])) near.sort() h3[str(s)] = { "period_used": Ps, "peak_pixel_xy": [x0, y0], "target_xy": [round(float(cx), 2), round(float(cy), 2)], "fit_xy": [round(float(fx), 2), round(float(fy), 2)], "fit_s_px": round(fit["s"], 2), "fit_amp": fit["A"], "offset_px": round(float(math.hypot(fx - cx, fy - cy)), 2), "offset_arcsec": round(float(math.hypot(dx, dy)), 1), "offset_E_N_arcsec": [round(dx, 1), round(dy, 1)], "gaia_within_21arcsec_brightest": near[:6], } res["H3"] = h3 # H4 controls in each sector h4 = {} for s in (62, 63, 89, 90): hdus, tab, _ = tp.load_sector(folder, s) cx, cy = tp.pixel_of(hdus[2][0], tp.TARGET_RA, tp.TARGET_DEC) Ps = foll["G2"][str(s)]["period_d"] out = [] for ang in range(0, 360, 45): cc = (cx + 5 * math.cos(math.radians(ang)), cy + 5 * math.sin(math.radians(ang))) tb, hb, _ = prepared(folder, s, P_eb, centre=cc) fr = tp.freq_grid(tb[-1] - tb[0]) amp = tp.LS(tb, fr).amp(hb) i = tp.near_target(fr, amp, target=1 / Ps, frac=0.01) out.append({"angle": ang, "amp": round(float(amp[i]), 2), "snr": round(tp.local_snr(fr, amp, i), 2)}) h4[str(s)] = {"target_amp": foll["G2"][str(s)]["amp"], "controls": out} res["H4"] = h4 # H5 waveform h5 = {} for a, b in ((62, 63), (89, 90)): t = np.concatenate([data[a][0], data[b][0]]) y = np.concatenate([data[a][1], data[b][1]]) P = h1["%d+%d" % (a, b)]["P_d"] h5["%d+%d" % (a, b)] = { "amp_P": amp_at(t, y, P), "amp_2P": amp_at(t, y, 2 * P), "amp_P_over_2": amp_at(t, y, P / 2), "amp_P_over_3": amp_at(t, y, P / 3), "control_median_near_2P": float(np.median([amp_at(t, y, 1 / f) for f in np.linspace(1 / (2 * P) - 0.4, 1 / (2 * P) + 0.4, 81) if abs(f - 1 / (2 * P)) > 0.03])), "control_median_near_P": float(np.median([amp_at(t, y, 1 / f) for f in np.linspace(1 / P - 0.4, 1 / P + 0.4, 81) if abs(f - 1 / P) > 0.03])), } ph = ((t - t[0]) / (2 * P)) % 1.0 nb = 20 idx = np.minimum((ph * nb).astype(int), nb - 1) h5["%d+%d" % (a, b)]["fold_on_2P_median"] = [round(float(np.median(y[idx == i])), 2) for i in range(nb)] res["H5"] = h5 # H6 h6 = {} for s in (62, 63): ex = foll["G6"][str(s)]["excess_over_pre_outburst"] h6[str(s)] = {"amp": foll["G2"][str(s)]["amp"], "excess_flux": ex, "fraction": foll["G2"][str(s)]["amp"] / ex} res["H6"] = h6 # H7 phase line across 4 segments in a pair h7 = {} for a, b in ((62, 63), (89, 90)): P = h1["%d+%d" % (a, b)]["P_d"] tm = float(np.concatenate([data[a][0], data[b][0]]).mean()) segs = [] for s in (a, b): t, y, lab = data[s] for k in np.unique(lab): m = lab == k r = tp.fit_fixed(t[m], y[m], 1 / P, tm) segs.append({"sector": s, "orbit": int(k), "mid_t": float(t[m].mean()), "amp": r["amp"], "amp_err": r["amp_err"], "phase": r["phase_cycles"], "phase_err": r["phase_err"]}) # unwrap phases and fit a line ph = np.unwrap(np.array([g["phase"] for g in segs]) * 2 * np.pi) / (2 * np.pi) tt = np.array([g["mid_t"] for g in segs]) w = 1 / np.array([g["phase_err"] for g in segs]) ** 2 cf = np.polyfit(tt, ph, 1, w=np.sqrt(w)) res_ph = ph - np.polyval(cf, tt) h7["%d+%d" % (a, b)] = { "segments": segs, "slope_cycles_per_day": float(cf[0]), "resid_rms_cycles": float(np.std(res_ph)), "chi2": float(np.sum(res_ph**2 * w)), "dof": len(segs) - 2, } res["H7"] = h7 # H8 h8 = {} for a, b in ((62, 63), (89, 90)): t = np.concatenate([data[a][0], data[b][0]]) y = np.concatenate([data[a][1], data[b][1]]) order = np.argsort(t) t, y = t[order], y[order] fr = tp.freq_grid(t[-1] - t[0]) ls = tp.LS(t, fr) amp = ls.amp(y) top = int(np.argmax(amp)) fap, p99 = tp.block_shuffle_fap(ls, t, y, amp[top], ndraw=1000, seed=77) # peak nearest 0.268 i = tp.near_target(fr, amp, target=1 / 0.268, frac=0.02) fap2, _ = tp.block_shuffle_fap(ls, t, y, amp[i], ndraw=1000, seed=78) h8["%d+%d" % (a, b)] = { "top_period_d": float(1 / fr[top]), "top_amp": float(amp[top]), "top_fap": fap, "peak_near_0.268": float(1 / fr[i]), "amp": float(amp[i]), "snr": round(tp.local_snr(fr, amp, i), 2), "fap": fap2, "p99_shuffled_max": p99, "top5": tp.peaks(fr, amp, 5), } res["H8"] = h8 # H9 orbit def a_of_p(p, m1=0.6, m2=0.2): return (G * (m1 + m2) * MSUN * (p * DAY) ** 2 / (4 * math.pi**2)) ** (1 / 3) / RSUN def t_of_r(r): pts = [(-40.0, 0.335), (47.0, 3.78), (106.0, 34.8)] for (t1, r1), (t2, r2) in zip(pts[:-1], pts[1:]): if r <= r2: return t1 + (math.log(r) - math.log(r1)) / (math.log(r2) - math.log(r1)) * (t2 - t1) return None h9 = {} for P in (P0, 2 * P0, 1.437): for m2 in (0.2, 0.5, 0.8): a = a_of_p(P, 0.6, m2) r2 = tn_egg(m2 / 0.6) * a te = t_of_r(a) h9["P=%.4f,m2=%.1f" % (P, m2)] = { "a_Rsun": round(a, 2), "R2_lobe_Rsun": round(r2, 2), "engulfed_day": round(te, 1), "revs_by_day45": round(max(0, 45 - te) / P, 0), "revs_by_day49": round(max(0, 49 - te) / P, 0), "revs_by_day68": round(max(0, 68 - te) / P, 0), "revs_by_day177": round(max(0, 177 - te) / P, 0), } res["H9"] = h9 with open(os.path.join(outdir, "tess_candidate.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1) print("wrote tess_candidate.json") def tn_egg(q): return 0.49 * q ** (2.0 / 3) / (0.6 * q ** (2.0 / 3) + math.log(1 + q ** (1.0 / 3))) if __name__ == "__main__": main()