diff --git "a/orbitlight.py" "b/orbitlight.py" --- "a/orbitlight.py" +++ "b/orbitlight.py" @@ -307,6 +307,32 @@ def archive_simbad_companions(names): return {n: sorted(by.get(oids.get(n), [])) for n in names} +archive_SIMBAD_BINARIES = ("EB*", "EB?", "SB*", "SB?", "El*", "El?", "RS*", "RS?") + + +def archive_simbad_binaries(): + """SIMBAD's eclipsing, spectroscopic, ellipsoidal and RS CVn binaries and their candidates (archive_SIMBAD_BINARIES): right ascension, + declination (deg) and the type's place in that list, sorted by declination, kept in DATA/simbad_index/binaries.npy once built.""" + if "binaries" not in archive_SIMBAD_CACHE: + path = archive_data("simbad_index", "binaries.npy") + if not os.path.exists(path): + import pyarrow as pa + import pyarrow.compute as pc + t = archive_simbad_table("basic", ("ra", "dec", "otype")) + t = t.filter(pc.is_in(t["otype"], value_set=pa.array(archive_SIMBAD_BINARIES))) + kind = np.array([archive_SIMBAD_BINARIES.index(k) for k in t["otype"].to_pylist()], float) + x = np.column_stack([t["ra"].to_numpy(zero_copy_only=False).astype(float), t["dec"].to_numpy(zero_copy_only=False).astype(float), kind]) + x = x[np.isfinite(x).all(axis=1)] + archive_SIMBAD_CACHE.pop(("basic", ("ra", "dec", "otype")), None) + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = archive_tmp(path) + with open(tmp, "wb") as fh: + np.save(fh, x[np.argsort(x[:, 1])]) + archive_place(tmp, path) + archive_SIMBAD_CACHE["binaries"] = np.load(path) + return archive_SIMBAD_CACHE["binaries"] + + def archive_simbad_basic(names, columns=("main_id", "otype")): """COLUMNS of SIMBAD's basic table for each identifier of NAMES: a dict of name to a dict of column to value.""" import pyarrow as pa @@ -458,9 +484,11 @@ def archive_exoplanets(query): def archive_eso_listing(ra, dec, inst, min_snr=10.0, radius_deg=0.01): """The public ESO Phase 3 spectra of a position from one instrument above MIN_SNR, in time order: dp_id, t_min and snr each.""" - q = ("SELECT dp_id, instrument_name, t_min, snr FROM ivoa.ObsCore WHERE dataproduct_type = 'spectrum' AND " + q = ("SELECT dp_id, instrument_name, t_min, snr, obs_release_date FROM ivoa.ObsCore WHERE dataproduct_type = 'spectrum' AND " "CONTAINS(POINT('ICRS', s_ra, s_dec), CIRCLE('ICRS', %.5f, %.5f, %g)) = 1" % (ra, dec, radius_deg)) - return sorted((r for r in archive_tap("eso", q) if r["instrument_name"] == inst and (archive_num(r["snr"]) or 0) > min_snr), key=lambda r: float(r["t_min"])) + today = time.strftime("%Y-%m-%d") + return sorted((r for r in archive_tap("eso", q) if r["instrument_name"] == inst and (archive_num(r["snr"]) or 0) > min_snr and (r.get("obs_release_date") or "")[:10] <= today), + key=lambda r: float(r["t_min"])) archive_ESO_INDEX = {} @@ -496,10 +524,10 @@ def archive_eso_fetch(rows, folder, streams=4, most=None, best=False): def archive_gaia_star(ra, dec, vmag=None, radius_arcsec=30.0, physical=True): - """A star's Gaia DR3 source, the brightest within RADIUS_ARCSEC of a J2000 position and 2.5 mag of VMAG, with its astrometry, RUWE and velocity - summary, and with PHYSICAL its FLAME mass and radius; or None.""" - q = ("SELECT source_id, ra, dec, parallax, pmra, pmdec, ruwe, phot_g_mean_mag, non_single_star, ipd_frac_multi_peak, radial_velocity, " - "radial_velocity_error, rv_amplitude_robust, rv_chisq_pvalue FROM gaiadr3.gaia_source WHERE CONTAINS(POINT('ICRS', ra, dec), " + """A star's Gaia DR3 source, the brightest within RADIUS_ARCSEC of a J2000 position and 2.5 mag of VMAG, with its astrometry, RUWE, excess noise + and velocity summary, and with PHYSICAL its FLAME mass and radius; or None.""" + q = ("SELECT source_id, ra, dec, parallax, pmra, pmdec, ruwe, astrometric_excess_noise, astrometric_excess_noise_sig, phot_g_mean_mag, " + "non_single_star, ipd_frac_multi_peak, radial_velocity, radial_velocity_error, rv_amplitude_robust, rv_chisq_pvalue FROM gaiadr3.gaia_source WHERE CONTAINS(POINT('ICRS', ra, dec), " "CIRCLE('ICRS', %.6f, %.6f, %.6f)) = 1" % (ra, dec, radius_arcsec / 3600.0)) rows = [r for r in archive_tap("gaia", q) if vmag is None or not math.isfinite(vmag) or abs((archive_num(r["phot_g_mean_mag"]) or 99.0) - vmag) < 2.5] if not rows: @@ -533,13 +561,34 @@ archive_VIZIER = "phanerozoic/VizieR" archive_VIZIER_CACHE = {} -def archive_vizier(catalogue, table): - """A table of the VizieR mirror, cached.""" - if (catalogue, table) not in archive_VIZIER_CACHE: +def archive_vizier(catalogue, table, columns=None): + """A table of the VizieR mirror, its COLUMNS alone where given, cached.""" + key = (catalogue, table, tuple(columns) if columns else None) + if key not in archive_VIZIER_CACHE: import pyarrow.parquet as pq from huggingface_hub import hf_hub_download - archive_VIZIER_CACHE[(catalogue, table)] = pq.read_table(hf_hub_download(archive_VIZIER, "%s/%s.parquet" % (catalogue, table), repo_type="dataset")) - return archive_VIZIER_CACHE[(catalogue, table)] + archive_VIZIER_CACHE[key] = pq.read_table(hf_hub_download(archive_VIZIER, "%s/%s.parquet" % (catalogue, table), repo_type="dataset"), + columns=list(columns) if columns else None) + return archive_VIZIER_CACHE[key] + + +def archive_earth(mjd): + """The Earth's barycentric place (AU, equatorial axes of J2000) at the epochs MJD: the opposite of the Sun's geocentric place from its + low-precision ecliptic longitude and distance (the Astronomical Almanac's, good to about a hundredth of a degree).""" + n = np.asarray(mjd, float) - 51544.5 + g = np.radians(357.528 + 0.9856003 * n) + lam = np.radians(280.460 + 0.9856474 * n + 1.915 * np.sin(g) + 0.020 * np.sin(2.0 * g)) + r = 1.00014 - 0.01671 * np.cos(g) - 0.00014 * np.cos(2.0 * g) + eps = math.radians(23.439) + return np.stack([-r * np.cos(lam), -r * np.sin(lam) * math.cos(eps), -r * np.sin(lam) * math.sin(eps)], -1) + + +def archive_parallax_factors(ra, dec, mjd): + """The parallax factors of a star at RA, DEC (degrees, or of many as columns of one) at the epochs MJD: its displacement along right ascension (times + cos dec) and along declination for a parallax of one, seen from the Earth's barycentric place (archive_earth).""" + x, y, z = archive_earth(mjd).T + a, d = np.radians(ra), np.radians(dec) + return x * np.sin(a) - y * np.cos(a), (x * np.cos(a) + y * np.sin(a)) * np.sin(d) - z * np.cos(d) # Kervella et al.'s (2022) columns, from the authors' release in the mirror, under VizieR's names for them: the Hipparcos-Gaia long-term proper motion @@ -1394,7 +1443,7 @@ def gpu_ensemble(logp, p0, steps, thin=10, seed=11, graph=False): k = (j + torch.randint(1, nb, (na,), device=gpu_DEVICE)) % nb xb = x[b] gamma = torch.where(torch.rand(1, dtype=gpu_F64, device=gpu_DEVICE) < 0.1, one, g0) - prop = x[a] + gamma * (xb[j] - xb[k]) + 1e-5 * torch.randn((na, 1), dtype=gpu_F64, device=gpu_DEVICE) + prop = x[a] + gamma * (1.0 + 1e-5 * torch.randn((na, 1), dtype=gpu_F64, device=gpu_DEVICE)) * (xb[j] - xb[k]) lq = logp(prop) take = torch.log(torch.rand(na, dtype=gpu_F64, device=gpu_DEVICE)) < lq - lp[a] x[a] = torch.where(take[:, None], prop, x[a]) @@ -1939,7 +1988,7 @@ TESS light curves, and its orbit is sampled. merge the shares joined, each unflagged signal's period tested in the stars' S index transitsearch the census stars' TESS light curves searched blind for transits eccentric the census's residuals searched by a Keplerian periodogram, eccentric orbits included - calibrate the census run blind on the archive's planets and scored on them + calibrate the census run blind on the archive's planets and scored on them; with --wobble, the weighing's wobble rule set on Gaia DR3's published solutions benchmark the census run on stars whose answers are known: Proxima, alpha Cen A and B, and the Sun from the solar mode lbl a star's line-by-line velocities from its HARPS spectra followup every signal decided, known, new or rejected: the census's, the varying stars' companions and TESS's candidates; signals.csv and @@ -2045,6 +2094,11 @@ def planets_bank(): planets_KNOWN = "SELECT hostname, hd_name, hip_name, ra, dec, sy_pmra, sy_pmdec, pl_name, pl_orbper, pl_bmassj, pl_orbeccen, pl_rvamp FROM pscomppars" planets_SOLUTIONS = "SELECT pl_name, hostname, hd_name, hip_name, tic_id, ra, dec, sy_pmra, sy_pmdec, pl_orbper FROM ps" planets_CATALOGUED = [] +# the Extrasolar Planets Encyclopaedia's catalogue, each of its statuses asked for by its query, and the columns kept of it +planets_EU = "https://exoplanet.eu/catalog/csv/" +planets_EU_STATUSES = ("confirmed", "candidate", "controversial", "retracted", "unconfirmed") +planets_EU_KEYS = ("name", "planet_status", "orbital_period", "ra", "dec", "star_name", "star_alternate_names", "alternate_names", "discovered") +planets_ENCYCLOPAEDIA = [] def planets_archive(days=1.0): @@ -2067,28 +2121,24 @@ def planets_archive(days=1.0): return planets_read(planets_path("solutions.csv")) -def planets_catalogued(days=1.0): - """A finder match(ra, dec, tic, names, P, radius) of the archive's planets of a star in any published solution, by TIC, name or position, those - within 5 per cent of P where given.""" - if not planets_CATALOGUED: - rows = planets_archive(days) - col = lambda k: np.array([planets_num(r.get(k)) for r in rows]) - ra, dec, per = col("ra"), col("dec"), col("pl_orbper") - pmra, pmdec = np.nan_to_num(col("sy_pmra")), np.nan_to_num(col("sy_pmdec")) - by_tic, by_name = {}, {} - for i, r in enumerate(rows): - tic = re.sub(r"\D", "", r.get("tic_id") or "") - if tic: - by_tic.setdefault(int(tic), []).append(i) - for c in ("hostname", "hd_name", "hip_name"): - if (r.get(c) or "").strip(): - by_name.setdefault(archive_simbad_key(r[c]), []).append(i) - order = np.argsort(np.nan_to_num(dec, nan=99.0)) - planets_CATALOGUED.append((np.array([r["pl_name"] for r in rows]), ra, dec, pmra, pmdec, per, by_tic, by_name, order, np.nan_to_num(dec, nan=99.0)[order], - {r["pl_name"]: r["hostname"] for r in rows})) - names_, ra0, dec0, pmra, pmdec, per, by_tic, by_name, order, dsorted, hosts = planets_CATALOGUED[0] - - def match(ra, dec, tic=None, names=(), P=None, radius=60.0): +def planets_finder(rows): + """A finder match(ra, dec, tic, names, P, radius, tolerance) of the planets ROWS, each under the archive's column names with its star's other names in aliases where it has them, of + a star by TIC, name or position, those within TOLERANCE of P in period where given; match.host and match.period give each planet's star and period.""" + col = lambda k: np.array([planets_num(r.get(k)) for r in rows]) + ra0, dec0, per = col("ra"), col("dec"), col("pl_orbper") + pmra, pmdec = np.nan_to_num(col("sy_pmra")), np.nan_to_num(col("sy_pmdec")) + by_tic, by_name = {}, {} + for i, r in enumerate(rows): + tic = re.sub(r"\D", "", r.get("tic_id") or "") + if tic: + by_tic.setdefault(int(tic), []).append(i) + for n in [r.get(c) for c in ("hostname", "hd_name", "hip_name")] + list(r.get("aliases", ())): + if (n or "").strip(): + by_name.setdefault(archive_simbad_key(n), []).append(i) + order = np.argsort(np.nan_to_num(dec0, nan=99.0)) + names_, dsorted = np.array([r["pl_name"] for r in rows]), np.nan_to_num(dec0, nan=99.0)[order] + + def match(ra, dec, tic=None, names=(), P=None, radius=60.0, tolerance=0.05): idx = set(by_tic.get(int(tic), ())) if tic not in (None, "") else set() for n in names: if n: @@ -2100,11 +2150,87 @@ def planets_catalogued(days=1.0): sep = lambda a, d: np.hypot(((a - ra + 180.0) % 360.0 - 180.0) * cosd, d - dec) * 3600.0 near = np.minimum(sep(ra0[j], dec0[j]), sep(ra0[j] - 16.0 * pmra[j] / 3.6e6 / cosd, dec0[j] - 16.0 * pmdec[j] / 3.6e6)) < radius idx.update(j[near].tolist()) - return sorted({str(names_[i]) for i in idx if P is None or abs(P / per[i] - 1.0) < 0.05}) - match.host = hosts + return sorted({str(names_[i]) for i in idx if P is None or abs(P / per[i] - 1.0) < tolerance}) + match.host = {r["pl_name"]: r["hostname"] for r in rows} + match.period = {r["pl_name"]: planets_num(r.get("pl_orbper")) for r in rows} return match +def planets_catalogued(days=1.0): + """A finder (planets_finder) of the archive's planets of a star in any published solution.""" + if not planets_CATALOGUED: + planets_CATALOGUED.append(planets_finder(planets_archive(days))) + return planets_CATALOGUED[0] + + +def planets_encyclopaedia(days=1.0): + """A finder (planets_finder) of the planets of the Extrasolar Planets Encyclopaedia (exoplanet.eu), every status of its catalogue (planets_EU_STATUSES), kept as ROOT/exoplanet_eu.csv + in order of name and fetched again once DAYS old, the file's time moved first so that one process of those side by side asks, the old copy kept where the site does not answer whole; + match.status gives each planet's status and match.cite how a row names it.""" + if not planets_ENCYCLOPAEDIA: + path = planets_path("exoplanet_eu.csv") + held = os.path.exists(path) + if not held or time.time() - os.path.getmtime(path) >= days * 86400.0: + if held: + os.utime(path) + try: + rows = {} + for status in planets_EU_STATUSES: + raw = archive_get(planets_EU + "?" + urllib.parse.urlencode({"query_f": '"%s" in planet_status' % status}), timeout=300, retries=2) + got = list(csv.DictReader(io.StringIO(raw.decode("utf-8-sig", "replace")))) + # the query matches the status's words, so that "confirmed" also brings the unconfirmed + if any(status not in r["planet_status"].lower() for r in got) or status == "confirmed" and len(got) < 1000: + raise IOError("%s: %d rows, not all of that status" % (status, len(got))) + rows.update({(r["name"], r["planet_status"]): r for r in got}) + tmp = archive_tmp(path) + planets_write(tmp, [rows[k] for k in sorted(rows)], planets_EU_KEYS) + archive_place(tmp, path) + except Exception as exc: + if not held: + raise + print("exoplanet.eu did not answer whole (%s); exoplanet_eu.csv kept" % str(exc)[:120], flush=True) + kept = planets_read(path) + tic = lambda r: re.search(r"TIC[\s-]*(\d+)", "%s, %s" % (r.get("star_alternate_names"), r.get("alternate_names"))) + found = planets_finder([dict(pl_name=r["name"], hostname=r["star_name"], ra=r["ra"], dec=r["dec"], pl_orbper=r["orbital_period"], tic_id=tic(r).group(1) if tic(r) else "", + aliases=(r.get("star_alternate_names") or "").split(",")) for r in kept]) + found.status = {r["name"]: r["planet_status"].strip().lower() for r in kept} + found.cite = {r["name"]: "exoplanet.eu %s, %s%s" % (r["name"], r["planet_status"].strip().lower(), " (%s)" % r["discovered"] if r["discovered"] else "") for r in kept} + planets_ENCYCLOPAEDIA.append(found) + return planets_ENCYCLOPAEDIA[0] + + +def planets_place(r, stars, exo): + """Where a decided row R's star lies and what it is called, as a finder (planets_finder) takes them: a TESS candidate's from its row of ExoFOP's tables EXO, a census star's from STARS, + and a star the TESS stage searched from its record's details.""" + x = exo.get(r["label"]) if r["kind"] in ("validated", "toi") else None + if x: + return planets_radec(x) + (x.get("TIC ID"), ()) + s = stars.get(r["name"], {}) + if not s and r.get("ra") is not None: + return planets_num(r["ra"]), planets_num(r["dec"]), r.get("tic"), (r["name"],) + return planets_num(s.get("RAJ2000")), planets_num(s.get("DEJ2000")), None, (r["name"], s.get("SimbadName")) + + +def planets_encyclopaedia_decide(sig, stars): + """The rows of SIG the decisions make new or leave candidates set against the Encyclopaedia (planets_encyclopaedia) at their stars, within 5 per cent in period or 25 per cent for a + companion, whose long orbit the data bound less closely, each entry named in the row's catalogued. A body it lists as retracted alone is rejected. A TESS candidate is known where it + lists it as confirmed, an independent validation where validated, since the catalogue's candidates include the TOIs themselves. Any other body it lists is known.""" + found = planets_encyclopaedia() + exo = {x["label"]: x for source in ("toi", "ctoi") if os.path.exists(planets_path(source + ".csv")) for x in planets_candidates(source)} + for r in sig: + if r["status"] not in ("new", "candidate"): + continue + hits = found(*planets_place(r, stars, exo), planets_num(r.get("orbit_P") or r["P"]), tolerance=0.25 if r["kind"] == "companion" else 0.05) + if not hits: + continue + said = {found.status[n] for n in hits} + r["catalogued"] = "; ".join([x for x in (r.get("catalogued"),) if x] + [found.cite[n] for n in hits]) + if said == {"retracted"}: + r.update(status="rejected", reason="retracted") + elif r["kind"] not in ("validated", "toi") or "confirmed" in said: + r.update(status="known", reason="catalogued", contribution="independent validation" if r["kind"] == "validated" else "") + + def planets_radec(x): """A TESS candidate's J2000 position (deg) from its ExoFOP row, sexagesimal or decimal; NaN where unreadable.""" def angle(text, scale): @@ -3358,6 +3484,62 @@ def planets_calibrate(): print(" %d found signals match no catalogued planet or alias, %d of them without flags" % (len(extra), res["extra_unflagged"]), flush=True) +def planets_wobble_calibration(): + """The weighing's rule on the wobble (planets_weigh_holds) set on what Gaia DR3 publishes, to RESULTS/wobble_calibration.json: its two-body solutions that hold an + astrometric orbit and its accelerations, of stars brighter than G 13, read from ESA's archive in 48 parts of source_id with each star's excess noise. Each solution's + photocentre over Gaia's window, its Thiele-Innes elements' orbit or its acceleration's polynomial, leaves about a five-parameter solution of the star the wobble + planets_weigh reads, the root mean square along one axis; that wobble over the excess noise, or over 0.3 mas where that is not significant, gives by steps of wobble the + percentiles of each kind of solution, the 99th being the table the rule holds (planets_WOBBLE_P99), and the share of each kind the rule turns down.""" + top, parts = 6917528997577384320, 48 + tg, tref = np.linspace(56863.0, 57901.0, 40), 57388.5 + dt = (tg - tref) / 365.25 + + def read(select, table, where): + rows = [] + for k in range(parts): + lo, hi = top // parts * k, top // parts * (k + 1) if k < parts - 1 else top + 1 + rows += archive_tap("gaia", "SELECT %s, g.ra, g.dec, g.astrometric_excess_noise, g.astrometric_excess_noise_sig FROM gaiadr3.%s AS o JOIN gaiadr3.gaia_source AS g " + "ON o.source_id = g.source_id WHERE o.source_id >= %d AND o.source_id < %d AND g.phot_g_mean_mag < 13 AND %s" % (select, table, lo, hi, where)) + return {key: np.array([planets_num(r[key]) for r in rows]) for key in rows[0]} + + def wobble(x, da, dd): + # the root mean square along one axis of the offsets DA, DD (solutions, epochs; mas) about each star's position, proper motion and parallax fitted to them + out = [] + for i in range(0, len(da), 8192): + fa, fd = archive_parallax_factors(x["ra"][i:i + 8192, None], x["dec"][i:i + 8192, None], tg) + one, zero, t = np.ones(fa.shape), np.zeros(fa.shape), np.tile(dt, (len(fa), 1)) + A = gpu_dev(np.stack([np.concatenate(c, 1) for c in ((one, zero), (zero, one), (t, zero), (zero, t), (fa, fd))], 2)) + y = gpu_dev(np.concatenate([da[i:i + 8192], dd[i:i + 8192]], 1)) + c = gpu_solve_spd(A.transpose(1, 2) @ A, (A.transpose(1, 2) @ y[:, :, None])[:, :, 0]) + out.append(gpu_host(torch.sqrt(((y - (A @ c[:, :, None])[:, :, 0]) ** 2).mean(1)))) + return np.concatenate(out) + o = read("o.period, o.eccentricity, o.t_periastron, o.a_thiele_innes, o.b_thiele_innes, o.f_thiele_innes, o.g_thiele_innes", "nss_two_body_orbit", "o.a_thiele_innes IS NOT NULL") + e = np.nan_to_num(o["eccentricity"])[:, None] + E = gpu_host(gpu_anomaly(tg[None, :], o["period"][:, None], tref + np.nan_to_num(o["t_periastron"])[:, None], e)) + X, Y = np.cos(E) - e, np.sqrt(1.0 - e * e) * np.sin(E) + a = read("o.accel_ra, o.accel_dec, o.deriv_accel_ra, o.deriv_accel_dec", "nss_acceleration_astro", "o.accel_ra IS NOT NULL") + bend = lambda g, j: 0.5 * g[:, None] * dt ** 2 + np.nan_to_num(j)[:, None] * dt ** 3 / 6.0 + kinds = (("orbit", o, wobble(o, o["b_thiele_innes"][:, None] * X + o["g_thiele_innes"][:, None] * Y, o["a_thiele_innes"][:, None] * X + o["f_thiele_innes"][:, None] * Y)), + ("acceleration", a, wobble(a, bend(a["accel_ra"], a["deriv_accel_ra"]), bend(a["accel_dec"], a["deriv_accel_dec"])))) + edges = (0.3,) + planets_WOBBLE_STEPS + (float("inf"),) + out = {} + for kind, x, w in kinds: + keep = np.isfinite(w) & np.isfinite(x["astrometric_excess_noise"]) + w, ratio = w[keep], w[keep] / np.maximum(np.where(x["astrometric_excess_noise_sig"][keep] > 2.0, x["astrometric_excess_noise"][keep], 0.0), 0.3) + limit = np.array(planets_WOBBLE_P99[kind])[np.searchsorted(planets_WOBBLE_STEPS, w, side="right")] + steps = [] + for lo, hi in zip(edges, edges[1:]): + m = (w >= lo) & (w < hi) + q = np.percentile(ratio[m], [50, 84, 95, 99]) + steps.append(dict(wobble_from=lo, wobble_to=hi if math.isfinite(hi) else None, solutions=int(m.sum()), p50=round(float(q[0]), 2), p84=round(float(q[1]), 2), p95=round(float(q[2]), 2), + p99=round(float(q[3]), 2))) + out[kind] = dict(solutions=len(w), turned_down=round(float(np.mean(ratio > limit)), 4), steps=steps) + print("%s: %d solutions, the rule turns down %.2f per cent" % (kind, len(w), 100.0 * out[kind]["turned_down"]), flush=True) + for s in steps: + print(" wobble from %5.2f mas: %6d solutions, ratio at 50 per cent %.2f, 84 %.2f, 95 %.2f, 99 %.2f" % (s["wobble_from"], s["solutions"], s["p50"], s["p84"], s["p95"], s["p99"]), flush=True) + archive_save(os.path.join(planets_RESULTS, "wobble_calibration.json"), json.dumps(out, separators=(",", ":")).encode()) + + def planets_cal_age(path, mjd): """The days between a HARPS spectrum at MJD and the ThAr exposure its wavelengths come from, read from the DRS's CAL TH FILE keyword, or NaN.""" from astropy.io import fits @@ -3761,7 +3943,8 @@ def planets_rotation(bv, s): def planets_decide(res, P, system, tess, prot=None): """Whether a followed signal at P is a planet, and if not why: it must hold in two independent reductions with no indicator at P, raise the joint model's BIC by more than 10 when removed, have no preferred alias, show no TESS brightness variation at P, P/2 or 2P (the strongest period, or power - 0.1 or more), lie more than 10 per cent from the star's rotation period PROT and half of it, and leave its system stable on circular orbits.""" + 0.1 or more, in PDCSAP flux, QLP's detrended flux having had a star's slow variation taken out), lie more than 10 per cent from the star's rotation period PROT and half of it, and leave its + system stable on circular orbits.""" held, _, ind, _ = planets_verdict(res, P) if ind: return False, "activity indicator" @@ -3776,6 +3959,7 @@ def planets_decide(res, P, system, tess, prot=None): if a["observed_ratio"] < 1.0 and a["truth"].get("%.4f d" % P, {}).get("reaching_observed", 1.0) < 0.01: return False, "alias" c = (tess or {}).get("combined") + c = None if c and c.get("flux") == "detrended" else c if c and float(c["fap"]) < 0.01 and any(abs(c["peak_d"] / q - 1.0) < 0.05 for q in (P, P / 2.0, 2.0 * P)): return False, "starspots" for label, power in (c or {}).get("near", {}).items(): @@ -3952,7 +4136,7 @@ def planets_companion(name, perms=50, most=40, seed=17): planets_weigh(name, pmin=0.75 * P0, pmax=1.25 * P0) if span >= 2.0 * P0 else planets_weigh(name) w = json.load(open(os.path.join(planets_RESULTS, "weigh", archive_tag(name) + ".json"))) rec["weigh"] = {k: w[k] for k in ("P_d", "e", "K1_ms", "m2_mjup", "incl_deg", "a_au", "acceleration", "velocity_trend", "p_below_13mjup", - "p_below_80mjup", "period_allowed")} + "p_below_80mjup", "period_allowed", "wobble_mas", "excess_noise_mas", "excess_noise_sig") if k in w} except BaseException as exc: rec["weigh_error"] = str(exc)[:200] gs = archive_gaia_star(float(star["RAJ2000"]), float(star["DEJ2000"]), archive_num(star.get("Vmag")), physical=False) @@ -3996,8 +4180,41 @@ def planets_companion(name, perms=50, most=40, seed=17): print(json.dumps(rec), flush=True) +# The 99th percentile of the wobble over Gaia's excess noise, or over 0.3 mas where that is not significant, among the orbits and the accelerations Gaia DR3 publishes, in steps +# of wobble ending at planets_WOBBLE_STEPS (mas) and a last step above them (planets_wobble_calibration) +planets_WOBBLE_STEPS = (0.4, 0.5, 0.65, 0.8, 1.0, 1.25, 1.6, 2.0, 2.5) +planets_WOBBLE_P99 = dict(orbit=(1.30, 1.58, 1.87, 2.06, 2.12, 2.39, 2.44, 2.42, 2.49, 3.06), acceleration=(1.32, 1.65, 2.10, 2.56, 3.09, 3.63, 4.26, 5.07, 5.76, 8.83)) + + +def planets_weigh_noise(w): + """The wobble a weighing (planets_weigh) sets against Gaia's astrometric excess noise, the posterior's median in mas, and that noise, 0.3 mas where it is not significant.""" + eps, sig = w.get("excess_noise_mas"), w.get("excess_noise_sig") + return w["wobble_mas"][0], max(eps if eps is not None and sig is not None and sig > 2.0 else 0.0, 0.3) + + +def planets_weigh_holds(w): + """Whether a weighing's orbit (planets_weigh) stands against Gaia's astrometric excess noise: the wobble its photocentre leaves about Gaia's five-parameter solution within what + 99 per cent of Gaia DR3's published solutions of that wobble leave against their own noise (planets_WOBBLE_P99), its accelerations where the star has one and its orbits + otherwise. A weighing made before the wobble was read holds.""" + if not w.get("wobble_mas"): + return True + wobble, noise = planets_weigh_noise(w) + return wobble <= planets_WOBBLE_P99["acceleration" if w.get("acceleration") else "orbit"][int(np.searchsorted(planets_WOBBLE_STEPS, wobble, side="right"))] * noise + + +def planets_weigh_agrees(w): + """Whether a weighing's orbit (planets_weigh) agrees with Gaia's astrometric excess noise closely enough for its mass to stand: its wobble at most 1.65 times that noise, twice + the quarter in log the weighing allows above it, which 95 per cent of Gaia DR3's published orbits near a milliarcsecond's wobble keep within. A weighing made before the wobble + was read agrees.""" + if not w.get("wobble_mas"): + return True + wobble, noise = planets_weigh_noise(w) + return wobble <= math.exp(0.5) * noise + + def planets_decide_companion(rec): - """A companion analysis's verdict and reason: 10+ nights, FAP < 1e-3, period fixed by a margin of 10 or by astrometry, second reduction at r >= 0.9.""" + """A companion analysis's verdict and reason: 10+ nights, FAP < 1e-3, period fixed by a margin of 10 or by astrometry whose orbit stands against Gaia's + excess noise (planets_weigh_holds), second reduction at r >= 0.9.""" if rec["nights"] < 10: return False, "few nights" if rec["cycles"] < 2.0: @@ -4007,6 +4224,8 @@ def planets_decide_companion(rec): return False, "under two cycles" if not ((rec.get("pma_snr") or 0.0) >= 5.0 or w.get("acceleration") or w.get("velocity_trend")): return False, "not significant" + if not planets_weigh_holds(w): + return False, "astrometry inconsistent" # the periods the profile allows (planets_weigh), or for a weighing without one the sampled 16th to 84th percentiles a, b = (w["period_allowed"][0][0], w["period_allowed"][-1][1]) if w.get("period_allowed") else (w["P_d"][1], w["P_d"][2]) lo, hi = max(0.5 * rec["span_d"], 50.0), 36525.0 @@ -4040,7 +4259,8 @@ def planets_companion_row(name, star, rec, cat): P, K, e = rec["P"], rec["K"], rec["e"] msini = planets_msini(P, K, e, m1) row.update(P=round(P, 4), K=round(K, 2), e=round(e, 3), msini_mjup=round(msini, 4), msini_mearth=round(msini * 317.83, 1)) - if w: + # the true mass where the weighing's orbit agrees with Gaia's excess noise; the minimum mass stands where it does not + if w and planets_weigh_agrees(w): row.update(mass_mjup=round(w["m2_mjup"][0], 3), mass_mjup_lo=round(w["m2_mjup"][1], 3), mass_mjup_hi=round(w["m2_mjup"][2], 3)) held, why = planets_decide_companion(rec) row.update(status=("known" if cat else "new") if held else "rejected", reason=("catalogued" if cat else "") if held else why, @@ -4206,11 +4426,18 @@ def planets_validation_decision(v, x, rv, events): sec, sig = v.get("depth_secondary_ppm"), v.get("secondary_sigma") most = planets_occultation_max(x, v.get("depth_ppm", 0.0), P) excess = (sec - most) / (sec / sig) if sec and sig and sig > 0 else 0.0 - own = "not vetted" if "odd_even_sigma" not in v else "odd-even depths" if (v["odd_even_sigma"] or 0.0) >= 3.0 else "secondary eclipse" if excess >= 3.0 else "" + checks = planets_check_cols(v, P, x) + # a transit its star leaves no room for, as 1 of 1,373 confirmed planets' and 83 of 1,111 false positives' on ExoFOP's stars and durations are + phys = planets_transit_physical(dict(P=P, depth_ppm=planets_num(x.get("Depth (ppm)")), duration_h=planets_num(x.get("Duration (hours)"))), x.get("Stellar Radius (R_Sun)"), x.get("Stellar Mass (M_Sun)")) + own = "not vetted" if "odd_even_sigma" not in v else "odd-even depths" if (v["odd_even_sigma"] or 0.0) >= 3.0 else "secondary eclipse" if excess >= 3.0 else \ + "variability" if planets_transit_smooth(v) else "a neighbour's variability" if v.get("variable_neighbours") else \ + "astrometric binary" if (checks.get("ruwe") or 0.0) >= planets_RUWE_MAX else "source off the star" if planets_centroid_off(v) else \ + "the star's rotation" if (checks.get("gaia_vbroad") or 0.0) >= planets_SPIN_FAST and planets_SPIN_LOW <= (checks.get("spin_ratio") or 0.0) <= planets_SPIN_HIGH else \ + "inside the star" if phys.startswith("orbit") else "duration" if phys else "" near = [e for e in events.get(str(v["tic"]), []) if abs(e["tce_period"] / P - 1.0) < 0.01] cols, why = planets_dv(max(near, key=lambda e: e["tce_num_transits"] if math.isfinite(e["tce_num_transits"]) else -1.0)) if near else ({}, "") cols.update(odd_even_sigma=v.get("odd_even_sigma", ""), secondary_sigma=v.get("secondary_sigma", ""), occultation_max_ppm=round(most, 1), - secondary_excess_sigma=round(excess, 2)) + secondary_excess_sigma=round(excess, 2), **checks) return ("rejected" if own or why else "new"), own or why, cols @@ -4218,7 +4445,9 @@ def planets_validated_rows(tois): """The TESS candidates validated statistically (RESULTS/validate/, planets_validate) as decided signals.csv rows. A candidate is new where its false-positive probability lies below 0.015 and its nearby-false-positive probability below 0.001 (Giacalone et al. 2021), each the mean of ten runs, ExoFOP's radius is below two Jupiter radii, the light curves it was weighed from show its odd and even transits' depths within 3 sigma of - each other and no dip of 3 sigma half an orbit on, and SPOC's data validation of its threshold-crossing event, its TIC star's event within 1 per + each other, no dip of 3 sigma half an orbit on, a transit's box rather than the star's own variation at the period (planets_transit_smooth), Gaia's RUWE + below planets_RUWE_MAX, a dip's source not placed off the star (planets_centroid_off), no star spinning at planets_SPIN_FAST or more with the period at its spin's limit (planets_check_cols), + an orbit and a transit's length its star allows (planets_transit_physical), and SPOC's data validation of its threshold-crossing event, its TIC star's event within 1 per cent of its period with the most transits, finds nothing against it where SPOC raised one (planets_dv), unless velocities weighed at its transits (TOIS, planets_toi_rows) put a star or brown dwarf there or a phase other than the transit's, and not decided again where those velocities already made it new; a pass from fewer runs waits for the rest, a pass weighed without those checks is not vetted, and the rest are rejected with why. A @@ -4315,16 +4544,16 @@ def planets_list(rows, stars): return None, None stellar[key] = [archive_num(row["Jmag"]), archive_num(row["Kmag"])] return tuple(stellar[key]) - match, discoverer = planets_catalogued(), planets_discoverers() + match, discoverer, eu = planets_catalogued(), planets_discoverers(), planets_encyclopaedia() + hosts = dict(eu.host, **match.host) def archived(r): - x = exo.get(r["label"]) if r["kind"] in ("validated", "toi") else None - if x: - return match(*planets_radec(x), x.get("TIC ID"), (), None, 10.0) - s = stars.get(r["name"], {}) - if not s and r.get("ra") is not None: - return match(planets_num(r["ra"]), planets_num(r["dec"]), r.get("tic"), (r["name"],), None, 10.0) - return match(planets_num(s.get("RAJ2000")), planets_num(s.get("DEJ2000")), None, (r["name"], s.get("SimbadName")), None, 10.0) + # the archive's planets of the star and those the Encyclopaedia holds of it beside them, for a TESS candidate its confirmed ones, its candidates including the TOIs themselves + where = planets_place(r, stars, exo) + listed = match(*where, None, 10.0) + said = ("confirmed",) if r["kind"] in ("validated", "toi") else ("confirmed", "candidate", "controversial", "unconfirmed") + same = lambda n, m: match.period[m] > 0 and abs(eu.period[n] / match.period[m] - 1.0) < 0.05 + return listed + [n for n in eu(*where, None, 10.0) if eu.status[n] in said and n not in listed and not any(same(n, m) for m in listed)] out = [] for r in sorted(new, key=lambda x: (x["name"], float(x["P"]))): host = host_of(r["name"]) @@ -4336,7 +4565,7 @@ def planets_list(rows, stars): [n.split()[-1] for n in listed if re.fullmatch(r"[a-z]", n.split()[-1])])) + 1) taken[r["name"]] = letter stem = r["label"].split(".")[0] if r["kind"] == "toi" else stems.get(r["name"], r["name"]) if r["kind"] == "validated" else host - stem = match.host[listed[0]] if listed else stem + stem = hosts[listed[0]] if listed else stem pick = lambda col, fallback: r.get(col) if r.get(col) not in (None, "") else fallback teff, rs, ms, rp = star_of(r) P = planets_num(pick("orbit_P", r["P"])) @@ -4344,7 +4573,7 @@ def planets_list(rows, stars): # the mass: weighed with the astrometry, or from the velocities, a transiting candidate's at the inclination of its transit and the others' least msini = archive_num(pick("orbit_msini_mearth", r["msini_mearth"])) mass, basis = (archive_num(r.get("mass_mjup")) * 317.83, "measured") if archive_num(r.get("mass_mjup")) else \ - (msini, "measured" if r["kind"] == "toi" else "minimum") if msini and r["kind"] != "validated" else (None, "") + (msini, "measured" if r["kind"] in ("toi", "transit") else "minimum") if msini and r["kind"] != "validated" else (None, "") character = planets_character(r["object"], P, teff, rs, ms, rp, mass, basis, *mags_of(r), teq) out.append(dict(planet="%s %s" % (stem, letter), host=host, kind=r["object"], found_by={"found": "census", "eccentric": "eccentric search", "companion": "companions", "toi": "TESS", "validated": "validation", @@ -4353,9 +4582,12 @@ def planets_list(rows, stars): P_d=pick("orbit_P", r["P"]), P_lo=r.get("orbit_P_lo", ""), P_hi=r.get("orbit_P_hi", ""), K_ms=pick("orbit_K", r["K"]), K_lo=r.get("orbit_K_lo", ""), K_hi=r.get("orbit_K_hi", ""), e=pick("orbit_e", r["e"]), e_lo=r.get("orbit_e_lo", ""), e_hi=r.get("orbit_e_hi", ""), msini_mearth=pick("orbit_msini_mearth", r["msini_mearth"]), - msini_mearth_lo=r.get("orbit_msini_mearth_lo", ""), msini_mearth_hi=r.get("orbit_msini_mearth_hi", ""), msini_mjup=r["msini_mjup"], + msini_mearth_lo=r.get("orbit_msini_mearth_lo", ""), msini_mearth_hi=r.get("orbit_msini_mearth_hi", ""), + msini_mjup=round(msini / 317.83, 4) if msini else r["msini_mjup"], mass_mjup=r.get("mass_mjup", ""), mass_mjup_lo=r.get("mass_mjup_lo", ""), mass_mjup_hi=r.get("mass_mjup_hi", ""), nights=r["nights"], - span_d=r["span_d"], prediction=r.get("prediction", ""), fpp=r.get("fpp", ""), nfpp=r.get("nfpp", ""), + span_d=r["span_d"], prediction=r.get("prediction", ""), second_instrument=r.get("second_instrument", ""), second_nights=r.get("second_nights", ""), + second_scale=r.get("second_scale", ""), second_scale_err=r.get("second_scale_err", ""), second_phase_sigma=r.get("second_phase_sigma", ""), second_test=r.get("second_test", ""), + fpp=r.get("fpp", ""), nfpp=r.get("nfpp", ""), sunlight=round(sunlight, 3) if sunlight else "", teq_k=round(teq) if teq else "", habitable_zone=zone or "", **character, bank_name=r["name"])) json.dump(stellar, open(kept, "w"), separators=(",", ":")) @@ -4483,7 +4715,8 @@ planets_DECISION_KEYS = ["status", "reason", "contribution", "discovered_by", "o "orbit_K", "orbit_K_lo", "orbit_K_hi", "mass_mjup", "mass_mjup_lo", "mass_mjup_hi", "fap_serval", "fap_drs", "fap_lbl", "fap_lbl_quiet", "dbic", "aliases_excluded", "tess_power", "tess_radius_limit_rearth", "rotation_d", "ruwe", "pma_snr", "catalogued", "fpp", "nfpp", "radius_rearth", "odd_even_sigma", "secondary_sigma", "occultation_max_ppm", "secondary_excess_sigma", "dv_odd_even", "dv_secondary_mes", "dv_centroid_sigma", "dv_core", "dv_halo", - "t0_btjd", "depth_ppm", "duration_h", "transit_snr", "transits", "single_event_share"] + "t0_btjd", "depth_ppm", "duration_h", "transit_snr", "transits", "single_event_share", "centroid_arcsec", "centroid_err", "centroid_sigma", "gaia_vbroad", "spin_ratio", + "second_instrument", "second_nights", "second_scale", "second_scale_err", "second_phase_sigma", "second_test"] def planets_followup(workers=6, report=False): @@ -4605,12 +4838,15 @@ def planets_followup(workers=6, report=False): cats = planets_catalogue(sorted(recs), stars, {n: period(rec) for n, rec in recs.items()}) rows += [planets_companion_row(n, stars[n], rec, cats[n]) for n, rec in sorted(recs.items())] tois = planets_toi_rows() - transit = planets_transit_rows(stars) - # a root of the TESS stage keeps the transit signals that pass the search's vetting alone, its rejections counted in its records + # a root of the TESS stage keeps the transit signals that pass the search's vetting alone, its rejections counted in its records, each star decided once if os.path.exists(planets_path("tess.json")): - transit = [r for r in transit if r["status"] != "rejected"] + transit = [r for r in planets_transit_kept(stars) if r["status"] != "rejected"] + else: + transit = planets_transit_rows(stars, full=True) rows += tois + planets_validated_rows(tois) + transit sig += rows + planets_encyclopaedia_decide(sig, stars) + planets_second_decide(sig) # Apply the verdicts of planets ledger: a new body whose predicted orbit failed against later observations is rejected. lpath, kinds = os.path.join(planets_RESULTS, "ledger.csv"), {"census": "found", "eccentric search": "eccentric", "companions": "companion", "TESS": "toi", "validation": "validated", "transit search": "transit"} @@ -4653,17 +4889,17 @@ def planets_orbits(name, periods, steps=30000, mstar=None, ebound=0.9, others=Tr a jitter, and every DACE instrument family outside HARPS with 5 nights or more (all but the bank's left out where OTHERS is false), each era with its offset and each family with its jitter. Nights more than six scaled median absolute deviations and five median errors from the circular fit are set aside, at most one in twenty, as the - census sets them aside. One Keplerian per starting period, each with its period (within 20 per cent of the start), time of periastron, sqrt(e) cos omega, sqrt(e) sin omega (e + census sets them aside. One Keplerian per starting period, each with its period (within 20 per cent of the start), time of inferior conjunction, which a nearly circular orbit fixes where it leaves periastron free, sqrt(e) cos omega, sqrt(e) sin omega (e below EBOUND) and semi-amplitude, started from a circular least-squares fit carried to the likelihood's maximum by Levenberg-Marquardt and sampled for STEPS steps by differential-evolution moves on the device (gpu_ensemble), the second half of the chain kept; with CIRCULAR every eccentricity is held at zero and the rest sampled about the circular fit. The medians and 16th to 84th percentiles of each period, K, e, minimum mass for a star of MSTAR solar - masses (the spectral type's by default) and time of inferior conjunction, the best fit's scatter, the chain's autocorrelation time (emcee's estimate), + masses (by default Gaia's FLAME mass as ROOT/stellar.json keeps it, else the spectral type's) and time of inferior conjunction, the best fit's scatter, the chain's autocorrelation time (emcee's estimate), and its log-likelihood beside that of the same orbits held circular; with CIRCULAR to .circular.json, with LABEL to .