Pre-DR4 Takip Hedefi Notu · Open Science · Fehmi Atican · v2, 20 Kasım 2026

Gaia DR3 6019286920341931520 (TIC 458320995): 47,56 günlük tek-çizgili spektroskopik ikili

ICRS (J2000): α = 250.740059° (16ʰ42ᵐ57.61ˢ), δ = −37.138758° (−37° 08′ 19.5″) · Galactic: (l, b) = (345.67°, +5.85°)

Not: bu bir ön-inceleme / aday hedef notudur, hakemli bir yayın değildir. "Keşif" ya da "doğrulanmış nötron yıldızı" iddiası içermez. Kaynak henüz El-Badry vd. (2026) ya da Simon vd. (2026)'nın büyük tayfsal takip programlarına girmemiş. Sonucu belirleyecek olan Gaia DR4 (2 Aralık 2026'da yayınlanması planlanıyor) ve yer tabanlı yüksek çözünürlüklü tayf gözlemleridir.

Gaia DR3'ün nss_two_body_orbit kataloğunda bu kaynak, 47,5625 ± 0,0193 günlük, hafif eksantrik (e = 0,049 ± 0,016) tek-çizgili spektroskopik ikili (SB1) olarak kayıtlı; K1 = 67,45 ± 1,26 km/s, anlamlılık = 53,46, F2 = 2,55 — El-Badry vd. (2026)'nın güvenilirlik eşiklerine göre bu, kataloğun daha güvenilir bölgesine düşüyor. Kütle fonksiyonu f(M) = 1,507 ± 0,085 M☉. Katalog yörüngesi geçerliyse, Gaia FLAME'ın birincil kütlesi M1 = 2,68 M☉ için M2,min = 4,11 M☉, ya da M1 = 1,55 M☉ için M2,min = 3,27 M☉ — nötron yıldızı sınırına (~3 M☉) yakın.

Ancak birkaç iç çelişki var: paralaks mesafesi (496,5 pc) ile spektrofotometrik mesafe (1658,8 pc) arasında 3,34 kat fark; Gaia'nın tayf şablonu 5500 K kullanırken GSP-Phot sıcaklığı 6980 K çıkıyor; ve 11 bantlı (optik + kızılötesi) tayf enerji dağılımı, tek yıldız modeli ile iki yıldız (sıcak eşlikçili) modeli istatistiksel olarak ayırt edemiyor. Astrometrik kalıntı da yüksek (RUWE = 9,00). Dört sektör TESS fotometrisinde (S12, S39, S66, S93) tutulma görülmüyor — ama notun kendi enjeksiyon-kurtarma testi, TESS'in uydu sistematiklerinin (±6000 ppm) zaten bu genlikteki bir sinyali maskeleyeceğini gösteriyor.

Not, dört yanlışlanabilir öngörüye bağlanıyor (aşağıda) ve tam doğrulama scriptini içeriyor; script ESA Gaia arşivinden ve NASA MAST'tan canlı veri çekip aynı tabloları, tayf enerji dağılımı testini ve iki şekli yeniden üretiyor. Tam İngilizce metin, tablolar, şekiller ve kod aşağıda.

Bu notu ilkokul sadeliğinde, Türkçe ve altı etkileşimli aletle anlatan sayfa: Görünmeyen eş: bir yıldızın hikâyesi.

Full note (English) · v2

Version 2 (November 20, 2026). Revised with Claude Opus 5.5 (Anthropic): all catalogued values and references were independently re-verified against the Gaia DR3 archive and arXiv; typography (solar symbols), the solution-quality attributions, the SED interpretation and the reference list were corrected. Scientific content and conclusions are otherwise unchanged from v1.
Citation: Atican, F. (2026). Gaia DR3 6019286920341931520 (TIC 458320995): A 47.56-Day Single-Lined Spectroscopic Binary with a High Catalogued Mass Function and Severe Astrometric Perturbation (Version v2). Zenodo. https://doi.org/10.5281/zenodo.24402951. The note (PDF) and verification script are archived there under CC BY 4.0.

Abstract

We present Gaia DR3 6019286920341931520 (TIC 458320995) as a not-yet-followed-up spectroscopic target ahead of Gaia Data Release 4 (scheduled for December 2, 2026). The system does not appear in either the spectroscopic follow-up program of El-Badry et al. (2026) or the radial-velocity survey of Gaia DR3 compact-object candidates by Simon et al. (2026). The Gaia DR3 nss_two_body_orbit catalogue lists a single-lined spectroscopic binary (SB1) orbit with P = 47.56250 ± 0.01928 d, K1 = 67.45 ± 1.26 km/s, and e = 0.049 ± 0.016 (NRV = 27, significance = 53.46, F2 = 2.55, efficiency = 0.156, flags = 0). Conditional on the validity of this orbit, the binary mass function is f(M) = 1.507 ± 0.085 M☉ (a1 sin i = 0.2945 AU), implying a minimum unseen companion mass of M2,min = 4.11 M☉ for the Gaia FLAME primary mass (M1 = 2.68 M☉) or 3.27 M☉ for M1 = 1.55 M☉.

We note a factor-of-3.34 discrepancy between the single-star parallax distance (dplx = 496.5 pc; RUWE = 9.00, εi = 1.306 mas) and the GSP-Phot distance (1658.8 pc), an RVS template-temperature mismatch (5500 K vs. 6980 K), and an 11-band SED for which single- and two-component blackbody models are statistically indistinguishable. Four sectors of TESS QLP photometry show no eclipses, while long-period ellipsoidal/Doppler modulations remain unconstrained by detrending and spacecraft systematics. We register explicit falsifiable criteria for independent multi-epoch spectroscopy and Gaia DR4.

1. Catalogued orbit, selection context and reliability

