#!/usr/bin/env python3 """The TESS numbers re-derived after a separate review of the page. Rules N1-N7 in RULES_addendum_8_after_review.txt, with the changes in RULES_addendum_9_after_first_rerun.txt. Usage: python -I review_tess.py Writes review_tess.json and tess_s89_spectrum_template.csv. Needs numpy and scipy. Reads the TESScut zips as data with our own FITS reader in tess_period.py. """ import csv import importlib.util import json import math import os import sys import numpy as np from scipy.optimize import least_squares HERE = os.path.dirname(os.path.abspath(__file__)) def load_module(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_module("tess_period") tn = load_module("tess_neighbour") SECTORS = tp.SECTORS PAIRS = {"2019": (9, 10), "2021": (36, 37), "2023": (62, 63), "2025": (89, 90)} STAR_RA, STAR_DEC = 142.4808758606437, -56.27943729547 PF = 1 / 1.437 VSX_P, VSX_T0 = 5.6946, 2457727.742 - 2457000.0 PIX_ARCSEC = 21.0 RNG = np.random.default_rng(20261104) class Sector: def __init__(self, folder, s): hdus, tab, _ = tp.load_sector(folder, s) self.s = s self.ap = hdus[2][0] t = np.array(tab["TIME"], dtype=float) q = np.array(tab["QUALITY"], dtype=int) cube = np.array(tab["FLUX"], dtype=float) good = np.isfinite(t) & (q == 0) & (np.sum(np.isfinite(cube), axis=(1, 2)) > 0.9 * cube.shape[1] * cube.shape[2]) self.t = t[good] self.cube = cube[good] self.fm = np.nanmedian(self.cube, axis=(1, 2)) self.nova = tuple(float(v) for v in tp.pixel_of(self.ap, tp.TARGET_RA, tp.TARGET_DEC)) self.star = tuple(float(v) for v in tp.pixel_of(self.ap, STAR_RA, STAR_DEC)) self.ny, self.nx = self.cube.shape[1:] self.t0 = self.t[0] self.cache = {} def sky(self, centre, r, how): key = ("sky", round(centre[0], 3), round(centre[1], 3), r, how) if key in self.cache: return self.cache[key] if how == "frame": out = self.fm else: r1, r2 = (2.5, 3.5) if r == 1.5 else (r + 1.0, r + 2.0) mask = tp.annulus(self.nx, self.ny, centre[0], centre[1], r1, r2) if how == "median": out = np.nanmedian(self.cube[:, mask], axis=1) elif how == "tool": out = tp.sky_mode(self.cube, mask) else: raise ValueError(how) self.cache[key] = out return out def phot(self, centre, r, how): """Unbinned aperture flux minus sky, with the sky's 95th-percentile cut as a boolean.""" key = ("phot", round(centre[0], 3), round(centre[1], 3), r, how) if key in self.cache: return self.cache[key] w = tp.weights(self.nx, self.ny, centre[0], centre[1], r) sky = self.sky(centre, r, how) f = np.nansum(w * (self.cube - sky[:, None, None]), axis=(1, 2)) ok = np.isfinite(sky) ok &= sky <= np.nanpercentile(sky[ok], 95) self.cache[key] = (f, ok) return f, ok def binned(self, f, ok): idx = np.floor((self.t[ok] - self.t0) * 48).astype(int) u, inv = np.unique(idx, return_inverse=True) cnt = np.bincount(inv) return np.bincount(inv, weights=self.t[ok]) / cnt, np.bincount(inv, weights=f[ok]) / cnt, u def series(self, centre, r, how, hp): """Binned, high-passed series in the aperture, with the star's series on the same time bins.""" f, ok = self.phot(centre, r, how) tb, yb, u = self.binned(f, ok) lab = tp.orbits(tb) y = tp.detrend_rm(tb, yb, lab, width=hp) if hp else yb fs, oks = self.phot(self.star, 1.5, "frame") tsb, ysb, us = self.binned(fs, oks) labs = tp.orbits(tsb) ys = tp.detrend_rm(tsb, ysb, labs, width=hp) if hp else ysb # align on common bins common, ia, ib = np.intersect1d(u, us, return_indices=True) return tb[ia], y[ia], ys[ib] def amp_at(t, y, f): arg = 2 * np.pi * f * (t - t.mean()) X = np.column_stack([np.cos(arg), np.sin(arg), np.ones_like(t)]) c, *_ = np.linalg.lstsq(X, y, rcond=None) return float(math.hypot(c[0], c[1])) def spectrum(t, y, freqs): y0 = y - y.mean() tt = t - t.mean() out = np.empty(freqs.size) step = 400 for i in range(0, freqs.size, step): fr = freqs[i : i + step] arg = 2 * np.pi * np.outer(fr, tt) c, s = np.cos(arg), np.sin(arg) cc, ss, cs = np.sum(c * c, axis=1), np.sum(s * s, axis=1), np.sum(c * s, axis=1) yc, ys = c @ y0, s @ y0 d = cc * ss - cs * cs a = (yc * ss - ys * cs) / d b = (ys * cc - yc * cs) / d out[i : i + step] = np.sqrt(a * a + b * b) return out def controls(t, y, f0, n=340, near=0.05, half=0.5): fc = np.linspace(f0 - half, f0 + half, n) fc = fc[np.abs(fc - f0) > near] return spectrum(t, y, fc) def fold_template(t, ys, P, T0, nb=60): ph = ((t - T0) / P) % 1.0 b = np.minimum((ph * nb).astype(int), nb - 1) m = np.array([np.mean(ys[b == i]) if np.any(b == i) else np.nan for i in range(nb)]) ok = np.isfinite(m) pc = (np.arange(nb) + 0.5) / nb return np.interp(ph, pc[ok], m[ok], period=1.0) def remove_scale(t, y, tmpl): X = np.column_stack([np.ones_like(t), tmpl]) c, *_ = np.linalg.lstsq(X, y, rcond=None) return y - X @ c, float(c[1]) def harmonics_matrix(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 remove_matrix(X, y): c, *_ = np.linalg.lstsq(X, y, rcond=None) return y - X @ c def trapezoid_fit(tt, ff): def model(p): D, c, h, ing, a, b = p x = np.abs(tt - c) return a + b * tt - D * np.clip((h - x) / ing, 0, 1) best = None for c0 in (-0.08, 0.0, 0.08): r = least_squares( lambda p: model(p) - ff, [200, c0, 0.17, 0.05, np.median(ff), 0], bounds=([0, -0.5, 0.03, 0.005, -np.inf, -np.inf], [1500, 0.5, 0.6, 0.3, np.inf, np.inf]), ) if best is None or r.cost < best.cost: best = r res = model(best.x) - ff try: cov = np.linalg.inv(best.jac.T @ best.jac) * res.var() err = float(math.sqrt(cov[1, 1])) except Exception: err = float("nan") return best.x, err def n1_timing(secs): rows = [] for s, S in secs.items(): f, ok = S.phot(S.star, 1.5, "frame") t, y = S.t[ok], f[ok] n0 = math.floor((t.min() - VSX_T0) / VSX_P) - 1 n1 = math.ceil((t.max() - VSX_T0) / VSX_P) + 1 for n2 in range(2 * n0, 2 * n1 + 1): n = n2 / 2 guess = VSX_T0 + n * 5.6950 + 0.012 * 5.6950 m = np.abs(t - guess) < 1.2 if m.sum() < 30: continue tt = t[m] - guess if tt.max() < 0.6 or tt.min() > -0.6 or (np.abs(tt) < 0.2).sum() < 4: continue x, err = trapezoid_fit(tt, y[m]) rows.append({"sector": s, "n": n, "kind": "primary" if n == int(n) else "secondary", "time": float(guess + x[1]), "err": err, "depth": float(x[0]), "half_width": float(x[2])}) keep = [r for r in rows if r["depth"] > 60 and np.isfinite(r["err"]) and r["err"] < 0.05] n = np.array([r["n"] for r in keep]) T = np.array([r["time"] for r in keep]) w = 1 / np.maximum(np.array([r["err"] for r in keep]), 0.005) c = np.polyfit(n, T, 1, w=w) res = T - np.polyval(c, n) # error on P from the residual scatter A = np.column_stack([n, np.ones_like(n)]) cov = np.linalg.inv((A * w[:, None]).T @ (A * w[:, None])) * max(1.0, np.sum((res * w) ** 2) / (n.size - 2)) P, T0 = float(c[0]), float(c[1]) by = {str(s): float(np.median(res[[r["sector"] == s for r in keep]])) for s in sorted(set(r["sector"] for r in keep))} cycle144 = VSX_T0 + 144 * VSX_P near = T0 + round((cycle144 - T0) / P) * P out = { "P_d": P, "P_err_d": float(math.sqrt(cov[0, 0])), "T0_BJD": T0 + 2457000.0, "n_eclipses_fitted": len(rows), "n_eclipses_kept": len(keep), "rms_d": float(np.std(res)), "median_residual_by_sector_d": by, "offset_from_VSX_cycle_144_cycles": float((near - cycle144) / VSX_P), "star_primary_depth_median": float(np.median([r["depth"] for r in keep if r["kind"] == "primary"])), "star_secondary_depth_median": float(np.median([r["depth"] for r in keep if r["kind"] == "secondary"])), "half_width_median_d": float(np.median([r["half_width"] for r in keep])), "primary_depth_by_sector": { str(s): [round(float(r["depth"]), 1) for r in keep if r["sector"] == s and r["kind"] == "primary"] for s in sorted(set(r["sector"] for r in keep)) }, "eclipses": [{k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()} for r in keep], } # how far the old fold was off by 2025 old_P, old_T0 = 5.695584156841794, 1547.8207070035173 t25 = 3745.0 out["old_fold_lateness_2025_d"] = float(((t25 - old_T0) / old_P - round((t25 - old_T0) / old_P)) * old_P - ((t25 - T0) / P - round((t25 - T0) / P)) * P) return out, P, T0 def eclipse_depth(t, y, P, T0, phase0=0.0, half=0.03): ph = ((t - T0) / P - phase0 + 0.5) % 1.0 - 0.5 ph2 = ((t - T0) / P - 0.5 + 0.5) % 1.0 - 0.5 ph1 = ((t - T0) / P + 0.5) % 1.0 - 0.5 inn = np.abs(ph) <= half out = (np.abs(ph1) > 0.08) & (np.abs(ph2) > 0.08) if inn.sum() < 3: return None, None, 0 sd = float(np.std(y[out])) return float(np.median(y[out]) - np.mean(y[inn])), sd / math.sqrt(inn.sum()), int(inn.sum()) def n2_refold(secs, P, T0): res = {} for s, S in secs.items(): e = {} for how in ("tool", "median"): f, ok = S.phot(S.nova, 1.5, how) tb, yb, _ = S.binned(f, ok) y = tp.detrend_rm(tb, yb, tp.orbits(tb), width=8.0) d1, er1, n1 = eclipse_depth(tb, y, P, T0, 0.0) d2, er2, n2 = eclipse_depth(tb, y, P, T0, 0.5) y4 = tp.detrend_rm(tb, yb, tp.orbits(tb), width=4.0) e[how] = {"primary": d1, "primary_err": er1, "secondary": d2, "secondary_err": er2, "semi_amp_P4": amp_at(tb, y4, 4 / P), "A_1437_before": amp_at(tb, y4, PF)} if how == "tool": e["share_flux_at_or_below_zero"] = float(np.mean(f[ok] <= 0)) f, ok = S.phot(S.star, 1.5, "frame") tb, yb, _ = S.binned(f, ok) y = tp.detrend_rm(tb, yb, tp.orbits(tb), width=8.0) d1s, _, _ = eclipse_depth(tb, y, P, T0, 0.0, half=0.01) d2s, _, _ = eclipse_depth(tb, y, P, T0, 0.5, half=0.01) d13, _, _ = eclipse_depth(tb, y, P, T0, 0.0, half=0.03) e["star"] = {"primary_0.01": d1s, "secondary_0.01": d2s, "primary_0.03": d13, "semi_amp_P4": amp_at(tb, tp.detrend_rm(tb, yb, tp.orbits(tb), width=4.0), 4 / P)} # raw nova aperture, frame sky f, ok = S.phot(S.nova, 1.5, "frame") tb, yb, _ = S.binned(f, ok) y = tp.detrend_rm(tb, yb, tp.orbits(tb), width=8.0) dr, _, _ = eclipse_depth(tb, y, P, T0, 0.0) e["raw_nova_primary"] = dr e["raw_share_of_star"] = dr / d13 if d13 else None # difference image and P/4 map ok = S.fm <= np.nanpercentile(S.fm, 95) t = S.t[ok] cube = S.cube[ok] - S.fm[ok, None, None] ph = ((t - T0) / P + 0.5) % 1.0 - 0.5 inn = np.abs(ph) <= 0.02 ph2 = ((t - T0) / P) % 1.0 out = (np.abs(ph2 - 0.25) <= 0.08) | (np.abs(ph2 - 0.75) <= 0.08) img = np.nan_to_num(np.nanmean(cube[out], axis=0) - np.nanmean(cube[inn], axis=0)) fit = fit_near(img, S.star, 3) ra, de = tn.world_of(S.ap, fit["x"], fit["y"]) e["difference_image"] = { "n_in": int(inn.sum()), "sep_star_arcsec": sep_arcsec(ra, de, STAR_RA, STAR_DEC), "sep_nova_arcsec": sep_arcsec(ra, de, tp.TARGET_RA, tp.TARGET_DEC), "fit_amp": fit["A"], "fit_sigma_px": fit["s"], } A, _ = amp_map(S, 1 / (P / 4), 4.0) fit = fit_near(A, S.star, 3) ra, de = tn.world_of(S.ap, fit["x"], fit["y"]) j, i = int(round(S.nova[1])), int(round(S.nova[0])) fit2 = fit_near(A, S.star, 2) ra2, de2 = tn.world_of(S.ap, fit2["x"], fit2["y"]) e["map_P4"] = {"sep_star_arcsec": sep_arcsec(ra, de, STAR_RA, STAR_DEC), "sep_star_arcsec_5x5_box": sep_arcsec(ra2, de2, STAR_RA, STAR_DEC), "peak": float(A.max()), "at_nova_pixel": float(A[j, i])} A2, _ = amp_map(S, 1.437, 4.0) jm, im = np.unravel_index(int(np.argmax(A2)), A2.shape) e["map_1437"] = {"peak_pixel": [int(im), int(jm)], "peak_px_from_star": float(math.hypot(im - S.star[0], jm - S.star[1])), "peak": float(A2.max()), "at_nova_pixel": float(A2[j, i])} res[str(s)] = e return res def sep_arcsec(ra, de, ra0, de0): return float(math.hypot((ra - ra0) * math.cos(math.radians(de0)) * 3600, (de - de0) * 3600)) def fit_near(img, centre, half): """2-D Gaussian in a box around a predicted pixel, starting from the box's peak. Centre held inside the box, width held to 0.35-1.5 px, so a weak map can't send the fit away.""" x0, y0 = int(round(centre[0])), int(round(centre[1])) ny, nx = img.shape lox, hix, loy, hiy = max(0, x0 - half), min(nx - 1, x0 + half), max(0, y0 - half), min(ny - 1, y0 + half) yy, xx = np.mgrid[loy : hiy + 1, lox : hix + 1] box = img[loy : hiy + 1, lox : hix + 1] j, i = np.unravel_index(int(np.argmax(box)), box.shape) def model(q): return q[0] * np.exp(-0.5 * ((xx - q[1]) ** 2 + (yy - q[2]) ** 2) / q[3] ** 2) + q[4] r = least_squares( lambda q: (model(q) - box).ravel(), [max(box.max() - np.median(box), 1e-3), lox + float(i), loy + float(j), 0.7, float(np.median(box))], bounds=([0, lox, loy, 0.35, -np.inf], [np.inf, hix, hiy, 1.5, np.inf]), ) q = r.x edge = q[3] <= 0.351 or q[3] >= 1.499 or q[1] <= lox + 0.01 or q[1] >= hix - 0.01 or q[2] <= loy + 0.01 or q[2] >= hiy - 0.01 return {"A": float(q[0]), "x": float(q[1]), "y": float(q[2]), "s": float(q[3]), "c": float(q[4]), "at_bound": bool(edge)} def amp_map(S, period, hp): """Per-pixel amplitude at a period, frame sky, high-passed. Returns amplitude and (cos, sin) coefficient maps.""" ok = S.fm <= np.nanpercentile(S.fm, 95) t = S.t[ok] cube = S.cube[ok] - S.fm[ok, 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 lab = tp.orbits(tb) arg = 2 * np.pi * (tb - 3000.0) / period X = np.column_stack([np.cos(arg), np.sin(arg)]) XtXi = np.linalg.inv(X.T @ X) A = np.zeros((S.ny, S.nx)) C = np.zeros((2, S.ny, S.nx)) for j in range(S.ny): for i in range(S.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, lab, width=hp) c = XtXi @ (X.T @ (vb - vb.mean())) A[j, i] = math.hypot(*c) C[:, j, i] = c return A, C def local_snr_exact(t, y, f0): return amp_at(t, y, f0) / float(np.median(controls(t, y, f0))) def limit_ladder(t, y, remover, f0=PF): """Lowest amplitude recovered at S/N >= 5 within +/-2% of f0 in at least 9 of 10 phases, through the given removal.""" span = t[-1] - t[0] fr = np.arange(f0 - 0.5, f0 + 0.5, 1 / (10 * span)) near = np.abs(fr - f0) > 0.05 win = np.where(np.abs(1 / fr - 1 / f0) <= 0.02 / f0)[0] for A0 in (0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 5, 7.5, 10, 15, 20, 30, 50, 75, 100, 150, 200, 300, 500, 750, 1000): rec = 0 for ph in np.arange(0, 1, 0.1): v = remover(y + A0 * np.sin(2 * np.pi * (f0 * t + ph))) a = spectrum(t, v, fr) if a[win].max() / np.median(a[near]) >= 5: rec += 1 if rec >= 9: return A0 return None def n3_test(secs, P, T0): res = {"sectors": {}, "pairs": {}} stores = {} for s, S in secs.items(): e = {} for how in ("tool", "median"): t, y, ys = S.series(S.nova, 1.5, how, 4.0) tm = fold_template(t, ys, P, T0) r, sc = remove_scale(t, y, tm) X = harmonics_matrix(t, P) keep_t, keep_h = [], [] for ph in np.arange(0, 1, 0.1): unit = np.sin(2 * np.pi * (PF * t + ph)) keep_t.append(amp_at(t, remove_scale(t, y + unit, tm)[0] - r, PF)) keep_h.append(amp_at(t, remove_matrix(X, y + unit) - remove_matrix(X, y), PF)) e[how] = { "scale": sc, "A_1437": amp_at(t, r, PF), "snr_1437": local_snr_exact(t, r, PF), "retained_template": float(np.mean(keep_t)), "retained_template_worst_phase": float(np.min(keep_t)), "retained_30_harmonics": float(np.mean(keep_h)), "A_after_30_harmonics": amp_at(t, remove_matrix(X, y), PF), } if how == "tool": e[how]["limit_template"] = limit_ladder(t, y, lambda v: remove_scale(t, v, tm)[0]) e[how]["limit_30_harmonics"] = limit_ladder(t, y, lambda v: remove_matrix(X, v)) if how == "median": e[how]["limit_template"] = limit_ladder(t, y, lambda v: remove_scale(t, v, tm)[0]) if s == 89: stores[how] = (t, y, r) res["sectors"][str(s)] = e for name, (a, b) in PAIRS.items(): row = {} for r_ap in (1.5, 1.0): ta, ya, sa = secs[a].series(secs[a].nova, r_ap, "median", 4.0) tb, yb, sb = secs[b].series(secs[b].nova, r_ap, "median", 4.0) ma, mb = fold_template(ta, sa, P, T0), fold_template(tb, sb, P, T0) na = ta.size def both(v): return np.concatenate([remove_scale(ta, v[:na], ma)[0], remove_scale(tb, v[na:], mb)[0]]) t = np.concatenate([ta, tb]) raw = np.concatenate([ya, yb]) y = both(raw) row["r%.1f" % r_ap] = {"A_1437": amp_at(t, y, PF), "snr": local_snr_exact(t, y, PF), "limit": limit_ladder(t, raw, both)} res["pairs"][name] = row # chart data, sector 89 fr = np.arange(0.05, 10.0, 1 / (10 * (stores["median"][0][-1] - stores["median"][0][0]))) return res, stores, fr def write_spectrum(outdir, stores, fr): tm, ym, rm = stores["median"] tt, yt, rt = stores["tool"] a, b, c, d = spectrum(tm, ym, fr), spectrum(tm, rm, fr), spectrum(tt, yt, fr), spectrum(tt, rt, fr) with open(os.path.join(outdir, "tess_s89_spectrum_template.csv"), "w", encoding="utf-8", newline="\n") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(["freq_per_day", "period_d", "median_sky_before", "median_sky_after_one_scale", "tool_sky_before", "tool_sky_after_one_scale"]) for row in zip(fr, a, b, c, d): w.writerow([round(float(row[0]), 5), round(float(1 / row[0]), 5)] + [round(float(v), 3) for v in row[1:]]) def epoch_series(secs, sectors, P, T0, r_ap, how, hp): T, Y = [], [] for s in sectors: S = secs[s] t, y, ys = S.series(S.nova, r_ap, how, hp) res, _ = remove_scale(t, y, fold_template(t, ys, P, T0)) T.append(t) Y.append(res) return np.concatenate(T), np.concatenate(Y) def best_near(t, y, lo=0.26, hi=0.275, step=2e-5): grid = np.arange(lo, hi, step) a = spectrum(t, y, 1 / grid) i = int(np.argmax(a)) return float(grid[i]), float(a[i]) def percent_controls(t, y, f0): a = amp_at(t, y, f0) c = controls(t, y, f0) return a, float(np.mean(c < a) * 100), float(np.median(c)), int(c.size), float(c.max()) def block_groups(t): d = np.floor(t).astype(int) return [np.where(d == k)[0] for k in np.unique(d)] def n4_quiescent(secs, P, T0): t25, y25 = epoch_series(secs, (89, 90), P, T0, 1.0, "median", 1.0) P25, A25 = best_near(t25, y25) f0 = 1 / P25 out = {"P_fixed_from_2025": P25, "A_2025": A25, "by_recipe": {}} recipes = (("tool_r1.5", 1.5, "tool"), ("median_r1.5", 1.5, "median"), ("median_r1.0", 1.0, "median"), ("median_r0.75", 0.75, "median"), ("frame_r1.0", 1.0, "frame")) for name, r_ap, how in recipes: row = {} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37)), ("9", (9,)), ("10", (10,)), ("36", (36,)), ("37", (37,)), ("2023", (62, 63)), ("2025", (89, 90))): t, y = epoch_series(secs, sect, P, T0, r_ap, how, 1.0) a, pct, med, n, mx = percent_controls(t, y, f0) row[lab] = {"A": a, "percentile": pct, "controls_median": med, "controls_max": mx, "n_controls": n} out["by_recipe"][name] = row # shuffles at r = 1.0, median sky out["shuffles_r1.0"] = {} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37))): t, y = epoch_series(secs, sect, P, T0, 1.0, "median", 1.0) groups = block_groups(t) y0 = y - y.mean() a = amp_at(t, y, f0) ge = 0 arg = 2 * np.pi * f0 * (t - t.mean()) X = np.column_stack([np.cos(arg), np.sin(arg)]) XtXi = np.linalg.inv(X.T @ X) for _ in range(2000): o = RNG.permutation(len(groups)) v = np.concatenate([y0[groups[k]] for k in o]) if math.hypot(*(XtXi @ (X.T @ v))) >= a: ge += 1 fr = np.arange(0.05, 10.0, 1 / (5 * (t[-1] - t[0]))) ls = tp.LS(t, fr) spec = ls.amp(y) top = int(np.argmax(spec)) near = int(np.argmin(np.abs(fr - f0))) obs = spec[max(0, near - 3) : near + 4].max() gw = 0 for _ in range(1000): o = RNG.permutation(len(groups)) v = np.concatenate([y0[groups[k]] for k in o]) if ls.amp(v).max() >= obs: gw += 1 out["shuffles_r1.0"][lab] = {"A": a, "p_fixed_period_of_2000": ge / 2000, "whole_grid_fap_of_1000": gw / 1000, "top_of_grid_period_d": float(1 / fr[top]), "top_of_grid_amp": float(spec[top])} # the track, r = 1.5, median sky, each sector at its own best period near 0.2676 d track = {} for s in SECTORS: t, y = epoch_series(secs, (s,), P, T0, 1.5, "median", 1.0) bp, ba = best_near(t, y, 0.26, 0.275, 2e-5) track[str(s)] = {"best_period_d": bp, "A_at_best": ba, "A_at_fixed": amp_at(t, y, f0)} out["track_r1.5_median"] = track # stability with the high-pass out["highpass_r1.0"] = {} for hp in (0.5, 1.0, 2.0, 4.0): row = {} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37))): t, y = epoch_series(secs, sect, P, T0, 1.0, "median", hp) a, pct, med, n, mx = percent_controls(t, y, f0) row[lab] = {"A": a, "percentile": pct} out["highpass_r1.0"][str(hp)] = row # eight apertures 5 px off off = {} for s in (9, 10, 36, 37): S = secs[s] vals = [] for ang in range(0, 360, 45): c = (S.nova[0] + 5 * math.cos(math.radians(ang)), S.nova[1] + 5 * math.sin(math.radians(ang))) t, y, ys = S.series(c, 1.0, "median", 1.0) a, pct, med, n, mx = percent_controls(t, y, f0) vals.append({"angle": ang, "A": a, "percentile": pct}) off[str(s)] = vals out["off_target_r1.0"] = off offp = {} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37))): vals = [] for ang in range(0, 360, 45): T, Y = [], [] for s in sect: S = secs[s] c = (S.nova[0] + 5 * math.cos(math.radians(ang)), S.nova[1] + 5 * math.sin(math.radians(ang))) t, y, ys = S.series(c, 1.0, "median", 1.0) res, _ = remove_scale(t, y, fold_template(t, ys, P, T0)) T.append(t) Y.append(res) a, pct, med, n, mx = percent_controls(np.concatenate(T), np.concatenate(Y), f0) vals.append({"angle": ang, "A": a, "percentile": pct}) offp[lab] = vals out["off_target_r1.0_pairs"] = offp # pixel test. Each pixel's amplitude over the median of 48 of its own control frequencies, without and then with the neighbour removed from each pixel by one scale factor pix = {} for s in SECTORS: S = secs[s] fc = np.linspace(f0 - 0.5, f0 + 0.5, 60) fc = fc[np.abs(fc - f0) > 0.05] fc = fc[np.linspace(0, fc.size - 1, 48).astype(int)] j, i = int(round(S.nova[1])), int(round(S.nova[0])) row = {"nova_pixel": [i, j]} for lab, removed in (("no_removal", False), ("neighbour_removed", True)): tb, V = pixel_cube(S, 1.0, P, T0, removed) A, C = amps_from_cube(S, tb, V, 1 / f0) ctrl = np.array([amps_from_cube(S, tb, V, 1 / f)[0] for f in fc]) ratio = A / np.median(ctrl, axis=0) order = np.argsort(ratio.ravel())[::-1] top_j, top_i = np.unravel_index(int(order[0]), A.shape) row[lab] = { "nova_pixel_rank_of_225": int(np.where(order == j * S.nx + i)[0][0]) + 1, "top_pixel": [int(top_i), int(top_j)], "ratio_at_nova_pixel": float(ratio[j, i]), } if removed: t, y = epoch_series(secs, (s,), P, T0, 1.0, "median", 1.0) arg = 2 * np.pi * (t - 3000.0) * f0 X = np.column_stack([np.cos(arg), np.sin(arg)]) co = np.linalg.lstsq(X, y - y.mean(), rcond=None)[0] unit = co / math.hypot(*co) inph = unit[0] * C[0] + unit[1] * C[1] fit = fit_near(inph, S.nova, 3) ra, de = tn.world_of(S.ap, fit["x"], fit["y"]) row["inphase_fit"] = {"sep_nova_arcsec": sep_arcsec(ra, de, tp.TARGET_RA, tp.TARGET_DEC), "sigma_px": fit["s"], "amp": fit["A"], "at_bound": fit["at_bound"]} pix[str(s)] = row out["pixels"] = pix return out, P25 _cube_cache = {} def pixel_cube(S, hp, P, T0, removed): """Binned, high-passed pixel series, frame sky. With removed=True each pixel loses the star's folded curve, scaled by one factor of its own.""" key = (S.s, hp, removed) if key in _cube_cache: return _cube_cache[key] ok = S.fm <= np.nanpercentile(S.fm, 95) t = S.t[ok] cube = S.cube[ok] - S.fm[ok, None, None] idx = np.floor((t - S.t0) * 48).astype(int) u, inv = np.unique(idx, return_inverse=True) cnt = np.bincount(inv) tb = np.bincount(inv, weights=t) / cnt lab = tp.orbits(tb) V = np.zeros((tb.size, S.ny, S.nx)) for j in range(S.ny): for i in range(S.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 V[:, j, i] = tp.detrend_rm(tb, vb, lab, width=hp) if removed: f, okk = S.phot(S.star, 1.5, "frame") tsb, ysb, _ = S.binned(f, okk) ys = tp.detrend_rm(tsb, ysb, tp.orbits(tsb), width=hp) tm = fold_template(tsb, ys, P, T0) X = np.column_stack([np.ones_like(tsb), tm]) flat = V.reshape(tb.size, -1) coef, *_ = np.linalg.lstsq(X, flat, rcond=None) V = (flat - X @ coef).reshape(V.shape) V = V - V.mean(axis=0) _cube_cache[key] = (tb, V) return tb, V def amps_from_cube(S, tb, V, period): arg = 2 * np.pi * (tb - 3000.0) / period X = np.column_stack([np.cos(arg), np.sin(arg)]) co = np.linalg.inv(X.T @ X) @ (X.T @ V.reshape(tb.size, -1)) return np.hypot(co[0], co[1]).reshape(S.ny, S.nx), co.reshape(2, S.ny, S.nx) def n5_periods(secs, P, T0): out = {"epochs": {}} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37)), ("2023", (62, 63)), ("2025", (89, 90)), ("62", (62,)), ("63", (63,))): t, y = epoch_series(secs, sect, P, T0, 1.0, "median", 1.0) best, amp = best_near(t, y, 0.2655, 0.2695, 1e-5) groups = block_groups(t) boots = [] for _ in range(1000): pick = RNG.integers(0, len(groups), len(groups)) sel = np.concatenate([groups[k] for k in pick]) boots.append(best_near(t[sel], y[sel], best - 0.0015, best + 0.0015, 1e-5)[0]) out["epochs"][lab] = {"P_d": best, "A": amp, "p16": float(np.percentile(boots, 16)), "p84": float(np.percentile(boots, 84))} # alias chance P25 = out["epochs"]["2025"]["P_d"] ep = {k: epoch_series(secs, PAIRS[k], P, T0, 1.0, "median", 1.0) for k in ("2019", "2021", "2025")} trials = np.arange(P25 - 0.0006, P25 + 0.0006, 5e-7) A25 = spectrum(ep["2025"][0], ep["2025"][1], 1 / trials) keep = A25 > 0.9 * A25.max() trial_keep = trials[keep] Ph = {k: np.array([phase_only(t, y, 1 / q) for q in trial_keep]) for k, (t, y) in ep.items()} Z = np.abs(sum(np.exp(2j * np.pi * Ph[k]) for k in Ph)) / 3 base = np.array([Ph[k] for k in Ph]) def chance(mask): sims = [] for _ in range(5000): off = RNG.uniform(0, 1, (3, 1)) sims.append((np.abs(np.exp(2j * np.pi * (base[:, mask] + off)).sum(axis=0)) / 3).max()) return float(np.mean(np.array(sims) >= Z[mask].max())) all_kept = np.ones(trial_keep.size, dtype=bool) i = int(np.argmax(Z)) inner = (trial_keep >= out["epochs"]["2025"]["p16"]) & (trial_keep <= out["epochs"]["2025"]["p84"]) k = int(np.where(inner)[0][np.argmax(Z[inner])]) tops = [q for q in range(1, Z.size - 1) if Z[q] > Z[q - 1] and Z[q] > Z[q + 1]] tops = sorted(tops, key=lambda q: -Z[q])[:6] out["alias"] = { "window_d": [float(trial_keep.min()), float(trial_keep.max())], "max_Z": float(Z[i]), "at_P_d": float(trial_keep[i]), "chance_of_that_or_higher": chance(all_kept), "best_inside_2025_range": {"P_d": float(trial_keep[k]), "Z": float(Z[k]), "chance": chance(inner)}, "top_solutions": [{"P_d": round(float(trial_keep[q]), 7), "Z": round(float(Z[q]), 3)} for q in tops], } Pfix = float(trial_keep[k]) out["fixed_period"] = Pfix phases = {} for s in SECTORS: t, y = epoch_series(secs, (s,), P, T0, 1.0, "median", 1.0) r = phase_of(t, y, 1 / Pfix) orbs = {} lab = tp.orbits(t) for q in np.unique(lab): m = lab == q orbs[str(int(q))] = phase_of(t[m], y[m], 1 / Pfix) phases[str(s)] = {"all": r, "orbits": orbs} out["phases_at_fixed_period"] = phases return out def phase_only(t, y, f): arg = 2 * np.pi * f * (t - 3000.0) X = np.column_stack([np.cos(arg), np.sin(arg), np.ones_like(t)]) c, *_ = np.linalg.lstsq(X, y, rcond=None) return math.atan2(c[1], c[0]) / (2 * np.pi) % 1.0 def phase_of(t, y, f): a = amp_at(t, y, f) c = controls(t, y, f, n=240) sig = float(np.median(c)) / 1.1774 return {"A": a, "phase": phase_only(t, y, f), "phase_err": sig / a / (2 * np.pi), "snr": a / sig, "mid_t": float(t.mean())} def n6_shape(secs, P, T0, n5): out = {} for lab, sect in (("2019", (9, 10)), ("2021", (36, 37)), ("2023", (62, 63)), ("2025", (89, 90))): Pk = n5["epochs"][lab]["P_d"] row = {} for name, r_ap in (("median_r1.0", 1.0), ("median_r1.5", 1.5)): t, y = epoch_series(secs, sect, P, T0, r_ap, "median", 1.0) vals = {} for h, fac in (("2P", 0.5), ("P", 1.0), ("P/2", 2.0), ("P/3", 3.0)): f0 = fac / Pk a = amp_at(t, y, f0) c = controls(t, y, f0) vals[h] = {"A": a, "controls_median": float(np.median(c)), "percentile": float(np.mean(c < a) * 100)} row[name] = vals out[lab] = row Pk = n5["epochs"]["2025"]["P_d"] t, y = epoch_series(secs, (89, 90), P, T0, 1.0, "median", 1.0) ph = ((t - 3000.0) / (2 * Pk)) % 1.0 b = np.minimum((ph * 16).astype(int), 15) m = np.array([y[b == i].mean() for i in range(16)]) e = np.array([y[b == i].std() / math.sqrt((b == i).sum()) for i in range(16)]) out["odd_even_2025"] = {"rms_first_half_minus_second": float(np.sqrt(np.mean((m[:8] - m[8:]) ** 2))), "mean_bin_error": float(e.mean()), "fold_on_2P": [round(float(v), 2) for v in m]} return out def n7_tool_search(secs): grid = np.logspace(math.log10(0.01), math.log10(25.0), 500) out = {"trials_around_1.43": [float(grid[np.searchsorted(grid, 1.43) - 1]), float(grid[np.searchsorted(grid, 1.43)])]} for s, S in secs.items(): f, ok = S.phot(S.nova, 1.5, "tool") tb, yb, _ = S.binned(f, ok) lab = tp.orbits(tb) row = {"share_flux_at_or_below_zero": float(np.mean(f[ok] <= 0))} variants = {"raw_flux": yb, "orbit_means_removed": tp.detrend_none(tb, yb, lab)} pos = yb > 0 for name, v in variants.items(): a = spectrum(tb, v, 1 / grid) m12 = (grid >= 1) & (grid <= 2) row[name] = {"best_overall": float(grid[int(np.argmax(a))]), "best_in_1_2d": float(grid[np.where(m12)[0][int(np.argmax(a[m12]))]])} if pos.sum() > 50: a = spectrum(tb[pos], -2.5 * np.log10(yb[pos]), 1 / grid) m12 = (grid >= 1) & (grid <= 2) row["magnitudes_where_positive"] = {"best_overall": float(grid[int(np.argmax(a))]), "best_in_1_2d": float(grid[np.where(m12)[0][int(np.argmax(a[m12]))]]), "n_used": int(pos.sum()), "n_all": int(pos.size)} out[str(s)] = row return out def tidy(v): """Round for the file, so that its bytes don't depend on the last digits of a linear solve.""" if isinstance(v, dict): return {k: tidy(x) for k, x in v.items()} if isinstance(v, (list, tuple)): return [tidy(x) for x in v] if isinstance(v, (float, np.floating)): return round(float(v), 6) if isinstance(v, (np.integer,)): return int(v) return v def main(): folder, outdir = sys.argv[1:3] os.makedirs(outdir, exist_ok=True) secs = {s: Sector(folder, s) for s in SECTORS} res = {"note": "Addendum 8. These numbers follow a separate review of the page, and supersede F8, F5/F7, G5, H2, H5 and F's folds."} n1, P, T0 = n1_timing(secs) res["N1_timing"] = n1 print("N1", n1["P_d"], n1["T0_BJD"], n1["rms_d"], n1["n_eclipses_kept"], flush=True) res["N2_refold"] = n2_refold(secs, P, T0) print("N2 done", flush=True) n3, stores, fr = n3_test(secs, P, T0) res["N3_one_scale"] = n3 write_spectrum(outdir, stores, fr) print("N3 done", flush=True) n4, P25 = n4_quiescent(secs, P, T0) res["N4_quiescent"] = n4 print("N4 done", P25, flush=True) n5 = n5_periods(secs, P, T0) res["N5_periods"] = n5 print("N5 done", flush=True) res["N6_shape"] = n6_shape(secs, P, T0, n5) res["N7_tool_search"] = n7_tool_search(secs) with open(os.path.join(outdir, "review_tess.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(tidy(res), fh, indent=1) print("wrote review_tess.json", flush=True) if __name__ == "__main__": main()