#!/usr/bin/env python3 """Section F of the rules: where does the 1.42-d signal in Gaia22alz's TESS aperture come from? Usage: python -I tess_neighbour.py Uses tess_period.py from this folder by path. """ 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__)) spec = importlib.util.spec_from_file_location("tess_period", os.path.join(HERE, "tess_period.py")) tp = importlib.util.module_from_spec(spec) spec.loader.exec_module(tp) SECTORS_QUIET = [9, 10, 36, 37, 89, 90] PAIRS = [(9, 10), (36, 37), (89, 90)] def stassun_t(g, bprp): """TESS magnitude from Gaia G and BP-RP, Stassun et al. (2019), their Eq. 1.""" return g - 0.00522555 * bprp**3 + 0.0891337 * bprp**2 - 0.633923 * bprp + 0.0324473 def world_of(hdr, x, y): """Inverse of tp.pixel_of for the linear WCS. 0-based x, y to RA, Dec in degrees.""" crpix1, crpix2 = float(hdr["CRPIX1"]), float(hdr["CRPIX2"]) crval1, crval2 = float(hdr["CRVAL1"]), float(hdr["CRVAL2"]) cd = np.array( [ [float(hdr.get("CD1_1", hdr.get("PC1_1", 0))), float(hdr.get("CD1_2", hdr.get("PC1_2", 0)))], [float(hdr.get("CD2_1", hdr.get("PC2_1", 0))), float(hdr.get("CD2_2", hdr.get("PC2_2", 0)))], ] ) dx = x + 1 - crpix1 dy = y + 1 - crpix2 xi, eta = cd @ np.array([dx, dy]) xi, eta = math.radians(xi), math.radians(eta) a0, d0 = math.radians(crval1), math.radians(crval2) den = math.cos(d0) - eta * math.sin(d0) a = a0 + math.atan2(xi, den) d = math.atan2((math.sin(d0) + eta * math.cos(d0)) * math.cos(a - a0), den) return math.degrees(a) % 360, math.degrees(d) def gauss2d_fit(img, x0, y0): """Least-squares fit: A exp(-r2/(2 s2)) + c, by Gauss-Newton from a start at x0, y0.""" ny, nx = img.shape yy, xx = np.mgrid[0:ny, 0:nx] p = np.array([img[int(round(y0)), int(round(x0))], x0, y0, 1.0, np.median(img)], dtype=float) for _ in range(60): A, x, y, s, c = p r2 = (xx - x) ** 2 + (yy - y) ** 2 g = np.exp(-r2 / (2 * s * s)) model = A * g + c J = np.column_stack( [g.ravel(), (A * g * (xx - x) / (s * s)).ravel(), (A * g * (yy - y) / (s * s)).ravel(), (A * g * r2 / (s**3)).ravel(), np.ones(g.size)] ) res = (img - model).ravel() dp, *_ = np.linalg.lstsq(J, res, rcond=None) p = p + 0.7 * dp if abs(p[3]) > 3.0: p[3] = 3.0 if abs(p[3]) < 0.4: p[3] = 0.4 A, x, y, s, c = p r2 = (xx - x) ** 2 + (yy - y) ** 2 res = img - (A * np.exp(-r2 / (2 * s * s)) + c) return {"A": float(A), "x": float(x), "y": float(y), "s": float(abs(s)), "c": float(c), "rms": float(np.std(res))} def lc_at(hdus, tab, centre, radius=1.5): return tp.sector_photometry(hdus, tab, radius=radius, centre=centre) def main(): folder, gaia_csv, outdir = sys.argv[1:4] res = {"note": "Section F of the rules, added after seeing section A. Not blind."} summ = json.load(open(os.path.join(outdir, "tess_summary.json"), encoding="utf-8")) # F1b: light curves centred on the named star, and a fine search around 5.6946 d STAR_RA, STAR_DEC = 142.4808758606437, -56.27943729547 store = {} for s in SECTORS_QUIET: hdus, tab, _ = tp.load_sector(folder, s) cx, cy = tp.pixel_of(hdus[2][0], STAR_RA, STAR_DEC) t, f, sky, c, good = lc_at(hdus, tab, (float(cx), float(cy))) lab = tp.orbits(t) y = tp.detrend_rm(t, f, lab, width=8.0) store[s] = (t, y, lab, float(cx), float(cy)) tbs = {} for a_, b_ in PAIRS: t = np.concatenate([store[a_][0], store[b_][0]]) y = np.concatenate([store[a_][1], store[b_][1]]) tb, yb, _ = tp.bin30(t, y) tbs[(a_, b_)] = (tb, yb) f1 = {} grid = np.arange(5.60, 5.80, 0.0002) power = np.zeros_like(grid) for k, P in enumerate(grid): tot = 0.0 for key, (tb, yb) in tbs.items(): ph = 2 * np.pi * (tb - tb.mean()) / P s0 = 0.0 for h in range(1, 31): s0 += abs(np.sum(yb * np.exp(1j * h * ph))) ** 2 / yb.size tot += s0 power[k] = tot Pinc = float(grid[np.argmax(power)]) ta = np.concatenate([tbs[k][0] for k in tbs]) ya = np.concatenate([tbs[k][1] for k in tbs]) span = float(ta[-1] - ta[0]) gridc = np.arange(Pinc - 0.01, Pinc + 0.01, 0.1 * Pinc * Pinc / span) powc = np.zeros_like(gridc) for k, P in enumerate(gridc): ph = 2 * np.pi * (ta - ta.mean()) / P s0 = 0.0 for h in range(1, 31): s0 += abs(np.sum(ya * np.exp(1j * h * ph))) ** 2 / ya.size powc[k] = s0 Pc = float(gridc[np.argmax(powc)]) f1["P_incoherent_pairs"] = Pinc f1["P_coherent_all"] = Pc f1["alias_spacing_d"] = Pc * Pc / span res["F1"] = f1 P2 = Pc P = Pc fold = {} t0map = {} nb = 80 allph = ((ta - ta[0]) / P) % 1.0 idx = np.minimum((allph * nb).astype(int), nb - 1) prof = np.array([np.median(ya[idx == i]) if np.any(idx == i) else np.nan for i in range(nb)]) i0 = int(np.nanargmin(prof)) half = (i0 + nb // 2) % nb win = [(half + d) % nb for d in range(-8, 9)] i1 = win[int(np.nanargmin(prof[win]))] top = np.nanpercentile(prof, 80) t00 = float(ta[0] + (i0 + 0.5) / nb * P) fold["all_pairs"] = { "P": P, "primary_T0_BTJD": t00, "profile_e_per_s": [round(float(v), 2) for v in prof], "primary_phase": (i0 + 0.5) / nb, "secondary_phase": (i1 + 0.5) / nb, "primary_depth_e_per_s": float(top - prof[i0]), "secondary_depth_e_per_s": float(top - prof[i1]), "top_level": float(top), } res["F1_fold"] = fold # F8: the same fold in the nova's own aperture, per sector f8 = {} for s in tp.SECTORS: hdus, tab, _ = tp.load_sector(folder, s) t, fl, sky, c, good = tp.sector_photometry(hdus, tab, radius=1.5) lab = tp.orbits(t) y = tp.detrend_rm(t, fl, lab, width=8.0) tb, yb, _ = tp.bin30(t, y) ph = ((tb - t00) / P + 0.5) % 1.0 - 0.5 inn1 = np.abs(ph) <= 0.03 phs = fold["all_pairs"]["secondary_phase"] - fold["all_pairs"]["primary_phase"] ph2 = ((tb - t00) / P - phs + 0.5) % 1.0 - 0.5 inn2 = np.abs(ph2) <= 0.03 outm = (np.abs(ph) > 0.08) & (np.abs(ph2) > 0.08) sd = float(np.std(yb[outm])) e1 = float(np.median(yb[outm]) - np.mean(yb[inn1])) if inn1.sum() else float("nan") e2 = float(np.median(yb[outm]) - np.mean(yb[inn2])) if inn2.sum() else float("nan") n1 = int(inn1.sum()) n2 = int(inn2.sum()) f8[str(s)] = { "depth_primary_e_per_s": e1, "depth_secondary_e_per_s": e2, "n_in_primary": n1, "n_in_secondary": n2, "rms_out": sd, "err_primary": sd / max(math.sqrt(n1), 1), "err_secondary": sd / max(math.sqrt(n2), 1), } res["F8"] = f8 t0map = {k: t00 for k in tbs} # F2: difference images f2 = {} posn = [] rows = list(csv.DictReader(open(gaia_csv, encoding="utf-8"))) for s in SECTORS_QUIET: hdus, tab, _ = tp.load_sector(folder, s) ap = hdus[2][0] cube = np.array(tab["FLUX"], dtype=float) t = np.array(tab["TIME"], dtype=float) q = np.array(tab["QUALITY"], dtype=int) ok = np.isfinite(t) & (q == 0) t = t[ok] cube = cube[ok] sky = np.nanmedian(cube, axis=(1, 2)) keep = sky <= np.nanpercentile(sky, 95) t, cube, sky = t[keep], cube[keep], sky[keep] cube = cube - sky[:, None, None] pairkey = [k for k in tbs if s in k][0] t00 = t0map[pairkey] ph = ((t - t00) / P + 0.5) % 1.0 - 0.5 inn = np.abs(ph) <= 0.05 out = (np.abs(np.abs(ph) - 0.25) <= 0.08) A = np.nanmean(cube[out], axis=0) - np.nanmean(cube[inn], axis=0) sum_out = np.nanmean(cube[out], axis=0) A = np.nan_to_num(A) j, i = np.unravel_index(np.argmax(A), A.shape) fit = gauss2d_fit(A, float(i), float(j)) ra, de = world_of(ap, fit["x"], fit["y"]) cx, cy = tp.pixel_of(ap, tp.TARGET_RA, tp.TARGET_DEC) dx = (ra - tp.TARGET_RA) * math.cos(math.radians(tp.TARGET_DEC)) * 3600 dy = (de - tp.TARGET_DEC) * 3600 # value of the difference image at the target's position, by Gaussian-weighted sum f2[str(s)] = { "n_in": int(inn.sum()), "n_out": int(out.sum()), "peak_pixel_xy": [int(i), int(j)], "fit": fit, "target_xy": [round(float(cx), 2), round(float(cy), 2)], "offset_px": round(float(math.hypot(fit["x"] - cx, fit["y"] - cy)), 2), "ra": ra, "dec": de, "offset_arcsec_E_N": [round(dx, 1), round(dy, 1)], "sep_arcsec_from_target": round(float(math.hypot(dx, dy)), 1), "diff_image_rows": [[round(float(v), 1) for v in row] for row in A], } posn.append((ra, de, s)) ra_m = float(np.median([p[0] for p in posn])) de_m = float(np.median([p[1] for p in posn])) near = [] for r in rows: dx = (float(r["ra"]) - ra_m) * math.cos(math.radians(de_m)) * 3600 dy = (float(r["dec"]) - de_m) * 3600 d = math.hypot(dx, dy) if d <= 30 and r.get("phot_g_mean_mag"): near.append( { "source_id": r["source_id"], "G": float(r["phot_g_mean_mag"]), "sep_from_fit_arcsec": round(d, 1), "sep_from_nova_arcsec": round(float(r["sep_arcsec"]), 1), "var": r["phot_variable_flag"], "bp_rp": (float(r["phot_bp_mean_mag"]) - float(r["phot_rp_mean_mag"])) if r["phot_bp_mean_mag"] and r["phot_rp_mean_mag"] else None, } ) near.sort(key=lambda r: r["G"]) res["F2"] = {"sectors": f2, "median_ra": ra_m, "median_dec": de_m, "gaia_within_30arcsec_of_fit_brightest_first": near[:15]} # F4: amplitude against flux Tq = stassun_t(18.38514, 18.843697 - 17.776117) fluxq = 10 ** (0.4 * (20.44 - Tq)) f4 = {"T_quiescent": round(Tq, 2), "flux_e_per_s_whole_star": round(fluxq, 1), "sectors": {}} for s in SECTORS_QUIET: f4["sectors"][str(s)] = summ["sectors"][str(s)]["photometry"]["r1.5_rm4d"]["near_1437"]["amp_e_per_s"] res["F4"] = f4 # F5 and F7: prewhitening in the target aperture f5 = {} for radius in (1.5, 1.0, 2.0): for s in tp.SECTORS: hdus, tab, _ = tp.load_sector(folder, s) t, fl, sky, c, good = tp.sector_photometry(hdus, tab, radius=radius) lab = tp.orbits(t) y = tp.detrend_rm(t, fl, lab) tb, yb, _ = tp.bin30(t, y) # remove 30 harmonics of the fitted period by linear least squares ph = 2 * np.pi * (tb - tb.mean()) / P2 X = [np.ones_like(tb)] for h in range(1, 31): X += [np.cos(h * ph), np.sin(h * ph)] X = np.column_stack(X) coef, *_ = np.linalg.lstsq(X, yb, rcond=None) rb = yb - X @ coef fr = tp.freq_grid(tb[-1] - tb[0]) ls = tp.LS(tb, fr) amp0 = ls.amp(yb) amp = ls.amp(rb) i = tp.near_target(fr, amp) top = int(np.argmax(amp)) entry = { "near_1437_after": {"period_d": round(float(1 / fr[i]), 4), "amp": float(amp[i]), "snr": round(tp.local_snr(fr, amp, i), 2)}, "top_after": tp.peaks(fr, amp, 5), } if radius == 1.5: fap, p99 = tp.block_shuffle_fap(ls, tb, rb, amp[top], ndraw=1000, seed=5) entry["top_peak"] = {"period_d": round(float(1 / fr[top]), 4), "amp": float(amp[top]), "snr": round(tp.local_snr(fr, amp, top), 2), "fap": fap} fapn, _ = tp.block_shuffle_fap(ls, tb, rb, amp[i], ndraw=1000, seed=6) entry["near_1437_after"]["fap"] = fapn f5["S%d_r%.1f" % (s, radius)] = entry res["F5_F7"] = f5 # F6: injection in 62 and 63 f6 = {} for s in (62, 63): hdus, tab, _ = tp.load_sector(folder, s) t, fl, sky, c, good = tp.sector_photometry(hdus, tab, radius=1.5) lab = tp.orbits(t) med = float(np.median(fl)) y0 = tp.detrend_rm(t, fl, lab) tb, yb, _ = tp.bin30(t, y0) fr = tp.freq_grid(tb[-1] - tb[0]) ls = tp.LS(tb, fr) table = [] for A in (5, 10, 15, 20, 30, 40, 50, 75, 100, 150, 200): rec = 0 for ph0 in np.arange(0, 1, 0.1): inj = yb + A * np.sin(2 * np.pi * (tb / 1.437 + ph0)) amp = ls.amp(inj) i = tp.near_target(fr, amp, frac=0.02) if tp.local_snr(fr, amp, i) >= 5: rec += 1 table.append({"amp": A, "recovered_of_10": rec}) f6[str(s)] = {"median_aperture_flux": med, "table": table} res["F6"] = f6 with open(os.path.join(outdir, "tess_neighbour.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1) print("wrote tess_neighbour.json") if __name__ == "__main__": main()