Gaia DR3 6019286920341931520 (TIC 458320995) is an apparently isolated (ipd_frac_multi_peak = 0%; nearest Gaia neighbour 5.38″ away at ΔG = +7.11 mag), reddened (AG = 1.61 mag) SB1 binary whose catalogued parameters are summarised in Table 1. The target is absent from both major Gaia DR3 compact-object follow-up programs: the spectroscopic follow-up sample of El-Badry et al. (2026) and the RV orbital survey of Simon et al. (2026). Its exclusion is consistent with their selection criteria: the catalogued mass function lies below the f(M) > 3 M☉ threshold of El-Badry et al. (2026), and their alternative minimum-companion-mass selection applies only to main-sequence primaries, whereas this primary appears evolved.

These follow-up studies provide essential context. El-Badry et al. (2026) found that roughly half of the high-mass-function Gaia DR3 SB1 candidates they examined have spurious orbital solutions, and that most of the remainder are post-mass-transfer binaries or hierarchical triples rather than dormant compact objects; they further caution that luminous companions are difficult to exclude for evolved primaries. At the same time, they report that a majority of solutions with significance > 20 are reliable, and that spurious orbits are concentrated at F2 > 6 for sources with G < 13. With significance = 53.46 and F2 = 2.55 at G = 11.69 (27 RVS transits, flags = 0), Gaia DR3 6019286920341931520 lies in the higher-reliability region of that parameter space, making it a well-motivated, though unconfirmed, candidate for independent spectroscopy.

Table 1. Catalogued and derived parameters (all values re-verified against the Gaia DR3 archive).
ParameterValueSource / note
Gaia DR3 ID / TIC ID6019286920341931520 / 458320995Multi-peak fraction 0%; nearest neighbour 5.38″, ΔG = +7.11 mag
Optical & IR photometryG = 11.687, GBP = 12.239, GRP = 10.942XP synthetic U = 13.12, B = 12.85, V = 12.06; 2MASS J = 9.81, H = 9.27, Ks = 9.04; AllWISE W1 = 8.90, W2 = 8.95
Astrometry & distancesϖ = 2.014 ± 0.168 mas (dplx = 496.5 pc)RUWE = 9.00; εi = 1.306 mas; dGSP-Phot = 1658.8 pc (1624–1680 pc)
GSP-Phot / FLAME / RVSTeff,GSP = 6980 K; log g = 2.78; Teff,RVS template = 5500 KAG = 1.61 mag; M1,FLAME = 2.68 M☉, LFLAME = 62.8 L☉, RFLAME = 2.24 R☉; RGSP = 9.47 R☉
SB1 orbitP = 47.56250 ± 0.01928 d; K1 = 67.45 ± 1.26 km/se = 0.049 ± 0.016; γ = −27.8 km/s; NRV = 27
Solution qualitysignificance = 53.46; F2 = 2.55Both in the higher-reliability regime of El-Badry et al. (2026) (significance > 20; F2 < 6 at G < 13); efficiency = 0.156; flags = 0
Dynamical mass budgetf(M) = 1.507 ± 0.085 M☉; a1 sin i = 0.2945 AUM2,min = 4.11 M☉ (M1 = 2.68 M☉) or 3.27 M☉ (M1 = 1.55 M☉)

2. Two self-consistent distance and luminosity regimes

Gaia DR3 reports two mutually inconsistent distances for this source: the single-star parallax yields dplx = 496.5 pc (subject to unmodeled orbital bias at RUWE = 9.00), whereas GSP-Phot yields 1658.8 pc. Such discrepancies are common for high-RUWE binaries and do not by themselves indicate new physics, but the pipeline radii and luminosities (RFLAME = 2.24 R☉, LFLAME = 62.8 L☉, RGSP = 9.47 R☉) cannot simultaneously describe a single 6980 K star. To avoid mixing incompatible assumptions, Table 2 evaluates both regimes self-consistently using V = 12.058 mag, AV = 1.97 mag, Teff = 6980 K, and the ellipsoidal scaling Aell ≈ αell(M2/M1)(R1/a)³sin²i with αell = 1.2 (Morris & Naftilan 1993) at i = 60°.

Table 2. The two Gaia DR3 distance regimes evaluated self-consistently.
Regimed (pc)MV,0L1 (L☉)R1 (R☉)Adopted M1M2,min (90°)Aell (60°)θ1 sin i (mas)
A (parallax)496.5+1.6117.92.891.55 M☉3.27 M☉≈61 ppm0.593
B (GSP-Phot)1658.8−1.01199.79.662.68 M☉4.11 M☉≈1192 ppm0.178

The astrophysical interpretation depends critically on which regime holds. In Regime A (MV,0 = +1.61), a luminous main-sequence companion matching the mass budget — a 4.3 M☉ B6V star (MV ≈ −0.55) or a 3.0 M☉ B8V star (MV ≈ −0.25; Pecaut & Mamajek 2013) — would substantially outshine the entire observed system, favouring a dark compact companion or faint inner binary. In Regime B (MV,0 = −1.01), the total luminosity readily accommodates a luminous B-type companion without invoking a compact object.

İki panelli şekil: eğime karşı eşlikçi kütlesi eğrileri ve beş senaryo için mutlak görsel kadir karşılaştırması.
Figure 1. (a) Unseen companion mass M2 versus inclination for f(M) = 1.507 M☉ across M1 = 1.55–2.68 M☉. If the 47.56-day orbit holds, the companion exceeds 3.27–4.11 M☉ at every inclination. (b) Dereddened absolute visual magnitude MV,0 in Regime A (496.5 pc) and Regime B (1658.8 pc) compared with Pecaut & Mamajek (2013) main-sequence values: at 496.5 pc a normal B-type companion is too bright to hide; at 1658.8 pc it fits inside the observed flux.

3. SED test, RVS template mismatch and astrometric excess

