#!/usr/bin/env python3 """TESS period check for Gaia22alz, following RULES_before_running.txt section A. Reads MAST TESScut zips as data with a small FITS reader of our own (no third-party code from the download). Usage: python -I tess_period.py [gaia_cone.csv] Writes tess_summary.json and tess_summary.txt to the out folder. Files are LF only. """ import io import json import math import os import re import sys import zipfile import numpy as np TARGET_RA = 142.47114 TARGET_DEC = -56.29057 PAPER_P = 1.437 PAPER_F = 1.0 / PAPER_P SECTORS = [9, 10, 36, 37, 62, 63, 89, 90] PAIRS = [(9, 10), (36, 37), (62, 63), (89, 90)] ZP = 20.44 # TESS zero point, e-/s (Vanderspek et al. 2018) BLOCK = 2880 def read_header(buf, pos): cards = {} order = [] while True: block = buf[pos:pos + BLOCK] pos += BLOCK ended = False for i in range(0, BLOCK, 80): card = block[i:i + 80].decode("ascii", "replace") key = card[:8].strip() if key == "END": ended = True break if card[8:10] == "= ": val = card[10:].split("/")[0].strip() if val.startswith("'"): m = re.match(r"'(.*?)'", card[10:]) val = m.group(1).strip() if m else val elif val in ("T", "F"): val = val == "T" else: try: val = int(val) except ValueError: try: val = float(val) except ValueError: pass cards[key] = val order.append(key) if ended: break return cards, pos def read_fits(buf): """Return a list of (header, data_bytes).""" hdus = [] pos = 0 while pos < len(buf): if buf[pos:pos + 6] not in (b"SIMPLE", b"XTENSI"): break hdr, pos = read_header(buf, pos) bitpix = abs(int(hdr.get("BITPIX", 8))) naxis = int(hdr.get("NAXIS", 0)) n = 1 if naxis else 0 for i in range(1, naxis + 1): n *= int(hdr.get("NAXIS%d" % i, 0)) size = n * bitpix // 8 + int(hdr.get("PCOUNT", 0)) data = buf[pos:pos + size] pos += size if size % BLOCK: pos += BLOCK - size % BLOCK hdus.append((hdr, data)) return hdus TFORM = {"J": (">i4", 4), "I": (">i2", 2), "E": (">f4", 4), "D": (">f8", 8), "B": ("u1", 1), "A": ("S1", 1), "L": ("S1", 1)} def read_table(hdr, data): nrows = int(hdr["NAXIS2"]) rowlen = int(hdr["NAXIS1"]) nf = int(hdr["TFIELDS"]) fields = [] for i in range(1, nf + 1): form = str(hdr["TFORM%d" % i]).strip() m = re.match(r"(\d*)([A-Z])", form) rep = int(m.group(1)) if m.group(1) else 1 code = m.group(2) name = str(hdr.get("TTYPE%d" % i, "F%d" % i)).strip() base = TFORM[code][0] if code == "A": fields.append((name, "S%d" % rep)) else: dim = str(hdr.get("TDIM%d" % i, "")).strip() if dim: shape = tuple(int(x) for x in re.findall(r"\d+", dim))[::-1] fields.append((name, base, shape)) elif rep > 1: fields.append((name, base, (rep,))) else: fields.append((name, base)) dt = np.dtype(fields) if dt.itemsize != rowlen: raise ValueError("row length mismatch %d %d" % (dt.itemsize, rowlen)) return np.frombuffer(data[: nrows * rowlen], dtype=dt, count=nrows) def pixel_of(hdr, ra, dec): """Linear WCS of the TESScut aperture extension: returns 0-based x, y.""" 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)))], ] ) # gnomonic projection a0, d0, a, d = map(math.radians, (crval1, crval2, ra, dec)) den = math.sin(d) * math.sin(d0) + math.cos(d) * math.cos(d0) * math.cos(a - a0) xi = math.degrees(math.cos(d) * math.sin(a - a0) / den) eta = math.degrees((math.sin(d) * math.cos(d0) - math.cos(d) * math.sin(d0) * math.cos(a - a0)) / den) dx, dy = np.linalg.solve(cd, [xi, eta]) return dx + crpix1 - 1, dy + crpix2 - 1 def weights(nx, ny, cx, cy, radius, sub=10): """Sub-pixel sampled aperture weights.""" off = (np.arange(sub) + 0.5) / sub - 0.5 w = np.zeros((ny, nx)) for j in range(ny): for i in range(nx): xx, yy = np.meshgrid(i + off, j + off) w[j, i] = np.mean((xx - cx) ** 2 + (yy - cy) ** 2 <= radius**2) return w def annulus(nx, ny, cx, cy, r1, r2): yy, xx = np.mgrid[0:ny, 0:nx] d2 = (xx - cx) ** 2 + (yy - cy) ** 2 return (d2 >= r1**2) & (d2 <= r2**2) def sky_mode(cube, mask): """Mode estimate 3*median - 2*mean after 3-sigma clipping, per cadence.""" vals = cube[:, mask] out = np.full(vals.shape[0], np.nan) for k in range(vals.shape[0]): v = vals[k] v = v[np.isfinite(v)] if v.size < 3: continue for _ in range(3): m, s = np.mean(v), np.std(v) keep = np.abs(v - m) <= 3 * s if keep.sum() < 3 or keep.all(): break v = v[keep] out[k] = 3 * np.median(v) - 2 * np.mean(v) return out def orbits(t): """Split at the largest gap near the middle of the sector.""" gaps = np.diff(t) mid = t[0] + (t[-1] - t[0]) / 2 idx = None best = 0 for i, g in enumerate(gaps): if g > 0.2 and abs(t[i] - mid) < 6 and g > best: best = g idx = i lab = np.zeros(t.size, dtype=int) if idx is not None: lab[idx + 1 :] = 1 return lab def running_median(t, y, width): out = np.empty_like(y) i0 = 0 i1 = 0 n = t.size for i in range(n): while t[i] - t[i0] > width / 2: i0 += 1 while i1 < n and t[i1] - t[i] <= width / 2: i1 += 1 out[i] = np.median(y[i0:i1]) return out def bin30(t, y, width=1.0 / 48): """Bin to 30 minutes on a common grid; a 30-min sector passes through almost unchanged.""" idx = np.floor((t - t[0]) / width).astype(np.int64) u, inv, cnt = np.unique(idx, return_inverse=True, return_counts=True) ty = np.bincount(inv, weights=t) / cnt yy = np.bincount(inv, weights=y) / cnt return ty, yy, cnt class LS: """Precomputed least-squares sinusoid amplitude at fixed times.""" def __init__(self, t, freqs): self.t = t self.f = freqs arg = 2 * np.pi * np.outer(freqs, t - t.mean()) self.c = np.cos(arg) self.s = np.sin(arg) self.cc = np.sum(self.c * self.c, axis=1) self.ss = np.sum(self.s * self.s, axis=1) self.cs = np.sum(self.c * self.s, axis=1) self.d = self.cc * self.ss - self.cs**2 def amp(self, y): y0 = y - np.mean(y) yc = self.c @ y0 ys = self.s @ y0 a = (yc * self.ss - ys * self.cs) / self.d b = (ys * self.cc - yc * self.cs) / self.d return np.sqrt(a * a + b * b) def freq_grid(span): df = 1.0 / (10 * span) return np.arange(0.05, 10.0 + df, df) def peaks(freqs, amp, n=5): idx = np.where((amp[1:-1] > amp[:-2]) & (amp[1:-1] > amp[2:]))[0] + 1 idx = idx[np.argsort(amp[idx])[::-1]][:n] return [{"period_d": round(float(1 / freqs[i]), 4), "freq": round(float(freqs[i]), 5), "amp": float(amp[i])} for i in idx] def local_snr(freqs, amp, i): w = (np.abs(freqs - freqs[i]) <= 0.5) & (np.abs(freqs - freqs[i]) >= 0.05) return float(amp[i] / np.median(amp[w])) def near_target(freqs, amp, target=PAPER_F, frac=0.05): lo, hi = target / (1 + frac), target / (1 - frac) w = np.where((freqs >= lo) & (freqs <= hi))[0] # the highest local maximum in the window, else the highest value cand = [i for i in w if 0 < i < len(freqs) - 1 and amp[i] >= amp[i - 1] and amp[i] >= amp[i + 1]] if cand: i = max(cand, key=lambda k: amp[k]) else: i = w[np.argmax(amp[w])] return i def block_shuffle_fap(ls, t, y, amp_obs, ndraw=1000, block=1.0, seed=20261104): rng = np.random.default_rng(seed) idx = np.floor((t - t[0]) / block).astype(int) groups = [np.where(idx == k)[0] for k in np.unique(idx)] y0 = y - np.mean(y) count = 0 maxima = np.empty(ndraw) for d in range(ndraw): order = rng.permutation(len(groups)) ys = np.concatenate([y0[groups[k]] for k in order]) # lengths may differ, so the sequence is mapped on to the sorted times in order maxima[d] = np.max(ls.amp(ys)) return float(np.mean(maxima >= amp_obs)), float(np.percentile(maxima, 99)) def fit_fixed(t, y, f, t0): arg = 2 * np.pi * f * (t - t0) X = np.column_stack([np.cos(arg), np.sin(arg), np.ones_like(t)]) coef, *_ = np.linalg.lstsq(X, y, rcond=None) res = y - X @ coef s2 = np.sum(res**2) / (t.size - 3) cov = s2 * np.linalg.inv(X.T @ X) a, b = coef[0], coef[1] amp = math.hypot(a, b) # y = A cos(2 pi f (t-t0) - phi) ; phase of maximum in cycles phi = math.atan2(b, a) / (2 * np.pi) err_amp = math.sqrt(0.5 * (cov[0, 0] + cov[1, 1])) return {"amp": amp, "phase_cycles": phi % 1.0, "amp_err": err_amp, "phase_err": err_amp / amp / (2 * np.pi), "rms": math.sqrt(s2)} def load_sector(folder, s): zpath = os.path.join(folder, "cut-s%04d.zip" % s) with zipfile.ZipFile(zpath) as z: names = [n for n in z.namelist() if n.endswith(".fits")] buf = z.read(names[0]) hdus = read_fits(buf) tab = read_table(hdus[1][0], hdus[1][1]) return hdus, tab, names[0] def sector_photometry(hdus, tab, radius=1.5, centre=None, r_in=2.5, r_out=3.5, q_mask=None): ap_hdr = hdus[2][0] cube = np.array(tab["FLUX"], dtype=float) # (n, ny, nx) ny, nx = cube.shape[1:] if centre is None: cx, cy = pixel_of(ap_hdr, TARGET_RA, TARGET_DEC) else: cx, cy = centre w = weights(nx, ny, cx, cy, radius) ann = annulus(nx, ny, cx, cy, r_in, r_out) t = np.array(tab["TIME"], dtype=float) q = np.array(tab["QUALITY"], dtype=int) sky = sky_mode(cube, ann) good = np.isfinite(t) & (q == 0) & np.isfinite(sky) good &= np.all(np.isfinite(cube), axis=(1, 2)) | (np.sum(np.isfinite(cube), axis=(1, 2)) > 0.9 * nx * ny) limit = np.nanpercentile(sky[good], 95) good &= sky <= limit flux = np.nansum(w * (cube - sky[:, None, None]), axis=(1, 2)) return t[good], flux[good], sky[good], (cx, cy), good def detrend_none(t, y, lab): out = y.copy() for k in np.unique(lab): out[lab == k] -= np.mean(out[lab == k]) return out def detrend_rm(t, y, lab, width=4.0): out = y.copy() for k in np.unique(lab): m = lab == k out[m] -= running_median(t[m], y[m], width) return out def main(): folder = sys.argv[1] outdir = sys.argv[2] gaia = sys.argv[3] if len(sys.argv) > 3 else None os.makedirs(outdir, exist_ok=True) summary = {"rules": "RULES_before_running.txt section A", "sectors": {}} store = {} lines = [] for s in SECTORS: hdus, tab, name = load_sector(folder, s) phdr = hdus[0][0] sec = {"file": name, "exposure_cadences": int(tab.shape[0])} res = {} for radius in (1.5, 1.0, 2.0): t, f, sky, c, good = sector_photometry(hdus, tab, radius=radius) lab = orbits(t) for det in ("orbit_mean", "rm4d"): y = detrend_none(t, f, lab) if det == "orbit_mean" else detrend_rm(t, f, lab) tb, yb, cnt = bin30(t, y) fr = freq_grid(tb[-1] - tb[0]) ls = LS(tb, fr) amp = ls.amp(yb) i = near_target(fr, amp) key = "r%.1f_%s" % (radius, det) res[key] = { "n_binned": int(tb.size), "span_d": round(float(tb[-1] - tb[0]), 2), "top_peaks": peaks(fr, amp), "near_1437": {"period_d": round(float(1 / fr[i]), 4), "amp_e_per_s": float(amp[i]), "snr": round(local_snr(fr, amp, i), 2)}, "median_flux_e_per_s": float(np.median(f)), "n_cadences_kept": int(t.size), } if radius == 1.5: fap, p99 = block_shuffle_fap(ls, tb, yb, amp[i], ndraw=1000) res[key]["near_1437"]["fap_block_shuffle"] = fap res[key]["near_1437"]["max_amp_99pct_shuffles"] = p99 top = np.argmax(amp) fap_top, _ = block_shuffle_fap(ls, tb, yb, amp[top], ndraw=1000, seed=7) res[key]["top_peak_fap"] = {"period_d": round(float(1 / fr[top]), 4), "amp": float(amp[top]), "snr": round(local_snr(fr, amp, top), 2), "fap": fap_top} if radius == 1.5: store[(s, det)] = (t, y, lab) sec["photometry"] = res sec["target_pixel_xy"] = [round(float(c[0]), 2), round(float(c[1]), 2)] sec["median_tmag_aperture_r1.5"] = round(ZP - 2.5 * math.log10(max(res["r1.5_orbit_mean"]["median_flux_e_per_s"], 1e-3)), 2) # per orbit t, f, sky, c, good = sector_photometry(hdus, tab, radius=1.5) lab = orbits(t) per_orbit = [] for k in np.unique(lab): m = lab == k for det in ("rm4d",): y = detrend_rm(t[m], f[m], lab[m]) tb, yb, cnt = bin30(t[m], y) fr = freq_grid(tb[-1] - tb[0]) ls = LS(tb, fr) amp = ls.amp(yb) i = near_target(fr, amp) fap, _ = block_shuffle_fap(ls, tb, yb, amp[i], ndraw=500, seed=11 + int(k)) per_orbit.append( { "orbit": int(k), "span_d": round(float(tb[-1] - tb[0]), 2), "top": peaks(fr, amp, 3), "near_1437": {"period_d": round(float(1 / fr[i]), 4), "amp": float(amp[i]), "snr": round(local_snr(fr, amp, i), 2), "fap": fap}, } ) sec["per_orbit"] = per_orbit # eight control apertures at 5 pixels ctrl = [] cx, cy = c for ang in range(0, 360, 45): ccx = cx + 5 * math.cos(math.radians(ang)) ccy = cy + 5 * math.sin(math.radians(ang)) tc, fc, _, _, _ = sector_photometry(hdus, tab, radius=1.5, centre=(ccx, ccy)) labc = orbits(tc) y = detrend_rm(tc, fc, labc) tb, yb, _ = bin30(tc, y) fr = freq_grid(tb[-1] - tb[0]) amp = LS(tb, fr).amp(yb) i = near_target(fr, amp) ctrl.append({"angle": ang, "near_1437_period": round(float(1 / fr[i]), 4), "amp": float(amp[i]), "snr": round(local_snr(fr, amp, i), 2), "median_flux": float(np.median(fc))}) sec["controls_5px"] = ctrl summary["sectors"][str(s)] = sec print("sector", s, "done", flush=True) # pairs: joint period and phase coherence at the paper's period and at the best nearby period pair_out = {} for a, b in PAIRS: ta, ya, la = store[(a, "rm4d")] tb, yb, lb = store[(b, "rm4d")] t = np.concatenate([ta, tb]) y = np.concatenate([ya, yb]) tbin, ybin, _ = bin30(t, y) fr = freq_grid(tbin[-1] - tbin[0]) ls = LS(tbin, fr) amp = ls.amp(ybin) i = near_target(fr, amp) fap, _ = block_shuffle_fap(ls, tbin, ybin, amp[i], ndraw=1000, seed=3) t0 = float(tbin.mean()) pair_out["%d+%d" % (a, b)] = { "span_d": round(float(tbin[-1] - tbin[0]), 2), "top_peaks": peaks(fr, amp), "near_1437": {"period_d": round(float(1 / fr[i]), 5), "amp": float(amp[i]), "snr": round(local_snr(fr, amp, i), 2), "fap": fap}, } for label, fq in (("paper_1.437", PAPER_F), ("best_near", float(fr[i]))): segs = [] for sect, (tt, yy, ll) in ((a, (ta, ya, la)), (b, (tb, yb, lb))): for k in np.unique(ll): m = ll == k tq, yq, _ = bin30(tt[m], yy[m]) r = fit_fixed(tq, yq, fq, t0) r.update({"sector": sect, "orbit": int(k), "mid_t": round(float(tq.mean()), 2)}) segs.append(r) pair_out["%d+%d" % (a, b)]["segments_" + label] = segs summary["pairs"] = pair_out # amplitude map at the paper's frequency in each post-outburst sector maps = {} for s in (62, 63, 89, 90, 36, 37, 9, 10): hdus, tab, _ = 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 = t[good] cube = cube[good] sky = np.nanmedian(cube, axis=(1, 2)) ok = sky <= np.nanpercentile(sky, 95) t = t[ok] cube = cube[ok] - sky[ok, None, None] lab = orbits(t) # bin to 30 min first for speed idx = np.floor((t - t[0]) * 48).astype(int) u, inv = np.unique(idx, return_inverse=True) tb = np.bincount(inv, weights=t) / np.bincount(inv) labb = orbits(tb) ampmap = np.zeros((ny, nx)) Xmap = np.zeros((ny, nx)) Ymap = np.zeros((ny, nx)) fq = PAPER_F t0 = tb.mean() arg = 2 * np.pi * fq * (tb - t0) X = np.column_stack([np.cos(arg), np.sin(arg)]) XtXi = np.linalg.inv(X.T @ X) 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) / np.bincount(inv) vb = detrend_rm(tb, vb, labb) coef = XtXi @ (X.T @ vb) Xmap[j, i], Ymap[j, i] = coef ampmap[j, i] = math.hypot(*coef) cx, cy = pixel_of(ap_hdr, TARGET_RA, TARGET_DEC) j, i = np.unravel_index(np.argmax(ampmap), ampmap.shape) # centroid of the squared amplitude above the median, in a 7 x 7 box around the peak yy, xx = np.mgrid[0:ny, 0:nx] base = np.median(ampmap) wt = np.clip(ampmap - base, 0, None) ** 2 cen = (float(np.sum(wt * xx) / np.sum(wt)), float(np.sum(wt * yy) / np.sum(wt))) maps[str(s)] = { "target_xy": [round(float(cx), 2), round(float(cy), 2)], "peak_pixel_xy": [int(i), int(j)], "peak_offset_px": round(float(math.hypot(i - cx, j - cy)), 2), "peak_amp_e_per_s": float(ampmap[j, i]), "median_amp": float(base), "centroid_xy": [round(cen[0], 2), round(cen[1], 2)], "centroid_offset_px": round(float(math.hypot(cen[0] - cx, cen[1] - cy)), 2), "map_rows_amp": [[round(float(v), 2) for v in row] for row in ampmap], } summary["amplitude_maps"] = maps with open(os.path.join(outdir, "tess_summary.json"), "w", encoding="utf-8", newline="\n") as fh: json.dump(summary, fh, indent=1) print("wrote", os.path.join(outdir, "tess_summary.json")) if __name__ == "__main__": main()