"""Re-measure TOI-125 b and c transit times from public TESS light curves. Reproduces the transit-timing variations reported by Naponiello et al. (2026, arXiv:2612.02068, CC BY 4.0, accepted by A&A) from the same public data: TESS SPOC 2-minute PDCSAP light curves of TIC 52368076, sectors 1, 2, 28, 68, 69, 95 and 96. Method (deliberately simpler than the paper's, and stated in the post): * keep QUALITY == 0 cadences with finite PDCSAP flux; normalise each sector by its median; * cut a window of +-0.35 d around each transit predicted from a linear ephemeris (the ephemeris only places the windows; it is fitted to the paper's Table 3 times for that purpose); * mask the other planets' transits (+-0.15 d) and drop windows where one overlaps the target's; * keep windows with at least 42 % of the expected 2-minute cadences after masking, and at least 20 cadences on each side of the predicted mid-time (0.07 to 0.2 d before and after it); * fit all windows of one planet jointly: a symmetric trapezoid (shared depth, total duration and ingress time), one mid-transit time per window and a linear baseline per window, by least squares on the SPOC flux errors; * uncertainties come from the covariance matrix scaled by the reduced chi-square; * our own linear ephemeris (weighted least squares on our times) defines O-C; * a sinusoid with a shared period is fitted to the O-C of both planets by a period grid. The trapezoid has no limb darkening, so depth and duration are not physical parameters; the mid-time of a symmetric transit does not depend on that choice. Run (see provenance.md for hashes; FITS files are not in the repository): uv run --no-project --python 3.13 --with astropy==8.0.3 --with numpy==2.5.5 \ --with scipy==1.18.1 --with matplotlib==3.11.2 python -I analysis.py """ from __future__ import annotations import csv import json import math import pathlib import sys import numpy as np from astropy.io import fits from scipy.optimize import least_squares HERE = pathlib.Path(__file__).resolve().parent REPO = HERE.parents[3] sys.path.insert(0, str(REPO / ".claude" / "skills" / "blog-post" / "scripts")) import figstyle # noqa: E402 FILES = [ "tess2018206045859-s0001-0000000052368076-0120-s_lc.fits", "tess2018234235059-s0002-0000000052368076-0121-s_lc.fits", "tess2020212050318-s0028-0000000052368076-0190-s_lc.fits", "tess2023209231226-s0068-0000000052368076-0262-s_lc.fits", "tess2023237165326-s0069-0000000052368076-0264-s_lc.fits", "tess2025206162959-s0095-0000000052368076-0292-s_lc.fits", "tess2025232030459-s0096-0000000052368076-0293-s_lc.fits", ] HALF_WINDOW = 0.35 # d MASK_OTHER = 0.15 # d MIN_COVERAGE = 0.42 # fraction of the expected cadences in a window, after masking MINUTES = 1440.0 def load_paper_times() -> dict[str, list[tuple[float, float]]]: """Table 3 of Naponiello et al. 2026: (BTJD, mean of the +/- errors in days).""" out: dict[str, list[tuple[float, float]]] = {} with open(HERE / "data" / "naponiello2026_table3.csv") as fh: rows = [r for r in csv.reader(fh) if r and not r[0].startswith("#")] for planet, t0, ep, em in rows[1:]: out.setdefault(planet, []).append((float(t0), (float(ep) + float(em)) / 2 / MINUTES)) return out def load_light_curves(folder: pathlib.Path): ts, fs, es, ss = [], [], [], [] for name in FILES: with fits.open(folder / name, memmap=False) as hdul: h0, d = hdul[0].header, hdul[1].data if hdul[1].header.get("TIMESYS") != "TDB": raise SystemExit(f"{name}: TIMESYS is not TDB") t = np.asarray(d["TIME"], float) f = np.asarray(d["PDCSAP_FLUX"], float) e = np.asarray(d["PDCSAP_FLUX_ERR"], float) q = np.asarray(d["QUALITY"], int) ok = (q == 0) & np.isfinite(t) & np.isfinite(f) & np.isfinite(e) med = np.median(f[ok]) ts.append(t[ok]); fs.append(f[ok] / med); es.append(e[ok] / med) ss.append(np.full(ok.sum(), int(h0["SECTOR"]))) return (np.concatenate(ts), np.concatenate(fs), np.concatenate(es), np.concatenate(ss)) def linear_ephemeris(times: np.ndarray, sig: np.ndarray, period_guess: float): epochs = np.round((times - times[0]) / period_guess) w = 1 / sig**2 A = np.vstack([np.ones_like(epochs), epochs]).T cov = np.linalg.inv(A.T @ (A * w[:, None])) t0, p = cov @ (A.T @ (w * times)) return float(t0), float(p), epochs.astype(int), cov def trapezoid(t, tc, depth, t14, tau): x = np.abs(t - tc) half = t14 / 2 f = np.clip((half - x) / tau, 0.0, 1.0) return 1.0 - depth * f def fit_planet(name, t, f, e, s, windows, shape0): """Joint fit: shared (depth, T14, tau); per window (tc, a, b).""" n = len(windows) idx = [w["idx"] for w in windows] def unpack(p): depth, t14, tau = p[:3] rest = p[3:].reshape(n, 3) return depth, t14, tau, rest def resid(p): depth, t14, tau, rest = unpack(p) out = [] for k, ii in enumerate(idx): tc, a, b = rest[k] tt = t[ii] model = trapezoid(tt, tc, depth, t14, tau) * (a + b * (tt - windows[k]["pred"])) out.append((f[ii] - model) / e[ii]) return np.concatenate(out) p0 = [shape0["depth"], shape0["t14"], shape0["tau"]] lo = [0.0, 0.03, 0.001] hi = [0.01, 0.4, 0.1] for w in windows: p0 += [w["tc0"], 1.0, 0.0] lo += [w["pred"] - HALF_WINDOW + 0.05, 0.9, -1.0] hi += [w["pred"] + HALF_WINDOW - 0.05, 1.1, 1.0] sol = least_squares(resid, np.array(p0), bounds=(lo, hi), x_scale="jac", method="trf", xtol=1e-12, ftol=1e-12, gtol=1e-12, max_nfev=20000) r = sol.fun dof = r.size - sol.x.size chi2r = float(r @ r / dof) J = sol.jac cov = np.linalg.pinv(J.T @ J) * chi2r sig = np.sqrt(np.diag(cov)) depth, t14, tau, rest = unpack(sol.x) srest = sig[3:].reshape(n, 3) for k, w in enumerate(windows): w["tc"] = float(rest[k, 0]) w["tc_sig"] = float(srest[k, 0]) return {"depth": float(depth), "depth_sig": float(sig[0]), "t14": float(t14), "t14_sig": float(sig[1]), "tau": float(tau), "tau_sig": float(sig[2]), "chi2_red": chi2r, "n_points": int(r.size), "n_params": int(sol.x.size), "status": int(sol.status)} def grid_start(t, f, e, ii, pred, shape0): """Best mid-time on a 1-minute grid with the nominal shape and a fitted linear baseline.""" best, best_tc = np.inf, pred tt, ff, ee = t[ii], f[ii], e[ii] for tc in np.arange(pred - 0.2, pred + 0.2, 1 / MINUTES): m = trapezoid(tt, tc, shape0["depth"], shape0["t14"], shape0["tau"]) A = np.vstack([m, m * (tt - pred)]).T / ee[:, None] coef, *_ = np.linalg.lstsq(A, ff / ee, rcond=None) chi2 = np.sum((ff / ee - A @ coef) ** 2) if chi2 < best: best, best_tc = chi2, tc return best_tc def sinusoid_fit(times_by_planet, periods, window=None): """O-C = c_k + A_k sin(2 pi t / P) + B_k cos(2 pi t / P), shared P; weighted LSQ per P. Returns the best fit over `periods` (or over the part inside `window`) and the chi-square of every trial period, so aliases can be shown. """ curve = [] fits_at = {} for P in periods: chi2 = 0.0 params = {} for name, (t, oc, sig) in times_by_planet.items(): w = 1 / sig A = np.vstack([np.ones_like(t), np.sin(2 * np.pi * t / P), np.cos(2 * np.pi * t / P)]).T coef, *_ = np.linalg.lstsq(A * w[:, None], oc * w, rcond=None) chi2 += float(np.sum(((oc - A @ coef) * w) ** 2)) params[name] = coef curve.append(chi2) fits_at[float(P)] = (chi2, params) curve = np.array(curve) sel = np.ones_like(periods, bool) if window is None else (periods >= window[0]) & (periods <= window[1]) k = int(np.argmin(np.where(sel, curve, np.inf))) P = float(periods[k]) chi2, params = fits_at[P] out = {"super_period_d": P, "chi2": chi2} for name, (c0, a, b) in params.items(): out[name] = {"semi_amplitude_min": float(math.hypot(a, b)), "phase_rad": float(math.atan2(b, a))} dphi = (out["c"]["phase_rad"] - out["b"]["phase_rad"]) % (2 * math.pi) out["phase_difference_deg"] = math.degrees(dphi) return out, curve def main(folder: str) -> int: folder = pathlib.Path(folder) paper = load_paper_times() t, f, e, s = load_light_curves(folder) print(f"{t.size} good 2-min cadences in {len(FILES)} sectors") # Linear ephemerides from Table 3, used only to place windows and mask other planets. eph = {} guess = {"b": 4.654, "c": 9.151, "d": 19.98, "e": 49.06} for name, rows in paper.items(): tt = np.array([r[0] for r in rows]); ss = np.array([r[1] for r in rows]) t0, p, _, _ = linear_ephemeris(tt, ss, guess[name]) eph[name] = (t0, p) other_centres = {k: np.array([r[0] for r in v]) for k, v in paper.items()} shape0 = {"b": {"depth": 0.0009, "t14": 0.11, "tau": 0.01}, "c": {"depth": 0.0009, "t14": 0.13, "tau": 0.01}} results = {} rows_out = [] for name in ("b", "c"): t0, p = eph[name] n_lo = math.floor((t.min() - t0) / p) - 1 n_hi = math.ceil((t.max() - t0) / p) + 1 windows = [] dropped = {"no data": 0, "coverage": 0, "overlap": 0} for n in range(n_lo, n_hi + 1): pred = t0 + n * p inwin = np.abs(t - pred) < HALF_WINDOW if inwin.sum() == 0: continue # other planets: drop overlaps, mask nearby transits mask = inwin.copy() overlap = False for other, centres in other_centres.items(): if other == name: continue to, po = eph[other] no = np.round((pred - to) / po) cands = np.concatenate([centres, [to + no * po]]) near = cands[np.abs(cands - pred) < HALF_WINDOW + MASK_OTHER] for c in near: if abs(c - pred) < 0.2: overlap = True mask &= np.abs(t - c) > MASK_OTHER if overlap: dropped["overlap"] += 1 continue ii = np.where(mask)[0] expected = 2 * HALF_WINDOW * MINUTES / 2.0 # 2-min cadence before = np.sum((t[ii] > pred - 0.2) & (t[ii] < pred - 0.07)) after = np.sum((t[ii] < pred + 0.2) & (t[ii] > pred + 0.07)) if ii.size < MIN_COVERAGE * expected or before < 20 or after < 20: dropped["coverage"] += 1 continue windows.append({"epoch": n, "pred": pred, "idx": ii, "sector": int(np.median(s[ii]))}) for w in windows: w["tc0"] = grid_start(t, f, e, w["idx"], w["pred"], shape0[name]) shape = fit_planet(name, t, f, e, s, windows, shape0[name]) tc = np.array([w["tc"] for w in windows]); sig = np.array([w["tc_sig"] for w in windows]) T0, P, ep, cov = linear_ephemeris(tc, sig, p) oc = tc - (T0 + ep * P) # match to the paper's times ptimes = np.array([r[0] for r in paper[name]]); psig = np.array([r[1] for r in paper[name]]) diffs = [] for k, w in enumerate(windows): j = int(np.argmin(np.abs(ptimes - w["tc"]))) if abs(ptimes[j] - w["tc"]) < 0.1: d = (w["tc"] - ptimes[j]) * MINUTES comb = math.hypot(w["tc_sig"], psig[j]) * MINUTES w.update(paper_tc=float(ptimes[j]), paper_sig=float(psig[j]), diff_min=d, diff_over_sigma=d / comb) diffs.append((d, d / comb)) rows_out.append({"planet": name, "sector": w["sector"], "epoch": int(ep[k]), "tc_btjd": round(w["tc"], 5), "tc_sigma_min": round(w["tc_sig"] * MINUTES, 2), "oc_min": round(oc[k] * MINUTES, 2), "paper_tc_btjd": w.get("paper_tc", ""), "paper_sigma_min": round(w["paper_sig"] * MINUTES, 2) if "paper_sig" in w else "", "diff_min": round(w["diff_min"], 2) if "diff_min" in w else ""}) d = np.array([x[0] for x in diffs]); z = np.array([x[1] for x in diffs]) results[name] = { "windows_fitted": len(windows), "dropped": dropped, "paper_times": int(len(paper[name])), "matched_to_paper": int(len(diffs)), "shape": shape, "ephemeris": {"T0_btjd": T0, "T0_sig_min": math.sqrt(cov[0, 0]) * MINUTES, "P_d": P, "P_sig_min": math.sqrt(cov[1, 1]) * MINUTES}, "median_sigma_min": float(np.median(sig) * MINUTES), "paper_median_sigma_min_matched": float(np.median( [w["paper_sig"] for w in windows if "paper_sig" in w]) * MINUTES), "median_abs_diff_min": float(np.median(np.abs(d))), "max_abs_diff_min": float(np.max(np.abs(d))), "within_1sigma": int(np.sum(np.abs(z) <= 1)), "within_2sigma": int(np.sum(np.abs(z) <= 2)), "oc_rms_min": float(np.std(oc) * MINUTES), "chi2_linear": float(np.sum((oc / sig) ** 2)), "dof_linear": int(len(oc) - 2), } results[name]["_series"] = (tc, oc * MINUTES, sig * MINUTES, windows) series = {k: (v["_series"][0], v["_series"][1], v["_series"][2]) for k, v in results.items()} periods = np.arange(100.0, 600.0, 0.25) best_any, curve = sinusoid_fit(series, periods) best_near, _ = sinusoid_fit(series, periods, window=(250.0, 330.0)) pb, pc = results["b"]["ephemeris"]["P_d"], results["c"]["ephemeris"]["P_d"] analytic = 1.0 / abs(2.0 / pc - 1.0 / pb) # Lithwick et al. 2012, j = 2 results["sinusoid"] = { "global_minimum": best_any, "best_between_250_and_330_d": best_near, "delta_chi2_alias_minus_near": best_near["chi2"] - best_any["chi2"], "analytic_super_period_d": analytic, "one_year_alias_of_analytic_d": 1.0 / (1.0 / analytic + 1.0 / 365.25), } # sensitivity of the formula to the input periods (days of super-period per minute of period) results["sinusoid"]["formula_days_per_minute_of_Pb"] = analytic**2 / pb**2 / MINUTES results["sinusoid"]["formula_days_per_minute_of_Pc"] = analytic**2 * 2 / pc**2 / MINUTES # fit quality: 3 coefficients per planet plus the shared period n_times = sum(len(v[0]) for v in series.values()) dof = n_times - (3 * len(series) + 1) red = best_any["chi2"] / dof results["sinusoid"].update({ "n_times": n_times, "dof": dof, "chi2_red_global_minimum": red, "delta_chi2_over_chi2_red": (best_near["chi2"] - best_any["chi2"]) / red, }) results["_curve"] = (periods, curve) # outputs data_dir = HERE / "data" with open(data_dir / "our_transit_times.csv", "w", newline="") as fh: wr = csv.DictWriter(fh, fieldnames=list(rows_out[0].keys()), lineterminator="\n") wr.writeheader(); wr.writerows(rows_out) clean = {k: {kk: vv for kk, vv in v.items() if kk != "_series"} if isinstance(v, dict) else v for k, v in results.items() if k != "_curve"} clean["n_cadences"] = int(t.size) with open(data_dir / "results.json", "w") as fh: json.dump(clean, fh, indent=1, sort_keys=True) fh.write("\n") make_figures(results, paper, t, f, e) print(json.dumps(clean, indent=1, sort_keys=True)) return 0 def make_figures(results, paper, t, f, e): fig_dir = HERE / "figures" for theme in figstyle.THEMES: with figstyle.style(theme) as c: fig, axes = figstyle.figure(7.2, 5.0, nrows=2, sharex=True) for ax, name in zip(axes, ("b", "c")): tc, oc, sig, windows = results[name]["_series"] eph = results[name]["ephemeris"] pt = np.array([r[0] for r in paper[name]]) ps = np.array([r[1] for r in paper[name]]) * MINUTES pep = np.round((pt - eph["T0_btjd"]) / eph["P_d"]) poc = (pt - (eph["T0_btjd"] + pep * eph["P_d"])) * MINUTES ax.errorbar(pt, poc, yerr=ps, fmt="s", mfc="none", mec=c["graphite"], ecolor=c["rule"], ms=4, mew=0.8, label="Naponiello et al. 2026, Table 3") ax.errorbar(tc, oc, yerr=sig, fmt="o", color=c["accent"], ecolor=c["accent"], ms=3.5, elinewidth=0.8, label="This re-measurement") ax.axhline(0, color=c["graphite"], lw=0.6) ax.set_ylabel("O − C (min)") ax.set_title(f"TOI-125 {name}", loc="left") axes[1].set_xlabel("BJD_TDB − 2457000 (d)") axes[0].legend(loc="upper right", ncols=2) figstyle.save(fig, fig_dir / "fig-1-oc", theme) # Figure 2: every fitted transit of planet c, aligned on our mid-times, binned. fig, ax = figstyle.figure(7.2, 3.4) tc, oc, sig, windows = results["c"]["_series"] sh = results["c"]["shape"] xs, ys = [], [] for w in windows: ii = w["idx"] xs.append((t[ii] - w["tc"]) * 24); ys.append(f[ii]) x = np.concatenate(xs); y = np.concatenate(ys) # divide out each window's baseline approximately by its out-of-transit median yy = [] for w, xx, y1 in zip(windows, xs, ys): oot = np.abs(xx) > sh["t14"] * 24 / 2 + 0.3 yy.append(y1 / np.median(y1[oot])) y = np.concatenate(yy) ax.plot(x, (y - 1) * 1e6, ".", color=c["graphite"], ms=1.2, alpha=0.35, label="2-min PDCSAP cadences", rasterized=True) bins = np.arange(-8.0, 8.0001, 0.25) mid = (bins[:-1] + bins[1:]) / 2 bmean = np.array([np.mean(y[(x >= a) & (x < b)]) if np.any((x >= a) & (x < b)) else np.nan for a, b in zip(bins[:-1], bins[1:])]) ax.plot(mid, (bmean - 1) * 1e6, "o", color=c["accent"], ms=3.5, label="15-min bins") xm = np.linspace(-8, 8, 2000) ax.plot(xm, (trapezoid(xm / 24, 0.0, sh["depth"], sh["t14"], sh["tau"]) - 1) * 1e6, "-", color=c["ink"], lw=1.0, label="Shared trapezoid fit") ax.set_xlim(-8, 8); ax.set_ylim(-3000, 2000) ax.set_xlabel("Hours from each fitted mid-transit time") ax.set_ylabel("Relative flux (ppm)") ax.set_title(f"TOI-125 c: {len(windows)} TESS transits aligned on their own mid-times", loc="left") ax.legend(loc="lower left", ncols=3) figstyle.save(fig, fig_dir / "fig-2-transits-c", theme) # Figure 3: chi-square of a shared sinusoid against trial super-period. periods, curve = results["_curve"] sin = results["sinusoid"] fig, ax = figstyle.figure(7.2, 3.0) ax.plot(periods, curve, "-", color=c["accent"], lw=1.2) for x, label, ls in ((sin["global_minimum"]["super_period_d"], "best sinusoid", "--"), (sin["analytic_super_period_d"], "near-resonance formula", ":")): ax.axvline(x, color=c["graphite"], lw=0.8, ls=ls) ax.text(x + 4, np.nanmax(curve) * 0.95, f"{label}\n{x:.0f} d", fontsize=8, color=c["ink"], va="top") ax.set_xlabel("Trial super-period (d)") ax.set_ylabel("χ² of sinusoid fit to O − C") ax.set_title("TESS-only timings: a one-year alias fits about as well", loc="left") figstyle.save(fig, fig_dir / "fig-3-superperiod", theme) # CSV equivalents of the plotted values (figure 1 is data/our_transit_times.csv plus Table 3) periods, curve = results["_curve"] with open(HERE / "figures" / "fig-3-chi2.csv", "w") as fh: fh.write("trial_period_d,chi2\n") for P, v in zip(periods, curve): fh.write(f"{P:.2f},{v:.3f}\n") with open(HERE / "figures" / "fig-2-binned.csv", "w") as fh: fh.write("hours_from_mid,binned_relative_flux_ppm\n") for m, v in zip(mid, bmean): if np.isfinite(v): fh.write(f"{m:.3f},{(v - 1) * 1e6:.1f}\n") if __name__ == "__main__": sys.exit(main(sys.argv[1]))