To test for a hidden hot companion — the main false-positive channel identified by El-Badry et al. (2026) — we compiled an 11-band optical-to-mid-infrared SED from Gaia XP (U, B, V), Gaia DR3 (GBP, G, GRP), 2MASS (J, H, Ks) and AllWISE (W1, W2), and compared reddened single- and two-blackbody models assuming 5% flux uncertainties. The single-component fit gives χ²/dof = 67.4/8 = 8.43 and the two-component fit χ²/dof = 50.2/6 = 8.36. Because both reduced χ² values are ≈ 8, the adopted uncertainties are underestimated by a factor of ≈ 2.9; after rescaling, the improvement (Δχ² = 17.2 for two additional parameters) corresponds to Δχ²scaled ≈ 2.0, which is not significant (p ≈ 0.35). Blackbodies also omit Balmer jumps and line blanketing. The SED therefore neither requires nor excludes a hot companion; full stellar-atmosphere modelling, ideally including ultraviolet photometry, is needed.

Two further catalogue anomalies reinforce the need for spectroscopic follow-up. First, the Gaia RVS pipeline derived radial velocities using a 5500 K template (log g = 2.5), 1480 K cooler than the GSP-Phot temperature (6980 K); such mismatches can bias RVs or inflate K1. Second, the astrometric excess noise (εi = 1.306 mas) exceeds the edge-on photocentre semimajor axis predicted for the 47.56-day orbit in both Regime A (θ1 sin i = 0.593 mas) and Regime B (0.178 mas). Because εi is not a direct orbital semimajor axis this comparison is only indicative; if astrophysical, the excess points either to a low-inclination, more massive companion or to an additional, wider component in a hierarchical triple.

4. TESS QLP assessment

We examined all four available TESS QLP sectors (12, 39, 66 and 93; epoch offset 2457389.0 − 2457000.0 = 389.0 d). The detrended light curves (KSPSAP_FLUX/DET_FLUX) show no eclipses, but detrending suppresses variability near the 27.4-day sector length (9 ppm at P/2 = 23.78 d). Raw SAP_FLUX and systematics-removed SYS_RM_FLUX (sectors 66 and 93; MAD = 3206–4287 ppm) are dominated by ±6000 ppm spacecraft drifts that produce spurious harmonic amplitudes (2193–3019 ppm at P/2; 466–1977 ppm at P), exceeding the expected Doppler-beaming scale 4K1/c ≈ 900 ppm. A 12-phase injection–recovery test (50–500 ppm at P/2) recovers ≈ 2200 ppm irrespective of the injected amplitude, confirming that QLP photometry cannot constrain 23.78-day ellipsoidal variations. Multi-year ground-based photometry such as ASAS-SN (Shappee et al. 2014; Kochanek et al. 2017) is better suited to test for 47.56-day or 23.78-day modulation.

Dört panelli şekil: ham ve detrend edilmiş TESS QLP akısının evre katlaması, 12 evreli enjeksiyon-kurtarma testi ve dört sektörün ham akı sistematikleri.
Figure 2. TESS QLP diagnostics for TIC 458320995 (sectors 12, 39, 66, 93). (a) Raw SAP_FLUX folded on P = 47.5625 d. (b) Detrended QLP flux showing no eclipses. (c) Ellipsoidal injection–recovery test on raw SAP_FLUX: the recovered amplitude (≈ 2200 ppm) is independent of the injected one. (d) Sector-by-sector raw SAP_FLUX showing ±6000 ppm spacecraft systematics. TESS excludes obvious eclipses but cannot constrain 50–500 ppm ellipsoidal signals.

5. Falsifiable predictions and code availability

Acknowledgments

This independent follow-up note is dedicated to my beloved wife, Ayşegül Işıldak Atican (informally, the Işıldak&Atican note, in her honour), for her constant patience and support. I warmly remember my late friend and former partner Orçun Güney, and thank Dr. Erkan Özkarakaş, Dr. Eyüp Numan Aytaş, Dr. Feyzi Emrah Başar and Prof. Dr. Mehmet Nuri İnel for their friendship and academic guidance, as well as my family — Berra Atican, Sami Atican and İlke Serra Atican — for their lifelong encouragement. Finally, I pay tribute to Mustafa Kemal Atatürk, whose enduring legacy of reason and science continues to illuminate independent inquiry (Yurtta Sulh, Cihanda Sulh).

AI and archive statement. Data retrieval, verification scripts and the v1 manuscript were developed in Google Colab with the assistance of Google Gemini. The v2 revision — independent re-verification of all catalogued values against the Gaia DR3 archive, verification of the cited literature, statistical review of the SED test, and manuscript editing — was carried out with Claude Opus 5.5 (Anthropic). All scientific interpretations and any remaining errors are my own. This work has made use of data from the European Space Agency (ESA) mission Gaia, processed by the Gaia Data Processing and Analysis Consortium (DPAC); of data products from the Two Micron All Sky Survey (2MASS) and the Wide-field Infrared Survey Explorer (WISE); and of TESS data (QLP high-level science products) obtained from the Mikulski Archive for Space Telescopes (MAST).

References

  1. Andrae, R., et al. (2023). Gaia DR3: Analysis of the Gaia BP/RP spectra using the General Stellar Parameterizer from Photometry (GSP-Phot). Astronomy & Astrophysics, 674, A27.
  2. Creevey, O. L., et al. (2023). Gaia DR3: Astrophysical parameters inference system (Apsis) I. Astronomy & Astrophysics, 674, A26.
  3. El-Badry, K., Latham, D. W., Rix, H.-W., et al. (2026). Spectroscopic follow-up of compact object binary candidates from Gaia DR3: white dwarfs, neutron stars, black holes, and the parallax zeropoint. arXiv:2608.06453.
  4. Gaia Collaboration, Arenou, F., Babusiaux, C., et al. (2023). Gaia Data Release 3: Stellar multiplicity, a teaser for the hidden treasure. Astronomy & Astrophysics, 674, A34.
  5. Gaia Collaboration, Vallenari, A., Brown, A. G. A., et al. (2023). Gaia Data Release 3: Summary of the content and survey properties. Astronomy & Astrophysics, 674, A1.
  6. Huang, C. X., Vanderburg, A., Pál, A., et al. (2020). Photometry of 10 Million Stars from the First Two Years of TESS Full Frame Images: Part I. Research Notes of the AAS, 4, 204.
  7. Katz, D., et al. (2023). Gaia DR3: Properties and validation of the radial velocities. Astronomy & Astrophysics, 674, A5.
  8. Kochanek, C. S., Shappee, B. J., Stanek, K. Z., et al. (2017). The All-Sky Automated Survey for Supernovae (ASAS-SN) light curve server v1.0. Publications of the Astronomical Society of the Pacific, 129, 104502.
  9. Morris, S. L., & Naftilan, S. A. (1993). The Equations of Ellipsoidal Star Variability Applied to HR 8427. The Astrophysical Journal, 419, 344.
  10. Pecaut, M. J., & Mamajek, E. E. (2013). Intrinsic Colors, Temperatures, and Bolometric Corrections of Pre-main-sequence Stars. The Astrophysical Journal Supplement Series, 208, 9.
  11. Shappee, B. J., Prieto, J. L., Grupe, D., et al. (2014). The Man Behind the Curtain: X-rays Drive the UV through NIR Variability in the 2013 AGN Outburst in NGC 2617. The Astrophysical Journal, 788, 48.
  12. Simon, J. D., Lam, C. Y., El-Badry, K., et al. (2026). Radial velocity orbital solutions for candidate black hole and neutron star binary systems in the Gaia Data Release 3 catalog. arXiv:2603.20371.

