#!/usr/bin/env python3 """Section G of the rules. Usage: python -I tess_followup.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__)) 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) spec2 = importlib.util.spec_from_file_location("tess_neighbour", os.path.join(HERE, "tess_neighbour.py")) tn = importlib.util.module_from_spec(spec2) spec2.loader.exec_module(tn) STAR_RA, STAR_DEC = 142.4808758606437, -56.27943729547 def harmonics_X(t, P, n=30): ph = 2 * np.pi * (t - t.mean()) / P X = [np.ones_like(t)] for h in range(1, n + 1): X += [np.cos(h * ph), np.sin(h * ph)] return np.column_stack(X) def prewhiten(t, y, P): X = harmonics_X(t, P) coef, *_ = np.linalg.lstsq(X, y, rcond=None) return y - X @ coef def ls_period_grid(t, y, periods): """Sinusoid power (variance reduction) on trial periods.""" y0 = y - y.mean() out = np.empty(periods.size) for k, P in enumerate(periods): arg = 2 * np.pi * t / P c, s = np.cos(arg), np.sin(arg) cc, ss, cs = c @ c, s @ s, c @ s yc, ys = c @ y0, s @ y0 d = cc * ss - cs * cs a = (yc * ss - ys * cs) / d b = (ys * cc - yc * cs) / d out[k] = (a * yc + b * ys) / (y0 @ y0) return out def main(): folder, outdir = sys.argv[1:3] neigh = json.load(open(os.path.join(outdir, "tess_neighbour.json"), encoding="utf-8")) P_eb = float(neigh["F1"]["P_incoherent_pairs"]) res = {"P_eb_used": P_eb, "note": "Section G, added after seeing sections A and F. Not blind."} grid = np.logspace(math.log10(0.01), math.log10(25.0), 500) res["G1_grid_neighbours_of_1.43"] = [float(grid[np.searchsorted(grid, 1.43) - 1]), float(grid[np.searchsorted(grid, 1.43)])] g1 = {} data = {} for s in tp.SECTORS: hdus, tab, _ = tp.load_sector(folder, s) t, f, sky, c, good = tp.sector_photometry(hdus, tab, radius=1.5) lab = tp.orbits(t) y = tp.detrend_none(t, f, lab) tb, yb, _ = tp.bin30(t, y) pw = ls_period_grid(tb, yb, grid) # also the raw form with no orbit-mean removal tb2, yb2, _ = tp.bin30(t, f) pw2 = ls_period_grid(tb2, yb2, grid) m12 = (grid >= 1.0) & (grid <= 2.0) i12 = np.where(m12)[0][np.argmax(pw[m12])] j12 = np.where(m12)[0][np.argmax(pw2[m12])] g1[str(s)] = { "best_any": float(grid[np.argmax(pw)]), "best_any_raw": float(grid[np.argmax(pw2)]), "best_in_1_2d": float(grid[i12]), "best_in_1_2d_raw": float(grid[j12]), } data[s] = (t, f, lab, sky, c) res["G1"] = g1 # G6: nova flux per sector g6 = {} for s in tp.SECTORS: t, f, lab, sky, c = data[s] g6[str(s)] = {"median": float(np.median(f)), "p16": float(np.percentile(f, 16)), "p84": float(np.percentile(f, 84))} for group in ((9, 36, 62, 89), (10, 37, 63, 90)): base = np.mean([g6[str(group[0])]["median"], g6[str(group[1])]["median"]]) for s in group: excess = g6[str(s)]["median"] - base g6[str(s)]["excess_over_pre_outburst"] = float(excess) g6[str(s)]["rough_T_of_excess"] = float(20.44 - 2.5 * math.log10(excess)) if excess > 0 else None res["G6"] = g6 # G2/G3/G5: prewhitened, high-pass g2 = {} spectra = {} for s in tp.SECTORS: t, f, lab, sky, c = data[s] y4 = tp.detrend_rm(t, f, lab, width=4.0) tb, yb, _ = tp.bin30(t, y4) rb = prewhiten(tb, yb, P_eb) # high-pass the residual with a 1-d running median, per orbit labb = tp.orbits(tb) hb = tp.detrend_rm(tb, rb, labb, width=1.0) fr = np.arange(0.05, 10.0, 1.0 / (10 * (tb[-1] - tb[0]))) ls = tp.LS(tb, fr) amp = ls.amp(hb) i = tp.near_target(fr, amp, target=1 / 0.268, frac=0.03) fap, p99 = tp.block_shuffle_fap(ls, tb, hb, amp[i], ndraw=1000, seed=21) entry = { "period_d": float(1 / fr[i]), "amp": float(amp[i]), "snr": round(tp.local_snr(fr, amp, i), 2), "fap": fap, "top5_highpassed": tp.peaks(fr, amp, 5), } # per orbit phase at the sector's peak period segs = [] for k in np.unique(labb): m = labb == k r = tp.fit_fixed(tb[m], hb[m], fr[i], tb.mean()) r["orbit"] = int(k) segs.append(r) entry["orbits"] = segs g2[str(s)] = entry if s == 89: ampb = tp.LS(tb, fr).amp(yb) ampa = tp.LS(tb, fr).amp(rb) spectra = {"freq": fr, "before": ampb, "after": ampa} res["G2"] = g2 # amplitude maps at 0.268 d and 1.24 d maps = {} def amp_map(s, period, remove_eb=True): hdus, tab, _ = tp.load_sector(folder, s) ap_hdr = 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) arg = 2 * np.pi * (tb - tb.mean()) / period X = np.column_stack([np.cos(arg), np.sin(arg)]) XtXi = np.linalg.inv(X.T @ X) 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 if period < 1 else 4.0) if remove_eb: vb = prewhiten(tb, vb, P_eb) co = XtXi @ (X.T @ vb) A[j, i] = math.hypot(*co) cx, cy = tp.pixel_of(ap_hdr, tp.TARGET_RA, tp.TARGET_DEC) j, i = np.unravel_index(np.argmax(A), A.shape) return { "target_xy": [round(float(cx), 2), round(float(cy), 2)], "peak_pixel_xy": [int(i), int(j)], "offset_px": round(float(math.hypot(i - cx, j - cy)), 2), "peak_amp": float(A[j, i]), "median_amp": float(np.median(A)), "amp_at_target_pixel": float(A[int(round(cy)), int(round(cx))]), } for s in (62, 63, 89, 90): maps["P0.268_S%d" % s] = amp_map(s, g2[str(s)]["period_d"]) for s, per in ((37, 1.2446), (89, 1.2389)): maps["P1.24_S%d" % s] = amp_map(s, per) res["G2_G3_maps"] = maps # G4 repair: sector 89 difference image in a box around the star hdus, tab, _ = tp.load_sector(folder, 89) 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, cube = t[ok], 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] T0 = neigh["F1_fold"]["all_pairs"]["primary_T0_BTJD"] P_c = float(neigh["F1"]["P_coherent_all"]) ph = ((t - T0) / P_c + 0.5) % 1.0 - 0.5 inn = np.abs(ph) <= 0.05 out = np.abs(np.abs(ph) - 0.25) <= 0.08 A = np.nan_to_num(np.nanmean(cube[out], axis=0) - np.nanmean(cube[inn], axis=0)) sx, sy = tp.pixel_of(ap, STAR_RA, STAR_DEC) x0, y0 = int(round(sx)), int(round(sy)) box = A[max(0, y0 - 3) : y0 + 4, max(0, x0 - 3) : x0 + 4] fit = tn.gauss2d_fit(box, float(sx - max(0, x0 - 3)), float(sy - max(0, y0 - 3))) fx, fy = fit["x"] + max(0, x0 - 3), fit["y"] + max(0, y0 - 3) ra, de = tn.world_of(ap, fx, fy) res["G4"] = { "star_pixel": [round(float(sx), 2), round(float(sy), 2)], "fit_pixel": [round(float(fx), 2), round(float(fy), 2)], "fit_A": fit["A"], "fit_s": fit["s"], "ra": ra, "dec": de, "sep_from_star_arcsec": round(float(math.hypot((ra - STAR_RA) * math.cos(math.radians(STAR_DEC)) * 3600, (de - STAR_DEC) * 3600)), 1), } # G5 g5 = {} for s in (89, 90): t, f, lab, sky, c = data[s] y4 = tp.detrend_rm(t, f, lab, width=4.0) tb, yb, _ = tp.bin30(t, y4) rb = prewhiten(tb, yb, P_eb) fr = tp.freq_grid(tb[-1] - tb[0]) ls = tp.LS(tb, fr) table = [] for A0 in (0.5, 1, 1.5, 2, 3, 4, 5, 7.5, 10): rec = 0 for ph0 in np.arange(0, 1, 0.1): inj = rb + A0 * 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": A0, "recovered_of_10": rec}) g5[str(s)] = table res["G5"] = g5 # G7 with open(os.path.join(outdir, "tess_s89_amplitude_spectrum.csv"), "w", encoding="utf-8", newline="\n") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["freq_cycles_per_d", "period_d", "amp_before_e_per_s", "amp_after_removing_30_harmonics_e_per_s"]) for a, b, c_ in zip(spectra["freq"], spectra["before"], spectra["after"]): w.writerow([round(float(a), 5), round(float(1 / a), 5), round(float(b), 3), round(float(c_), 3)]) # G8 G, MSUN, RSUN, DAY = 6.674e-8, 1.989e33, 6.957e10, 86400.0 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 res["G8"] = [{"P_d": p, "a_Rsun": round(a_of_p(p), 2), "engulfed_day": round(t_of_r(a_of_p(p)), 1)} for p in (0.1, 0.186, 0.214, 0.268, 0.4, 0.693, 1.0, 1.424, 1.437, 2.0, 2.85, 3.0)] with open(os.path.join(outdir, "tess_followup.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1) print("wrote tess_followup.json") if __name__ == "__main__": main()