Run it yourself

The script below reproduces every number on this page — the catalogue query, the two-regime distance/luminosity budget, the 11-band SED test, and the TESS QLP diagnostics — directly from the ESA Gaia archive (TAP/ADQL) and NASA MAST (TESS QLP FITS files), plus both figures. No API key is needed. It was not run on Fehmi's own server: fehmiatican.com is a small serverless site, and a live ADQL query plus multi-megabyte FITS downloads and numerical fitting for every visitor would be slow and expensive. Instead, copy it into your own Google Colab notebook and run it there, on your own account:

  1. Open a new notebook at colab.research.google.com.
  2. In the first cell, run !pip install -q astropy scipy.
  3. Paste the full script below into a second cell and run it.
  4. It queries the live Gaia archive and downloads ~4 TESS FITS files (a minute or two), then prints Table 1–2 and the SED test, and saves Figure 1 and Figure 2 as PNGs.
takip-scripti.py · 413 satır
İndir (.py)
#!/usr/bin/env python3
"""
Independent Verification & Follow-Up Target Script
Target: Gaia DR3 6019286920341931520 (TIC 458320995)
Author: Fehmi Atican

Reproduces:
  1. Gaia DR3 astrometric, astrophysical, RVS template, and NSS SB1 parameters
  2. Two-regime distance/luminosity physics (Regime A: 496.5 pc vs Regime B: 1658.8 pc)
  3. 11-band optical-to-MIR SED comparison (1-star vs 2-star blackbody models)
  4. Direct download & harmonic analysis of 4 TESS QLP sectors (S12, S39, S66, S93)
  5. 12-phase ellipsoidal injection-recovery test on raw SAP_FLUX
  6. Publication-quality Figure 1 and Figure 2 (300 DPI PNG)

Google Colab prerequisite:
  !pip install -q astropy scipy
"""

import io
import warnings
import urllib.request
import urllib.parse
from concurrent.futures import ThreadPoolExecutor

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from astropy.io import fits

warnings.filterwarnings("ignore")
plt.rcdefaults()
plt.style.use("default")
plt.rcParams.update({
    "figure.facecolor": "white",
    "axes.facecolor": "white",
    "text.color": "black",
    "axes.labelcolor": "black",
    "xtick.color": "black",
    "ytick.color": "black",
    "axes.edgecolor": "black",
    "font.family": "serif",
    "font.size": 10,
    "axes.linewidth": 1.0,
    "xtick.direction": "in",
    "ytick.direction": "in",
    "savefig.dpi": 300,
})

TARGET_ID = 6019286920341931520
TIC_ID = "458320995"


def gaia_tap(adql):
    """Execute a synchronous ADQL query against ESA Gaia DR3 TAP."""
    url = "https://gea.esac.esa.int/tap-server/tap/sync?" + urllib.parse.urlencode({
        "REQUEST": "doQuery",
        "LANG": "ADQL",
        "FORMAT": "csv",
        "QUERY": " ".join(adql.split()),
    })
    df = pd.read_csv(io.BytesIO(urllib.request.urlopen(url, timeout=25).read()))
    return df.iloc[0] if len(df) > 0 else None


def solve_m2(f_m, m1, inc_deg=90.0):
    """Solve binary mass function for companion mass M2 at given inclination."""
    fm_eff = f_m / (np.sin(np.deg2rad(inc_deg)) ** 3)
    roots = np.roots([1.0, -fm_eff, -2.0 * fm_eff * m1, -fm_eff * (m1 ** 2)])
    return max([rt.real for rt in roots if abs(rt.imag) < 1e-7 and rt.real > 0])


def run_sed_test(g_row):
    """11-band SED test (Gaia XP U,B,V + Gaia BP,G,RP + 2MASS J,H,Ks + AllWISE W1,W2)."""
    try:
        tm = gaia_tap(f"""
            SELECT tm.j_m, tm.h_m, tm.ks_m
            FROM gaiadr3.tmass_psc_xsc_best_neighbour AS b
            JOIN gaiadr1.tmass_original_valid AS tm ON b.original_ext_source_id = tm.designation
            WHERE b.source_id = {TARGET_ID}
        """)
    except Exception:
        tm = None

    try:
        aw = gaia_tap(f"""
            SELECT aw.w1mpro, aw.w2mpro
            FROM gaiadr3.allwise_best_neighbour AS b
            JOIN gaiadr1.allwise_original_valid AS aw ON b.allwise_oid = aw.allwise_oid
            WHERE b.source_id = {TARGET_ID}
        """)
    except Exception:
        aw = None

    bands = [
        ("U",  0.365, g_row["u_jkc_mag"],        4.175e-9,  1.56),
        ("B",  0.445, g_row["b_jkc_mag"],        6.320e-9,  1.31),
        ("V",  0.551, g_row["v_jkc_mag"],        3.631e-9,  1.00),
        ("BP", 0.511, g_row["phot_bp_mean_mag"], 4.080e-9,  1.08),
        ("G",  0.622, g_row["phot_g_mean_mag"],  2.500e-9,  0.85),
        ("RP", 0.777, g_row["phot_rp_mean_mag"], 1.270e-9,  0.63),
        ("J",  1.235, tm["j_m"]    if tm is not None else np.nan, 3.129e-10, 0.28),
        ("H",  1.662, tm["h_m"]    if tm is not None else np.nan, 1.133e-10, 0.18),
        ("Ks", 2.159, tm["ks_m"]   if tm is not None else np.nan, 4.283e-11, 0.11),
        ("W1", 3.353, aw["w1mpro"] if aw is not None else np.nan, 8.178e-12, 0.06),
        ("W2", 4.603, aw["w2mpro"] if aw is not None else np.nan, 2.415e-12, 0.04),
    ]
    valid = [(n, lam, float(m), f0, al) for (n, lam, m, f0, al) in bands if pd.notna(m)]
    lam_m = np.array([x[1] for x in valid]) * 1e-6
    mags = np.array([x[2] for x in valid])
    f0s = np.array([x[3] for x in valid])
    al_av = np.array([x[4] for x in valid])
    f_obs = f0s * (10.0 ** (-0.4 * mags))
    sigma_f = 0.05 * f_obs

    def planck_lam(lam, T):
        h, c, k = 6.62607e-34, 2.99792e8, 1.38065e-23
        x = np.clip((h * c) / (lam * k * T), 1e-4, 500.0)
        return (1.0 / (lam ** 5)) / (np.exp(x) - 1.0)

    def loss_1star(p):
        T1, Av, ls1 = p
        if not (3500 <= T1 <= 20000 and 0.0 <= Av <= 4.0):
            return 1e12
        f_mod = (10 ** ls1) * planck_lam(lam_m, T1) * (10 ** (-0.4 * Av * al_av))
        return np.sum(((f_obs - f_mod) / sigma_f) ** 2)

    def loss_2star(p):
        T1, T2, Av, ls1, ls2 = p
        if not (3500 <= T1 <= 9000 and 8000 <= T2 <= 25000 and 0.0 <= Av <= 4.0):
            return 1e12
        f_mod = ((10 ** ls1) * planck_lam(lam_m, T1) + (10 ** ls2) * planck_lam(lam_m, T2)) * (10 ** (-0.4 * Av * al_av))
        return np.sum(((f_obs - f_mod) / sigma_f) ** 2)

    res1 = minimize(loss_1star, [6500.0, 1.8, -42.0], method="Nelder-Mead", options={"maxiter": 8000})
    res2 = minimize(loss_2star, [5800.0, 12500.0, 2.0, -42.0, -44.0], method="Nelder-Mead", options={"maxiter": 15000})

    print(f"\n=== 2. 11-Band SED Test ({len(valid)} bands) ===")
    print(f"  1-Star Blackbody : T1={res1.x[0]:.0f} K | A_V={res1.x[1]:.2f} mag | chi2/dof={res1.fun:.1f}/{len(valid)-3} ({res1.fun/(len(valid)-3):.2f})")
    print(f"  2-Star Blackbody : T1={res2.x[0]:.0f} K + T2={res2.x[1]:.0f} K | A_V={res2.x[2]:.2f} mag | chi2/dof={res2.fun:.1f}/{len(valid)-5} ({res2.fun/(len(valid)-5):.2f})")
    print(f"  Delta chi2 (1-star - 2-star) = {res1.fun - res2.fun:.1f}")


def download_tess_qlp(item):
    """Download a single TESS QLP FITS light curve directly from MAST."""
    sector, uri = item
    url = f"https://mast.stsci.edu/api/v0.1/Download/file?uri={uri}"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    raw = urllib.request.urlopen(req, timeout=25).read()
    with fits.open(io.BytesIO(raw), memmap=False) as h:
        d = h[1].data
        cols = {k.upper(): k for k in d.names}
        bjdref = float(h[1].header.get("BJDREFI", 2457000.0)) + float(h[1].header.get("BJDREFF", 0.0))
        t = np.asarray(d[cols["TIME"]], float)
        q = np.asarray(d[cols["QUALITY"]], np.int64) if "QUALITY" in cols else np.zeros(len(t), np.int64)
        sap = np.asarray(d[cols["SAP_FLUX"]], float)
        det_col = next(cols[k] for k in ["KSPSAP_FLUX", "DET_FLUX"] if k in cols)
        det = np.asarray(d[det_col], float)
        has_sys = "SYS_RM_FLUX" in cols
        sys_rm = np.asarray(d[cols["SYS_RM_FLUX"]], float) if has_sys else np.full_like(t, np.nan)

        m = (q == 0) & np.isfinite(t) & np.isfinite(sap) & (sap > 0) & np.isfinite(det) & (det > 0)
        if np.sum(m) < 40:
            m = np.isfinite(t) & np.isfinite(sap) & (sap > 0)

        sys_valid = has_sys and (np.sum(np.isfinite(sys_rm[m]) & (sys_rm[m] > 0)) > 40)
        sys_norm = (
            sys_rm[m] / np.nanmedian(sys_rm[m][sys_rm[m] > 0])
            if sys_valid else np.full(np.sum(m), np.nan)
        )
        return {
            "sector": sector,
            "bjdref": bjdref,
            "t": t[m],
            "sap": sap[m] / np.nanmedian(sap[m]),
            "det": det[m] / np.nanmedian(det[m]),
            "sys": sys_norm,
            "has_sys": sys_valid,
            "det_col": det_col,
        }


def bin_30min(t_s, y_s):
    """Bin light curve into 30-minute intervals."""
    idx = np.floor(t_s / (30.0 / 1440.0)).astype(np.int64)
    _, inv = np.unique(idx, return_inverse=True)
    counts = np.bincount(inv)
    return np.bincount(inv, weights=t_s) / counts, np.bincount(inv, weights=y_s) / counts


def fit_harmonics(t_arr, y_arr, p_orb, t0):
    """Simultaneous linear least-squares fit at P_orb (Doppler) and P_orb/2 (ellipsoidal)."""
    phi = 2.0 * np.pi * (t_arr - t0) / p_orb
    X = np.column_stack([np.ones_like(phi), np.cos(phi), np.sin(phi), np.cos(2 * phi), np.sin(2 * phi)])
    coef, _, _, _ = np.linalg.lstsq(X, y_arr, rcond=None)
    return np.hypot(coef[1], coef[2]) * 1e6, np.hypot(coef[3], coef[4]) * 1e6, coef


def main():
    print(f"=== 1. Querying Gaia DR3 {TARGET_ID} ===")
    r = gaia_tap(f"""
        SELECT g.ra, g.dec, g.phot_g_mean_mag, g.phot_bp_mean_mag, g.phot_rp_mean_mag,
               g.parallax, g.parallax_error, g.distance_gspphot, g.ag_gspphot,
               g.teff_gspphot, g.rv_template_teff, g.rv_template_logg,
               g.ruwe, g.astrometric_excess_noise,
               a.mass_flame, a.lum_flame, a.radius_flame, a.flags_flame,
               n.period, n.period_error, n.eccentricity, n.eccentricity_error,
               n.semi_amplitude_primary, n.semi_amplitude_primary_error, n.t_periastron,
               n.significance, n.goodness_of_fit, n.efficiency,
               sp.u_jkc_mag, sp.b_jkc_mag, sp.v_jkc_mag
        FROM gaiadr3.gaia_source AS g
        LEFT JOIN gaiadr3.astrophysical_parameters AS a ON g.source_id = a.source_id
        LEFT JOIN gaiadr3.nss_two_body_orbit AS n ON g.source_id = n.source_id
        LEFT JOIN gaiadr3.synthetic_photometry_gspc AS sp ON g.source_id = sp.source_id
        WHERE g.source_id = {TARGET_ID}
    """)

    P, dP = float(r["period"]), float(r["period_error"])
    K1, dK1 = float(r["semi_amplitude_primary"]), float(r["semi_amplitude_primary_error"])
    e, de = float(r["eccentricity"]), float(r["eccentricity_error"])
    Teff = float(r["teff_gspphot"])
    V_mag = float(r["v_jkc_mag"]) if pd.notna(r["v_jkc_mag"]) else 12.058
    A_V = 1.97
    d_plx = 1000.0 / float(r["parallax"])
    d_gsp = float(r["distance_gspphot"])

    f_M = 1.036118e-7 * P * (K1 ** 3) * ((1.0 - e ** 2) ** 1.5)
    df_M = f_M * np.sqrt((dP / P) ** 2 + (3 * dK1 / K1) ** 2 + (3 * e * de / (1 - e ** 2)) ** 2)
    a1_sini = (K1 * 1000.0 * P * 86400.0 * np.sqrt(1.0 - e ** 2)) / (2.0 * np.pi * 1.495978707e11)

    print(f"  f(M) = {f_M:.4f} +/- {df_M:.4f} M_sun | a1*sin(i) = {a1_sini:.4f} AU")
    print(f"  significance = {r['significance']:.2f} | GoF (F2) = {r['goodness_of_fit']:.2f} | RUWE = {r['ruwe']:.2f}")
    print(f"  rv_template_teff = {r['rv_template_teff']:.0f} K vs teff_gspphot = {Teff:.0f} K")

    for label, d_val, m1 in [("Regime A (Parallax)", d_plx, 1.55), ("Regime B (GSP-Phot)", d_gsp, 2.68)]:
        M_V0 = V_mag - 5.0 * np.log10(d_val / 10.0) - A_V
        L_c = 10.0 ** (-0.4 * (M_V0 - 4.74))
        R_c = np.sqrt(L_c) / ((Teff / 5772.0) ** 2)
        m2_90 = solve_m2(f_M, m1, 90.0)
        m2_60 = solve_m2(f_M, m1, 60.0)
        a_rs = (((m1 + m2_60) * ((P / 365.25) ** 2)) ** (1.0 / 3.0)) * 215.032
        A_ell = 1.2 * (m2_60 / m1) * ((R_c / a_rs) ** 3) * (np.sin(np.deg2rad(60.0)) ** 2) * 1e6
        theta_sini = a1_sini * (1000.0 / d_val)
        print(
            f"  {label:19s}: d={d_val:6.1f} pc | M_V0={M_V0:+5.2f} | L={L_c:5.1f} L_sun | "
            f"R1={R_c:4.2f} R_sun | M2(90)={m2_90:.2f} M_sun | A_ell(60)={A_ell:6.1f} ppm | theta1*sini={theta_sini:.3f} mas"
        )

    run_sed_test(r)

    print("\n=== 3. Downloading 4 TESS QLP Sectors (S12, S39, S66, S93) ===")
    sector_uris = [
        (12, "mast:HLSP/qlp/s0012/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0012-0000000458320995_tess_v01_llc.fits"),
        (39, "mast:HLSP/qlp/s0039/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0039-0000000458320995_tess_v01_llc.fits"),
        (66, "mast:HLSP/qlp/s0066/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0066-0000000458320995_tess_v01_llc.fits"),
        (93, "mast:HLSP/qlp/s0093/0000/0004/5832/0995/hlsp_qlp_tess_ffi_s0093-0000000458320995_tess_v01_llc.fits"),
    ]
    with ThreadPoolExecutor(max_workers=4) as ex:
        sectors = sorted(list(ex.map(download_tess_qlp, sector_uris)), key=lambda x: x["sector"])

    t_peri = float(r["t_periastron"]) + (2457389.0 - sectors[0]["bjdref"])
    tb_l, sap_l, det_l, sys_t_l, sys_y_l = [], [], [], [], []
    for s in sectors:
        tb_s, sb_s = bin_30min(s["t"], s["sap"])
        _, db_s = bin_30min(s["t"], s["det"])
        ok = np.abs(sb_s - 1.0) < 5.0 * 1.4826 * np.nanmedian(np.abs(sb_s - 1.0))
        tb_l.append(tb_s[ok])
        sap_l.append(sb_s[ok])
        det_l.append(db_s[ok])
        if s["has_sys"]:
            ts_s, ys_s = bin_30min(s["t"], s["sys"])
            ok_s = np.abs(ys_s - 1.0) < 5.0 * 1.4826 * np.nanmedian(np.abs(ys_s - 1.0))
            sys_t_l.append(ts_s[ok_s])
            sys_y_l.append(ys_s[ok_s])

    tb = np.concatenate(tb_l)
    sapb = np.concatenate(sap_l)
    detb = np.concatenate(det_l)

    dop_sap, ell_sap, c_sap = fit_harmonics(tb, sapb, P, t_peri)
    dop_det, ell_det, c_det = fit_harmonics(tb, detb, P, t_peri)
    print(f"  Raw SAP_FLUX : P={dop_sap:.1f} ppm | P/2={ell_sap:.1f} ppm")
    print(f"  Detrended QLP: P={dop_det:.1f} ppm | P/2={ell_det:.1f} ppm")
    if sys_t_l:
        dop_sys, ell_sys, _ = fit_harmonics(np.concatenate(sys_t_l), np.concatenate(sys_y_l), P, t_peri)
        print(f"  SYS_RM_FLUX  : P={dop_sys:.1f} ppm | P/2={ell_sys:.1f} ppm (S66+S93)")

    inj_amps = [50, 100, 200, 500]
    rec_med, rec_std = [], []
    for a_in in inj_amps:
        vals = []
        for ph0 in np.linspace(0, 2 * np.pi, 12, endpoint=False):
            y_all = np.concatenate([
                (sy + (a_in * 1e-6) * np.cos(4 * np.pi * (st - t_peri) / P + ph0))
                / np.nanmedian(sy + (a_in * 1e-6) * np.cos(4 * np.pi * (st - t_peri) / P + ph0))
                for st, sy in zip(tb_l, sap_l)
            ])
            vals.append(fit_harmonics(tb, y_all, P, t_peri)[1])
        rec_med.append(np.median(vals))
        rec_std.append(np.std(vals))

    # === 4. Generate Figure 1 ===
    fig1, axes = plt.subplots(2, 2, figsize=(12.2, 8.2), facecolor="white")
    faz = ((tb - t_peri) / P) % 1.0
    edges = np.linspace(0, 1, 25)
    cen = 0.5 * (edges[:-1] + edges[1:])
    ib = np.digitize(faz, edges) - 1
    fg = np.linspace(0, 1, 200)

    by_sap = [np.nanmedian(sapb[ib == k]) if np.sum(ib == k) >= 4 else np.nan for k in range(24)]
    m_sap = (
        c_sap[0] + c_sap[1] * np.cos(2 * np.pi * fg) + c_sap[2] * np.sin(2 * np.pi * fg)
        + c_sap[3] * np.cos(4 * np.pi * fg) + c_sap[4] * np.sin(4 * np.pi * fg)
    )
    axes[0, 0].scatter(faz, (sapb - 1) * 1e6, s=4, color="#94a3b8", alpha=0.25)
    axes[0, 0].plot(cen, (np.array(by_sap) - 1) * 1e6, "o-", ms=4, color="#0f766e", lw=1.4, label="Raw SAP_FLUX (24 phase bins)")
    axes[0, 0].plot(fg, (m_sap - 1) * 1e6, "--", color="#dc2626", lw=1.6, label=f"P={dop_sap:.0f} ppm | P/2={ell_sap:.0f} ppm")
    axes[0, 0].set_ylim(-5000, 5000)
    axes[0, 0].set_xlabel(r"Orbital Phase ($P = 47.5625$ d)")
    axes[0, 0].set_ylabel("Relative Flux (ppm)")
    axes[0, 0].set_title("(a) Raw SAP_FLUX Phase-Folded Light Curve", fontweight="bold", loc="left", fontsize=10)
    axes[0, 0].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[0, 0].grid(alpha=0.25)

    by_det = [np.nanmedian(detb[ib == k]) if np.sum(ib == k) >= 4 else np.nan for k in range(24)]
    m_det = (
        c_det[0] + c_det[1] * np.cos(2 * np.pi * fg) + c_det[2] * np.sin(2 * np.pi * fg)
        + c_det[3] * np.cos(4 * np.pi * fg) + c_det[4] * np.sin(4 * np.pi * fg)
    )
    axes[0, 1].scatter(faz, (detb - 1) * 1e6, s=4, color="#94a3b8", alpha=0.25)
    axes[0, 1].plot(cen, (np.array(by_det) - 1) * 1e6, "o-", ms=4, color="#1d4ed8", lw=1.4, label="Detrended QLP (24 phase bins)")
    axes[0, 1].plot(fg, (m_det - 1) * 1e6, "--", color="#f59e0b", lw=1.6, label=f"P={dop_det:.0f} ppm | P/2={ell_det:.0f} ppm")
    axes[0, 1].set_ylim(-3500, 3500)
    axes[0, 1].set_xlabel(r"Orbital Phase ($P = 47.5625$ d)")
    axes[0, 1].set_ylabel("Relative Flux (ppm)")
    axes[0, 1].set_title("(b) Detrended QLP Comparison (No Eclipses)", fontweight="bold", loc="left", fontsize=10)
    axes[0, 1].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[0, 1].grid(alpha=0.25)

    axes[1, 0].plot([0, 550], [0, 550], ":", color="gray", label="Ideal 100% Recovery")
    axes[1, 0].errorbar(inj_amps, rec_med, yerr=rec_std, fmt="o-", color="#0f766e", lw=2, capsize=4, label="Raw SAP_FLUX Recovery (12 phases)")
    axes[1, 0].set_xlabel("Injected P/2 = 23.78 d Amplitude (ppm)")
    axes[1, 0].set_ylabel("Recovered Amplitude (ppm)")
    axes[1, 0].set_title("(c) Ellipsoidal Signal Injection-Recovery Test", fontweight="bold", loc="left", fontsize=10)
    axes[1, 0].legend(fontsize=8, facecolor="white", edgecolor="#cbd5e1")
    axes[1, 0].grid(alpha=0.25)

    for i_s, (s_meta, st, sy) in enumerate(zip(sectors, tb_l, sap_l)):
        axes[1, 1].scatter(st - st[0] + i_s * 30, (sy - 1) * 1e6, s=5, alpha=0.6, label=f"S{s_meta['sector']}")
    axes[1, 1].set_ylim(-6000, 6000)
    axes[1, 1].set_xlabel("Relative Time (Sectors Offset by 30 d)")
    axes[1, 1].set_ylabel("Relative Flux (ppm)")
    axes[1, 1].set_title("(d) Sector-by-Sector Raw SAP_FLUX Systematics", fontweight="bold", loc="left", fontsize=10)
    axes[1, 1].legend(fontsize=8, ncol=4, facecolor="white", edgecolor="#cbd5e1")
    axes[1, 1].grid(alpha=0.25)

    plt.suptitle(f"TIC {TIC_ID} (Gaia DR3 {TARGET_ID}) — TESS QLP Photometric Systematics", fontsize=11.5, fontweight="bold", y=0.99)
    plt.tight_layout(rect=[0, 0, 1, 0.96])
    plt.savefig("Figure1_TESS_Systematics.png", dpi=300, bbox_inches="tight", facecolor="white")
    plt.show()

    # === 5. Generate Figure 2 ===
    inc_grid = np.linspace(25, 90, 200)
    fig2, (ax1, ax2) = plt.subplots(1, 2, figsize=(12.2, 4.6), facecolor="white")
    for m1_val, sty, col, lbl in [
        (2.68, "-", "#0f172a", r"$M_1 = 2.68\,M_\odot$ (FLAME; $M_{2,\min}=4.11\,M_\odot$)"),
        (2.00, "--", "#2563eb", r"$M_1 = 2.00\,M_\odot$ ($M_{2,\min}=3.63\,M_\odot$)"),
        (1.55, ":", "#059669", r"$M_1 = 1.55\,M_\odot$ (Regime A; $M_{2,\min}=3.27\,M_\odot$)"),
    ]:
        m2_arr = [solve_m2(f_M, m1_val, inc) for inc in inc_grid]
        ax1.plot(inc_grid, m2_arr, sty, color=col, lw=2.0, label=lbl)
    ax1.axhline(3.0, color="#dc2626", ls="-.", lw=1.2, label=r"Nominal NS Mass Limit ($\sim 3.0\,M_\odot$)")
    ax1.axhspan(3.0, 20.0, color="#fee2e2", alpha=0.35)
    ax1.set_xlim(25, 90)
    ax1.set_ylim(2.0, 18.0)
    ax1.set_xlabel(r"Orbital Inclination $i$ (deg)")
    ax1.set_ylabel(r"Companion Mass $M_2$ ($M_\odot$)")
    ax1.set_title(r"(a) Dynamical Mass Constraint ($f(M) = 1.507 \pm 0.085\,M_\odot$)", fontweight="bold", loc="left", fontsize=10)
    ax1.legend(fontsize=8, loc="upper right", frameon=True, facecolor="white", edgecolor="#cbd5e1")
    ax1.grid(alpha=0.25)

    labels = [
        "Regime A\n(496.5 pc)",
        "Regime B\n(1658.8 pc)",
        "Twin A3V\n" + r"($2\times 1.86\,M_\odot$)",
        "Single B8V\n" + r"($3.0\,M_\odot$)",
        "Single B6V\n" + r"($4.3\,M_\odot$)",
    ]
    mv_vals = [1.61, -1.01, 0.95, -0.25, -0.55]
    cols = ["#0f766e", "#1d4ed8", "#f59e0b", "#ef4444", "#991b1b"]
    bars = ax2.bar(labels, mv_vals, color=cols, alpha=0.88, edgecolor="black", lw=0.8)
    ax2.axhline(1.61, color="#0f766e", ls="--", lw=1.2, label=r"Regime A: $M_{V,0}=+1.61$ (d=496.5 pc)")
    ax2.axhline(-1.01, color="#1d4ed8", ls=":", lw=1.3, label=r"Regime B: $M_{V,0}=-1.01$ (d=1658.8 pc)")
    ax2.invert_yaxis()
    ax2.set_ylim(2.4, -1.7)
    ax2.set_ylabel(r"Absolute Visual Magnitude $M_{V,0}$ (Brighter $\uparrow$)")
    ax2.set_title(r"(b) Distance-Dependent Optical Luminosity Comparison ($A_V = 1.97$)", fontweight="bold", loc="left", fontsize=10)
    for b_i, val in zip(bars, mv_vals):
        ax2.text(b_i.get_x() + b_i.get_width() / 2, val - 0.12, f"{val:+.2f}", ha="center", va="bottom", fontsize=8.5, fontweight="bold")
    ax2.tick_params(axis="x", labelsize=8)
    ax2.legend(fontsize=7.8, loc="lower right", frameon=True, facecolor="white", edgecolor="#cbd5e1")
    ax2.grid(axis="y", alpha=0.25)

    plt.suptitle(f"Gaia DR3 {TARGET_ID} (TIC {TIC_ID}) — Dynamical Mass & Luminosity Regimes", fontsize=11.5, fontweight="bold", y=0.99)
    plt.tight_layout(rect=[0, 0, 1, 0.95])
    plt.savefig("Figure2_Dynamical_Constraints.png", dpi=300, bbox_inches="tight", facecolor="white")
    plt.show()
    print("\nDone! Saved Figure1_TESS_Systematics.png and Figure2_Dynamical_Constraints.png.")


if __name__ == "__main__":
    main()