"""orbitlight: planets, planetary atmospheres and stellar companions in the public archives of high-resolution spectra and radial velocities. python orbitlight.py planets bank|dace|rvcat|targets|measure|census|merge|followup|ledger|eccentric|calibrate|benchmark|lbl|vet|orbits|tess|tois|validate|system|weigh|controls|strict|sparse|recovery|window|figure|dip|companions-read|progress|epochs-trial ... python orbitlight.py solar plan|days|lbl|fit|reflected|orbit|molecules|eclipse ... python orbitlight.py giants plan|fetch|search|record|reflected|emission|opacities ... python orbitlight.py transits plan|fetch|run|record ... python orbitlight.py companions plan|test|search|survey|reanalyse|validate ... python orbitlight.py binaries series|orbit|rows|search|measure|depth|template|zero|shift ... python orbitlight.py eclipses fetch|fit|table ... python orbitlight.py publish OUT LABEL=DATA ... python orbitlight.py publish scan FOLDER [--git] python orbitlight.py publish check FOLDER PUBLIC python orbitlight.py pipeline run|start|watch|stop|pause|resume|decide|publish|chain|peers|status|end|deploy ... python orbitlight.py selftest Each mode's --help gives its method and options. Data live under ORBITLIGHT_DATA (default ./data) and results under ORBITLIGHT_RESULTS (default /results); the array work runs on ORBITLIGHT_DEVICE, by default the CUDA device where there is one and the CPU otherwise.""" import argparse import concurrent.futures as cf import csv import datetime import glob import gzip import http.client import inspect import io import json import logging import math import os import random import re import shutil import subprocess import sys import threading import time import types import urllib.error import urllib.parse import urllib.request import warnings import zlib import numpy as np import torch # The archives and the helpers every mode shares; data under ORBITLIGHT_DATA, results under ORBITLIGHT_RESULTS. archive_DATA = os.path.abspath(os.environ.get("ORBITLIGHT_DATA") or "data") archive_RESULTS = os.path.abspath(os.environ.get("ORBITLIGHT_RESULTS") or os.path.join(archive_DATA, "results")) def archive_data(*parts): """Path under the data root.""" return os.path.join(archive_DATA, *parts) def archive_results(*parts): """Path under the results root.""" return os.path.join(archive_RESULTS, *parts) def archive_record_run(run_id, title, archive, selection, approach, n_targets, n_unit, params, null_summary, sensitivity, result, rows): """A run's description and its per-target rows written as JSON under the results root, one file per run, replacing the last.""" os.makedirs(archive_RESULTS, exist_ok=True) path = os.path.join(archive_RESULTS, run_id + ".json") json.dump(dict(id=run_id, title=title, archive=archive, selection=selection, approach=approach, n_targets=n_targets, n_unit=n_unit, params=params, null=null_summary, sensitivity=sensitivity, result=result, finished=time.strftime("%Y-%m-%d"), rows=rows), open(path, "w"), separators=(",", ":")) return path def archive_quiet_warnings(): """Silence the expected astropy and numpy warnings (empty, all-NaN, invalid, overflow, divide); show all others.""" warnings.filterwarnings("ignore", category=RuntimeWarning, message=r"(Mean of empty slice|All-NaN (slice|axis) encountered|invalid value encountered" r"|divide by zero encountered|overflow encountered|Degrees of freedom <= 0)") try: from astropy.utils.exceptions import AstropyWarning except ImportError: return warnings.filterwarnings("ignore", category=AstropyWarning) def archive_num(x, missing=None): """Catalogue value as a finite float, else missing.""" try: v = float(x) except (TypeError, ValueError): return missing return v if math.isfinite(v) else missing archive_UA = {"User-Agent": "orbitlight Python-urllib/%d.%d" % sys.version_info[:2]} archive_TAP = { "eso": "https://archive.eso.org/tap_obs/sync", "exoplanets": "https://exoplanetarchive.ipac.caltech.edu/TAP/sync", "gaia": "https://gea.esac.esa.int/tap-server/tap/sync", "vizier": "https://tapvizier.cds.unistra.fr/TAPVizieR/tap/sync", } archive_MAXREC = 10000000 # the Gaia partner data centre that holds the releases under ESA's table and column names, writing its array columns in braces archive_GAIA_PARTNER = "https://gaia.ari.uni-heidelberg.de/tap/sync" def archive_get(url, headers=None, payload=None, timeout=120, retries=4, byte_range=None, soft=False, pause=5): """Bytes of a URL with retries and growing pauses, PAYLOAD posted where given; byte_range slices; soft returns None on 404 or exhausted retries and logs the latter.""" h = dict(archive_UA) if headers: h.update(headers) if byte_range: h["Range"] = "bytes=%d-%d" % byte_range last = None for attempt in range(retries): try: req = urllib.request.Request(url, headers=h, data=payload) return urllib.request.urlopen(req, timeout=timeout).read() except urllib.error.HTTPError as e: last = e if soft and e.code == 404: return None except Exception as e: last = e if attempt < retries - 1: time.sleep(pause * (attempt + 1)) if soft: sys.stderr.write("archive_get: %s failed %d times (%s); returned None\n" % (url, retries, repr(last)[:200])) return None raise last def archive_tap(service, query, fmt="csv", method=None, timeout=600, maxrec=None, retries=4): """ADQL on a named TAP service or sync URL, tried RETRIES times: rows as dicts (csv) or text; MAXREC set to avoid silent 50000-row cuts. Gaia's queries go to ESA's archive and its partner (archive_GAIA_PARTNER), DR3's to the partner first, the other asked where the first does not answer.""" if service == "gaia": sites = (archive_GAIA_PARTNER, archive_TAP["gaia"]) if "gaiadr3." in query else (archive_TAP["gaia"], archive_GAIA_PARTNER) try: return archive_tap(sites[0], query, fmt, "POST", timeout, maxrec, 2) except Exception: return archive_tap(sites[1], query, fmt, "POST", timeout, maxrec, retries) url = archive_TAP.get(service, service) if maxrec is None: maxrec = archive_MAXREC params = dict(REQUEST="doQuery", LANG="ADQL", FORMAT=fmt, QUERY=query) if maxrec: params["MAXREC"] = maxrec method = method or ("GET" if service in ("eso", "exoplanets") else "POST") enc = urllib.parse.urlencode(params) if method == "GET": raw = archive_get(url + "?" + enc, timeout=timeout, retries=retries) else: raw = archive_get(url, payload=enc.encode(), timeout=timeout, retries=retries) text = raw.decode("utf-8-sig", errors="replace") if fmt == "votable": if b"QUERY_STATUS\" value=\"ERROR" in raw: raise IOError("%s answered with an error: %s" % (service, text[:400])) elif fmt in ("csv", "json") and text.lstrip()[:1] == "<": raise IOError("%s answered with an HTML or XML page instead of %s: %s" % (service, fmt, text[:200])) if fmt == "csv": return list(csv.DictReader(io.StringIO(text))) if fmt == "json": return json.loads(text) if fmt == "votable": return archive_votable_rows(raw) return text def archive_votable_rows(raw): """Rows of a VOTable as dicts of Python values.""" from astropy.io.votable import parse_single_table t = parse_single_table(io.BytesIO(raw)).to_table() return [dict(zip(t.colnames, [x.item() if hasattr(x, "item") else x for x in row])) for row in t] def archive_pmap(fn, items, threads=8): """fn over items on a bounded thread pool, results in order.""" with cf.ThreadPoolExecutor(threads) as ex: return list(ex.map(fn, items)) # SIMBAD's tables as parquet on Hugging Face archive_SIMBAD = "phanerozoic/SIMBAD" archive_SIMBAD_CACHE = {} def archive_simbad_table(name, columns): """COLUMNS of a table of the SIMBAD mirror, cached.""" key = (name, tuple(columns)) if key not in archive_SIMBAD_CACHE: import pyarrow.parquet as pq from huggingface_hub import snapshot_download root = snapshot_download(archive_SIMBAD, repo_type="dataset", allow_patterns="data/%s/*" % name) archive_SIMBAD_CACHE[key] = pq.read_table(os.path.join(root, "data", name), columns=list(columns)) return archive_SIMBAD_CACHE[key] def archive_simbad_key(s): """An identifier without spaces, in capitals.""" return "".join(str(s).split()).upper() def archive_simbad_hash(s): """An identifier's key as a signed 64-bit FNV-1a hash, as the key_hash kernel computes it.""" h = 14695981039346656037 for c in archive_simbad_key(s).encode(): h = ((h ^ c) * 1099511628211) & 0xFFFFFFFFFFFFFFFF return h - (1 << 64) if h >= 1 << 63 else h def archive_simbad_hashes(column): """The key hash of every string of a pyarrow string column, on the device.""" import pyarrow as pa out = [] for chunk in column.chunks: if _gpu_kernels() is None: out.append(torch.as_tensor([archive_simbad_hash(s) for s in chunk.to_pylist()], dtype=torch.int64, device=gpu_DEVICE)) continue _, offsets, data = chunk.buffers() off = np.frombuffer(offsets, dtype=np.int64 if pa.types.is_large_string(chunk.type) else np.int32)[chunk.offset:chunk.offset + len(chunk) + 1] raw = np.frombuffer(data, dtype=np.uint8) if data is not None else np.zeros(1, np.uint8) out.append(_gpu_kernels().key_hash(torch.as_tensor(raw, device=gpu_DEVICE), torch.as_tensor(off.astype(np.int64), device=gpu_DEVICE), _gpu_stream())) return torch.cat(out) archive_SIMBAD_TYPES = ("Pl", "Pl?", "BD*", "BD?") def archive_simbad_build(folder): """The SIMBAD mirror's index written to FOLDER: every identifier's key hash with its oid, every object-paper and parent-child link, every object's position and velocity, and the planets and brown dwarfs with their names.""" import pyarrow.compute as pc import pyarrow.parquet as pq os.makedirs(folder, exist_ok=True) save = lambda name, x: np.save(os.path.join(folder, name + ".npy"), x) t = archive_simbad_table("ident", ("id", "oidref")) save("id_hash", gpu_host(archive_simbad_hashes(t["id"]))) save("id_oid", t["oidref"].to_numpy()) t = archive_simbad_table("has_ref", ("oidref", "oidbibref")) save("ref_oid", t["oidref"].to_numpy()), save("ref_bib", t["oidbibref"].to_numpy()) t = archive_simbad_table("h_link", ("parent", "child")) save("link_parent", t["parent"].to_numpy()), save("link_child", t["child"].to_numpy()) t = archive_simbad_table("basic", ("oid", "ra", "dec", "rvz_radvel", "main_id", "otype")) save("basic_oid", t["oid"].to_numpy()) for c, name in (("ra", "basic_ra"), ("dec", "basic_dec"), ("rvz_radvel", "basic_rv")): save(name, t[c].to_numpy(zero_copy_only=False).astype(float)) pq.write_table(t.select(["oid", "main_id", "otype"]).filter(pc.is_in(t["otype"], value_set=__import__("pyarrow").array(archive_SIMBAD_TYPES))), os.path.join(folder, "companions.parquet")) archive_SIMBAD_CACHE.clear() def archive_simbad_array(name): """One array of the SIMBAD mirror's index on the device, the index built into DATA/simbad_index on first use.""" if name not in archive_SIMBAD_CACHE: folder = archive_data("simbad_index") if not os.path.exists(os.path.join(folder, "companions.parquet")): archive_simbad_build(folder) archive_SIMBAD_CACHE[name] = torch.as_tensor(np.load(os.path.join(folder, name + ".npy")), device=gpu_DEVICE) return archive_SIMBAD_CACHE[name] def archive_simbad_oids(names): """SIMBAD's oid of each identifier of NAMES, matched by key hash on the device: a dict of name to oid, each way of writing one identifier among NAMES given it.""" keys = {} for n in names: keys.setdefault(archive_simbad_hash(n), []).append(n) h = archive_simbad_array("id_hash") hit = torch.isin(h, torch.as_tensor(list(keys), dtype=torch.int64, device=gpu_DEVICE)) return {n: int(o) for a, o in zip(gpu_host(h[hit]), gpu_host(archive_simbad_array("id_oid")[hit])) for n in keys[int(a)]} def archive_simbad_select(name, oids): """The positions of the index array NAME whose values are among OIDS.""" return torch.isin(archive_simbad_array(name), torch.as_tensor(sorted(set(oids)), dtype=torch.int64, device=gpu_DEVICE)) def archive_simbad_velocities(names): """SIMBAD's radial velocity (km/s) of each identifier of NAMES: a dict of name to velocity.""" oids = archive_simbad_oids(names) hit = archive_simbad_select("basic_oid", oids.values()) rv = {int(o): float(v) for o, v in zip(gpu_host(archive_simbad_array("basic_oid")[hit]), gpu_host(archive_simbad_array("basic_rv")[hit])) if math.isfinite(v)} return {n: rv[o] for n, o in oids.items() if o in rv} def archive_simbad_velocity_near(ra, dec, radius_arcsec=10.0): """SIMBAD's radial velocity (km/s) of the nearest object with one within RADIUS_ARCSEC of a J2000 position, or None.""" a, d, v = (archive_simbad_array(x) for x in ("basic_ra", "basic_dec", "basic_rv")) sep = torch.hypot((torch.remainder(a - ra + 180.0, 360.0) - 180.0) * math.cos(math.radians(dec)), d - dec) sep = torch.where(torch.isfinite(v), sep, torch.full_like(sep, float("inf"))) i = int(torch.argmin(sep)) return float(v[i]) if float(sep[i]) < radius_arcsec / 3600.0 else None def archive_simbad_near(ra, dec, radius_arcsec=10.0): """SIMBAD's main identifier of the object nearest a J2000 position within RADIUS_ARCSEC, or None.""" import pyarrow.compute as pc if not (math.isfinite(ra) and math.isfinite(dec)): return None a, d = archive_simbad_array("basic_ra"), archive_simbad_array("basic_dec") sep = torch.hypot((torch.remainder(a - ra + 180.0, 360.0) - 180.0) * math.cos(math.radians(dec)), d - dec) sep = torch.where(torch.isfinite(sep), sep, torch.full_like(sep, float("inf"))) i = int(torch.argmin(sep)) if float(sep[i]) >= radius_arcsec / 3600.0: return None t = archive_simbad_table("basic", ("oid", "main_id")) t = t.filter(pc.equal(t["oid"], int(archive_simbad_array("basic_oid")[i]))) return t["main_id"][0].as_py() if len(t) else None def archive_simbad_within(positions, radius_arcsec=10.0): """SIMBAD's objects within RADIUS_ARCSEC of each J2000 position (ra, dec) of POSITIONS, read from the mirror's index sorted by declination: for each its oids, nearest first.""" a, d, o = (gpu_host(archive_simbad_array(x)) for x in ("basic_ra", "basic_dec", "basic_oid")) keep = np.isfinite(a) & np.isfinite(d) a, d, o = a[keep], d[keep], o[keep] order = np.argsort(d) a, d, o = a[order], d[order], o[order] w, out = radius_arcsec / 3600.0, [] for ra, dec in positions: lo, hi = np.searchsorted(d, dec - w), np.searchsorted(d, dec + w) sep = np.hypot((np.remainder(a[lo:hi] - ra + 180.0, 360.0) - 180.0) * math.cos(math.radians(dec)), d[lo:hi] - dec) if math.isfinite(ra) and math.isfinite(dec) else np.zeros(0) k = np.argsort(sep) out.append([int(o[lo + j]) for j in k if sep[j] < w]) return out def archive_simbad_companions(names): """SIMBAD's planets and brown dwarfs linked to each identifier of NAMES as its children: a dict of name to (main_id, otype, oid).""" import pyarrow.parquet as pq oids = archive_simbad_oids(names) hit = archive_simbad_select("link_parent", oids.values()) if "companions" not in archive_SIMBAD_CACHE: t = pq.read_table(os.path.join(archive_data("simbad_index"), "companions.parquet")) archive_SIMBAD_CACHE["companions"] = {o: (m, k) for o, m, k in zip(t["oid"].to_pylist(), t["main_id"].to_pylist(), t["otype"].to_pylist())} kinds, by = archive_SIMBAD_CACHE["companions"], {} for p, c in zip(gpu_host(archive_simbad_array("link_parent")[hit]).tolist(), gpu_host(archive_simbad_array("link_child")[hit]).tolist()): if c in kinds: by.setdefault(p, []).append(kinds[c] + (c,)) 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 import pyarrow.compute as pc oids = archive_simbad_oids(names) t = archive_simbad_table("basic", ("oid",) + tuple(columns)) t = t.filter(pc.is_in(t["oid"], value_set=pa.array(sorted(set(oids.values())), type=t["oid"].type))) rows = {o: dict(zip(columns, vals)) for o, *vals in zip(t["oid"].to_pylist(), *(t[c].to_pylist() for c in columns))} return {n: rows[o] for n, o in oids.items() if o in rows} def archive_simbad_papers(names, words=("planet", "companion", "radial veloc"), most=None): """SIMBAD's papers on each identifier of NAMES whose titles contain any of WORDS, of at most MOST objects where given: name to (bibcode, year, title).""" import pyarrow as pa import pyarrow.compute as pc oids = archive_simbad_oids(names) hit = archive_simbad_select("ref_oid", oids.values()) pairs = list(zip(gpu_host(archive_simbad_array("ref_oid")[hit]).tolist(), gpu_host(archive_simbad_array("ref_bib")[hit]).tolist())) ref = archive_simbad_table("ref", ("oidbib", "bibcode", "year", "title", "nbobject")) ref = ref.filter(pc.is_in(ref["oidbib"], value_set=pa.array(sorted({b for _, b in pairs}), type=ref["oidbib"].type))) info = {b: (c, y, t or "", n) for b, c, y, t, n in zip(*(ref[x].to_pylist() for x in ("oidbib", "bibcode", "year", "title", "nbobject")))} by = {} for o, b in pairs: if b in info and any(w in info[b][2].lower() for w in words) and (most is None or (info[b][3] or 0) <= most): by.setdefault(o, []).append(info[b][:3]) return {n: sorted(by.get(oids.get(n), []), key=lambda r: -(r[1] or 0)) for n in names} def archive_spectra(ra, dec, radius_deg=0.01): """Every archived spectrum of a position: ESO Phase 3 products, CFHT SPIRou planes through the CADC and Keck NIRSPEC frames through KOA, each with its source, instrument, identifier, time span (MJD), exposure (s) and wavelength span (m).""" rows = [] q = ("SELECT dp_id, instrument_name, t_min, t_max, t_exptime, em_min, em_max, snr 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)) for r in archive_tap("eso", q): rows.append(dict(src="ESO", inst=r["instrument_name"], id=r["dp_id"], t0=float(r["t_min"]), t1=float(r["t_max"]), exp=archive_num(r["t_exptime"]), lo=archive_num(r["em_min"]), hi=archive_num(r["em_max"]), snr=archive_num(r["snr"]))) q = ("SELECT p.productID, p.time_bounds_lower, p.time_bounds_upper, p.time_exposure, p.energy_bounds_lower, p.energy_bounds_upper, p.dataRelease " "FROM caom2.Observation o JOIN caom2.Plane p ON o.obsID = p.obsID WHERE o.collection = 'CFHT' AND o.instrument_name = 'SPIRou' AND " "o.intent = 'science' AND INTERSECTS(CIRCLE('ICRS', %.5f, %.5f, %g), p.position_bounds) = 1" % (ra, dec, radius_deg)) # one plane per exposure, the telluric-corrected product (t), and public ones alone for r in archive_tap(archive_CADC_TAP, q, method="POST", maxrec=20000): t0, t1 = archive_num(r["time_bounds_lower"]), archive_num(r["time_bounds_upper"]) if t0 is not None and t1 is not None and r["productID"].endswith("t") and (r.get("dataRelease") or "")[:10] <= time.strftime("%Y-%m-%d"): rows.append(dict(src="CADC", inst="SPIRou", id=r["productID"], t0=t0, t1=t1, exp=archive_num(r["time_exposure"]), lo=archive_num(r["energy_bounds_lower"]), hi=archive_num(r["energy_bounds_upper"]), snr=None, release=r.get("dataRelease"))) return rows + archive_koa_spectra(ra, dec, radius_deg) def archive_koa_spectra(ra, dec, radius_deg=0.01): """Keck NIRSPEC spectrograph frames of a position through KOA, object frames of the spectrograph camera alone, each with its start (MJD), exposure (s) and wavelength span (m).""" q = ("SELECT koaid, mjd, elaptime, waveblue, wavered FROM koa_nirspec WHERE camera = 'spec' AND koaimtyp = 'object' AND " "CONTAINS(POINT('icrs', ra, dec), CIRCLE('icrs', %.5f, %.5f, %g)) = 1" % (ra, dec, radius_deg)) rows = [] for r in archive_tap(archive_KOA_TAP, q, method="POST", maxrec=20000): t0, exp = archive_num(r["mjd"]), archive_num(r["elaptime"]) or 0.0 if t0 is None: continue lo, hi = archive_num(r["waveblue"]), archive_num(r["wavered"]) rows.append(dict(src="KOA", inst="NIRSPEC", id=r["koaid"], t0=t0, t1=t0 + exp / 86400.0, exp=exp, lo=lo * 1e-6 if lo else None, hi=hi * 1e-6 if hi else None, snr=None)) return rows archive_CADC_TAP = "https://ws.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/argus/sync" archive_KOA_TAP = "https://koa.ipac.caltech.edu/TAP/sync" archive_CADC_FILE = "https://ws.cadc-ccda.hia-iha.nrc-cnrc.gc.ca/data/pub/CFHT/" def archive_path(folder, r): """Where an archived spectrum, a row of archive_spectra or of an ESO listing, is kept in FOLDER: its identifier made a file name.""" return os.path.join(folder, re.sub(r"[^A-Za-z0-9_.-]", "_", r.get("dp_id") or r["id"]) + ".fits") def archive_tmp(path): """A temporary file beside PATH of this process's and thread's own, so that processes writing the same file at once never meet.""" return "%s.%d.%d.tmp" % (path, os.getpid(), threading.get_ident()) def archive_place(tmp, path): """The written file TMP put in PATH's place; where another process has just put PATH there, its copy stands and TMP is removed.""" try: os.replace(tmp, path) except PermissionError: os.remove(tmp) if not os.path.exists(path): raise return path def archive_save(path, data): """DATA, bytes, written to PATH whole (archive_tmp, archive_place).""" tmp = archive_tmp(path) open(tmp, "wb").write(data) return archive_place(tmp, path) def archive_download(r, path): """One archived spectrum, a row of archive_spectra (src, id) or of an ESO listing (dp_id), fetched to PATH unless it is already there: the CADC's SPIRou products from its CFHT collection, the rest from ESO. PATH, or None where the archive refuses it, as for a proprietary or withdrawn product.""" if os.path.exists(path): return path os.makedirs(os.path.dirname(path) or ".", exist_ok=True) try: if r.get("src") in ("CADC", "SOPHIE", "HARPN"): b = archive_get(archive_CADC_FILE + r["id"] + ".fits" if r["src"] == "CADC" else planets_SOPHIE + planets_SOPHIE_FILE % r["id"] if r["src"] == "SOPHIE" else planets_TNG_FILES + r["id"] + "_S1D_A.fits.gz", timeout=600, soft=True) b = gzip.decompress(b) if b and b[:2] == b"\x1f\x8b" else b if b and b[:6] == b"SIMPLE": return archive_save(path, b) return None return path if archive_eso_download(r.get("dp_id") or r["id"], path) else None except Exception: return None archive_HARPS_MIRROR = "datasets/phanerozoic/HARPS/" archive_HF_FS = [] def archive_harps_path(dp_id): """A HARPS product's path in the mirror: HARPS//T/.fits, by the time ESO created the product, so that no folder nears the Hub's 10000 files.""" return "HARPS/%s/%s/%s.fits" % (dp_id[4:11], dp_id[12:17], re.sub(r"[^A-Za-z0-9_.-]", "_", dp_id)) def archive_eso_download(dp_id, path): """Download one public ESO product to PATH, from the HARPS mirror on Hugging Face where it holds the product, else from ESO; True when a FITS file arrived.""" try: from huggingface_hub import HfFileSystem archive_HF_FS or archive_HF_FS.append(HfFileSystem()) tmp = archive_tmp(path) archive_HF_FS[0].get_file(archive_HARPS_MIRROR + archive_harps_path(dp_id), tmp) if open(tmp, "rb").read(6) == b"SIMPLE": archive_place(tmp, path) return True except Exception: pass b = archive_get("https://dataportal.eso.org/dataportal_new/file/" + dp_id, timeout=300) if b[:6] != b"SIMPLE": return False archive_save(path, b) return True def archive_exoplanets(query): """Rows of ADQL on the NASA Exoplanet Archive.""" return archive_tap("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, 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)) 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 = {} def archive_eso_listings(positions, inst, min_snr=10.0, radius_deg=0.01): """archive_eso_listing for many (ra, dec) positions from a single query: the instrument's whole Phase 3 spectrum index is fetched once per run and matched locally. Returns one time-ordered listing per position.""" if inst not in archive_ESO_INDEX: rows = archive_tap("eso", "SELECT dp_id, s_ra, s_dec, t_min, snr FROM ivoa.ObsCore WHERE dataproduct_type = 'spectrum' AND instrument_name = '%s'" % inst, timeout=1800) col = lambda k: np.array([archive_num(r[k], np.nan) for r in rows]) dec = col("s_dec") o = np.argsort(np.nan_to_num(dec, nan=99.0)) archive_ESO_INDEX[inst] = dict(dp_id=np.array([r["dp_id"] for r in rows])[o], ra=col("s_ra")[o], dec=dec[o], t_min=col("t_min")[o], snr=col("snr")[o]) x = archive_ESO_INDEX[inst] out = [] for ra, dec in positions: lo, hi = np.searchsorted(x["dec"], dec - radius_deg), np.searchsorted(x["dec"], dec + radius_deg) dra = (np.remainder(x["ra"][lo:hi] - ra + 180.0, 360.0) - 180.0) * math.cos(math.radians(dec)) k = lo + np.where((np.hypot(dra, x["dec"][lo:hi] - dec) < radius_deg) & (np.nan_to_num(x["snr"][lo:hi]) > min_snr))[0] k = k[np.argsort(x["t_min"][k])] out.append([dict(dp_id=str(x["dp_id"][i]), instrument_name=inst, t_min=float(x["t_min"][i]), snr=float(x["snr"][i])) for i in k]) return out def archive_eso_fetch(rows, folder, streams=4, most=None, best=False): """The listed ESO products fetched into FOLDER, MOST of them spread evenly over the listing's span (or the MOST of highest signal to noise with BEST), those present kept: their paths.""" if most and len(rows) > most: rows = sorted(rows, key=lambda r: -(archive_num(r.get("snr")) or 0))[:most] if best else [rows[int(i)] for i in np.unique(np.linspace(0, len(rows) - 1, most).round())] os.makedirs(folder, exist_ok=True) return [p for p in archive_pmap(lambda r: archive_download(r, archive_path(folder, r)), rows, streams) if p] 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, 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: return None best = min(rows, key=lambda r: archive_num(r["phot_g_mean_mag"]) or 99.0) if physical: ap = archive_tap("gaia", "SELECT mass_flame, radius_flame, teff_gspphot FROM gaiadr3.astrophysical_parameters WHERE source_id = %s" % best["source_id"]) best.update(ap[0] if ap else dict(mass_flame="", radius_flame="", teff_gspphot="")) return best def archive_gaia_solutions(source_ids): """Gaia DR3's two-body orbits, acceleration solutions and velocity trends of SOURCE_IDS, by source.""" ids = sorted({str(s) for s in source_ids}) out = {s: dict(orbit=[], acceleration=[], trend=[]) for s in ids} for kind, table in (("orbit", "nss_two_body_orbit"), ("acceleration", "nss_acceleration_astro"), ("trend", "nss_non_linear_spectro")): for i in range(0, len(ids), 500): for r in archive_tap("gaia", "SELECT * FROM gaiadr3.%s WHERE source_id IN (%s)" % (table, ", ".join(ids[i:i + 500]))): out[str(r["source_id"])][kind].append(r) return out def archive_hipparcos_of(source_id): """The Hipparcos number of a Gaia DR3 source from DR3's best neighbours, or None.""" rows = archive_tap("gaia", "SELECT original_ext_source_id FROM gaiadr3.hipparcos2_best_neighbour WHERE source_id = %s" % source_id) return int(rows[0]["original_ext_source_id"]) if rows else None # VizieR's catalogues as parquet on Hugging Face, each table at /.parquet archive_VIZIER = "phanerozoic/VizieR" 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[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_vizier_text(query, timeout=120, retries=2, rows=False): """The reply to the asu-tsv QUERY from the first of VizieR's sites (planets_VIZIER_SITES) to answer that holds its catalogue, as text, with ROWS one that has rows, or None: a site without the catalogue says so in a reply that otherwise reads as a table with no rows.""" for site in planets_VIZIER_SITES: raw = archive_get("%s/viz-bin/asu-tsv?%s" % (site, query), timeout=timeout, retries=retries, soft=True) if raw and b"VizieR" in raw[:4000] and b"#INFO\tError=" not in raw: text = raw.decode("utf-8", "replace") if not rows or sum(1 for x in text.splitlines() if x and not x.startswith("#")) > 3: return text return None def archive_vizier_table(source, timeout=60): """A whole table of VizieR, SOURCE its catalogue and table (archive_vizier_text): its rows as dicts of text; an error where no site gives them.""" q = urllib.parse.urlencode({"-source": source, "-out.max": "unlimited", "-out.all": ""}) for attempt in range(6): text = archive_vizier_text(q, timeout, 3, rows=True) if text: lines = [x for x in text.splitlines() if x and not x.startswith("#")] keys = [k.strip() for k in lines[0].split("\t")] return [dict(zip(keys, [c.strip() for c in x.split("\t")])) for x in lines[3:]] # the sites answer empty for a while after several whole tables in a row time.sleep(120) raise IOError("no VizieR site answered with %s" % source) def archive_vizier_file(path, timeout=120): """A file of the CDS archive's catalogues, PATH under its cats folder, from the first of VizieR's sites to serve it, as text, or None.""" for site in planets_VIZIER_SITES: raw = archive_get("%s/ftp/cats/%s" % (site, path), timeout=timeout, retries=2, soft=True) if raw and not raw.lstrip().startswith(b"<"): return raw.decode("latin-1") return None 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 # and the proper-motion anomaly at Gaia's epoch, 2016.0 archive_KERVELLA = {"HIP": "HIP", "PlxG3": "PlxG3", "RUWE": "RUWE", "M1": "M1", "R1": "R1", "dVt": "dVt", "e_dVt": "e_dVt", "pmRAH2EG3b": "muHGGRA", "e_pmRAH2EG3b": "e_muHGGRA", "pmDEH2EG3b": "muHGGDec", "e_pmDEH2EG3b": "e_muHGGDec", "PMaRAH2EG3b": "PMaGRA", "e_PMaRAH2EG3b": "e_PMaGRA", "PMaDEH2EG3b": "PMaGDec", "e_PMaDEH2EG3b": "e_PMaGDec", "snrPMaH2EG3b": "PMaG3snr"} def archive_kervella(hip=None, ra=None, dec=None): """A star's Hipparcos-Gaia proper-motion anomaly, long-term proper motion and mass from Kervella et al. (2022), by Hipparcos number or else the nearest star within 10 arcsec, under VizieR's column names; None where the catalogue holds no star there or no anomaly for it.""" t = archive_vizier("J/A+A/657/A7", "Hip-EDR3-PMa_v7") if hip: i = np.where(t["HIP"].to_numpy(zero_copy_only=False) == hip)[0] else: a, d = (t[c].to_numpy(zero_copy_only=False).astype(float) for c in ("RA_ICRS", "DE_ICRS")) sep = np.hypot((np.remainder(a - ra + 180.0, 360.0) - 180.0) * math.cos(math.radians(dec)), d - dec) i = np.where(sep == np.nanmin(sep))[0] if np.nanmin(sep) < 10.0 / 3600.0 else [] if not len(i): return None row = {k: t[c][int(i[0])].as_py() for k, c in archive_KERVELLA.items()} if not all(archive_num(row[k]) is not None for k in ("pmRAH2EG3b", "pmDEH2EG3b", "PMaRAH2EG3b", "PMaDEH2EG3b", "snrPMaH2EG3b")): return None return dict(row, source="Kervella et al. (2022)") archive_NIST_LINES = ("https://physics.nist.gov/cgi-bin/ASD/lines1.pl?spectra=%s&output_type=0&low_w=%g&upp_w=%g&unit=0" "&submit=Retrieve+Data&de=0&plot_out=0&I_scale_type=1&format=3&line_out=0&remove_js=on&en_unit=0&output=0" "&bibrefs=1&page_size=15&show_obs_wl=1&show_calc_wl=1&unc_out=1&order_out=0&max_low_enrg=&show_av=2" "&max_upp_enrg=&tsb_value=0&min_str=&A_out=0&intens_out=on&max_str=&allowed_out=1&forbid_out=1" "&min_accur=&min_intens=&conf_out=on&term_out=on&enrg_out=on&J_out=on") def archive_nist_lines(spectrum, lo, hi, cache_dir=None): """NIST ASD lines of one spectrum between lo and hi (A): ion, vacuum wavelength, intensity, Aki, lower-level energy.""" path = None if cache_dir: os.makedirs(cache_dir, exist_ok=True) path = os.path.join(cache_dir, "%s_%g_%g.tsv" % (spectrum.replace(" ", "_"), lo, hi)) if path and os.path.exists(path): t = open(path, encoding="utf-8").read() else: b = archive_get(archive_NIST_LINES % (urllib.parse.quote_plus(spectrum), lo, hi), timeout=300, retries=3, soft=True) t = b.decode("utf-8", "replace") if b else "" if "Input Error" in t or " 2000.0: w = float(archive_air_to_vac(w)) out.append(dict(ion=spectrum, lam=w, intens=r.get("intens", ""), aki=r.get("Aki(s^-1)", ""), ei=r.get("Ei(cm-1)", ""))) return out def archive_run_cli(main, description=None): """The command line of a mode run as its analysis, or as `record`, which also writes the run's record; every other keyword of MAIN is an option, `--name value` (a list as several values), with the keyword's default; DESCRIPTION is the mode's help.""" archive_quiet_warnings() p = argparse.ArgumentParser(prog=sys.argv[0], description=description, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("mode", nargs="?", choices=("run", "record"), default="run") for name, par in inspect.signature(main).parameters.items(): d = par.default if name == "record" or d is inspect.Parameter.empty or d is None: continue flag = "--" + name.replace("_", "-") if isinstance(d, bool): p.add_argument(flag, dest=name, default=d, type=lambda v: v.lower() in ("1", "true", "yes", "on")) elif isinstance(d, (list, tuple)): p.add_argument(flag, dest=name, default=list(d), nargs="+", type=type(d[0]) if d else str) else: p.add_argument(flag, dest=name, default=d, type=type(d)) a = vars(p.parse_args()) main(record=a.pop("mode") == "record", **a) archive_SITES = {"Paranal": (-70.4045, -24.6272, 2635.0), "LaSilla": (-70.7380, -29.2567, 2400.0), "CFHT": (-155.4681, 19.8253, 4204.0)} def archive_location(site): """EarthLocation of a named site among the observatories whose spectra are read.""" from astropy.coordinates import EarthLocation import astropy.units as u lon, lat, h = archive_SITES[site] return EarthLocation.from_geodetic(lon=lon * u.deg, lat=lat * u.deg, height=h * u.m) def archive_barycentric_correction(ra, dec, mjd_utc, site): """Barycentric correction (km/s) for an observatory-frame radial velocity.""" from astropy.coordinates import SkyCoord from astropy.time import Time import astropy.units as u return SkyCoord(ra * u.deg, dec * u.deg).radial_velocity_correction( kind="barycentric", obstime=Time(mjd_utc, format="mjd"), location=archive_location(site)).to(u.km / u.s).value def archive_vac_to_air(w): """Air wavelength (A) of a vacuum wavelength (Morton 2000).""" s2 = (1e4 / np.asarray(w, float)) ** 2 return w / (1.0 + 0.0000834254 + 0.02406147 / (130.0 - s2) + 0.00015998 / (38.9 - s2)) def archive_air_to_vac(w, iterations=3): """Vacuum wavelength (A) of an air wavelength.""" v = np.asarray(w, float).copy() for _ in range(iterations): v = v + (w - archive_vac_to_air(v)) return v def archive_tag(*parts): """A file name of PARTS joined by underscores, every character but a letter, a digit or one of +_.- made an underscore.""" return re.sub(r"[^A-Za-z0-9+_.-]", "_", "_".join(str(p) for p in parts)) # The array work, in torch on ORBITLIGHT_DEVICE (the CUDA device where there is one, else the CPU): arrays or tensors in, tensors out. gpu_DEVICE = torch.device(os.environ.get("ORBITLIGHT_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu")) gpu_F64 = torch.float64 gpu_NAN = float("nan") def gpu_budget(): """The most bytes one intermediate block may take: a gibibyte on a card, and on the CPU a sixteenth of the memory free when the process starts, a gibibyte at most.""" if gpu_DEVICE.type == "cuda": return 1 << 30 try: import psutil return int(min(1 << 30, max(1 << 26, psutil.virtual_memory().available / 16))) except ImportError: return 1 << 28 gpu_BUDGET = gpu_budget() def gpu_dev(x, dtype=gpu_F64): """An array, list or tensor as a tensor of DTYPE on the device.""" if isinstance(x, torch.Tensor): return x.to(device=gpu_DEVICE, dtype=dtype) return torch.as_tensor(np.asarray(x), dtype=dtype, device=gpu_DEVICE) def gpu_host(x): """A tensor as a numpy array.""" return x.detach().cpu().numpy() if isinstance(x, torch.Tensor) else np.asarray(x) def gpu_interp(x, xp, fp, left=gpu_NAN, right=gpu_NAN): """Linear interpolation: the rows FP (..., n), given at the increasing abscissae XP (n,), read at X, LEFT below XP and RIGHT above it.""" x, xp, fp = gpu_dev(x), gpu_dev(xp), gpu_dev(fp) n = xp.shape[-1] j = torch.searchsorted(xp, x, right=True).clamp(1, n - 1) x0, x1 = xp[j - 1], xp[j] d = x1 - x0 w = torch.where(d > 0, (x - x0) / torch.where(d > 0, d, torch.ones_like(d)), torch.zeros_like(d)) out = fp[..., j - 1] + (fp[..., j] - fp[..., j - 1]) * w out = torch.where(x < xp[0], torch.full_like(out, left), out) return torch.where(x > xp[-1], torch.full_like(out, right), out) def gpu_interp_rows(x, xps, fps): """numpy.interp of each pair (xp, fp) of XPS and FPS at the abscissae X, NaN beyond each xp's ends, as rows (pairs, len(x)), with numpy's own arithmetic: the value at an abscissa equal to a sample, else the slope times the distance from the sample below plus its value, from the sample above where that is not finite.""" X = gpu_dev(x) L = max([len(a) for a in xps] + [2]) XP = torch.full((len(xps), L), float("inf"), dtype=gpu_F64, device=gpu_DEVICE) FP = torch.full((len(xps), L), gpu_NAN, dtype=gpu_F64, device=gpu_DEVICE) last = torch.as_tensor([len(a) - 1 for a in xps], device=gpu_DEVICE) for i, (a, b) in enumerate(zip(xps, fps)): XP[i, :len(a)], FP[i, :len(b)] = gpu_dev(a), gpu_dev(b) Xb = X[None, :].expand(len(xps), -1).contiguous() j = (torch.searchsorted(XP, Xb, right=True) - 1).clamp(min=0) j = torch.minimum(j, (last - 1).clamp(min=0)[:, None]) x0, x1, f0, f1 = XP.gather(1, j), XP.gather(1, j + 1), FP.gather(1, j), FP.gather(1, j + 1) slope = (f1 - f0) / (x1 - x0) out = slope * (Xb - x0) + f0 out = torch.where(torch.isnan(out), slope * (Xb - x1) + f1, out) out = torch.where(torch.isnan(out) & (f0 == f1), f0, out) out = torch.where(Xb == x0, f0, out) xlast, flast = XP.gather(1, last.clamp(min=0)[:, None]), FP.gather(1, last.clamp(min=0)[:, None]) out = torch.where(Xb == xlast, flast.expand_as(out), out) return torch.where((Xb < XP[:, :1]) | (Xb > xlast) | (last[:, None] < 0), torch.full_like(out, gpu_NAN), out) def gpu_shift_rows(rows, v, left=gpu_NAN, right=gpu_NAN): """Each row of ROWS (b, n), sampled on the integer grid centred on zero, read by linear interpolation at the grid plus its own shift V[i], LEFT and RIGHT beyond its ends.""" rows, v = gpu_dev(rows), gpu_dev(v) n = rows.shape[1] x = torch.arange(n, dtype=gpu_F64, device=gpu_DEVICE)[None, :] + v[:, None] j = torch.floor(x).clamp(0, n - 2).long() fr = x - j r = torch.arange(rows.shape[0], device=gpu_DEVICE)[:, None] out = rows[r, j] * (1.0 - fr) + rows[r, j + 1] * fr out = torch.where(x < 0, torch.full_like(out, left), out) return torch.where(x > n - 1, torch.full_like(out, right), out) def gpu_running_median(y, size): """The running median along the last axis of Y: at each sample the element of rank SIZE // 2 among the SIZE samples centred on it, the ends repeated.""" y = gpu_dev(y) lead, tail = size // 2, size - 1 - size // 2 shape = y.shape[:-1] p = torch.cat([y[..., :1].expand(*shape, lead), y, y[..., -1:].expand(*shape, tail)], -1) n = y.shape[-1] if gpu_DEVICE.type == "cuda" and 2 * (size - 1) <= 4096 and _gpu_kernels() is not None: return _gpu_kernels().running_median_rows(p.reshape(-1, p.shape[-1]).contiguous(), n, size, _gpu_stream()).reshape(y.shape) chunk = max(1024, int(gpu_BUDGET / (8 * size * max(int(np.prod(shape)), 1)))) out = torch.empty_like(y) for c0 in range(0, n, chunk): c1 = min(c0 + chunk, n) out[..., c0:c1] = p[..., c0:c1 + size - 1].unfold(-1, size, 1).kthvalue(size // 2 + 1, dim=-1).values return out def gpu_nanmedian(F, dim=0): """The median along DIM over finite values: the mean of the two middle values where their count is even, NaN where there is none.""" X = gpu_dev(F).movedim(dim, 0) fin = torch.isfinite(X) n = fin.sum(0) S = torch.sort(torch.where(fin, X, torch.full_like(X, float("inf"))), dim=0).values lo, hi = torch.clamp((n - 1) // 2, min=0), torch.clamp(n // 2, min=0) med = 0.5 * (S.gather(0, lo[None]) + S.gather(0, hi[None]))[0] return torch.where(n > 0, med, torch.full_like(med, gpu_NAN)) def gpu_nanmean(F, dim=0): """The mean along DIM over finite values.""" X = gpu_dev(F) fin = torch.isfinite(X) n = fin.sum(dim) s = torch.where(fin, X, torch.zeros_like(X)).sum(dim) return torch.where(n > 0, s / n.clamp(min=1), torch.full_like(s, gpu_NAN)) def gpu_nanstd(F, dim=0): """The standard deviation along DIM over finite values, no degree of freedom removed.""" X = gpu_dev(F) fin = torch.isfinite(X) n = fin.sum(dim) m = gpu_nanmean(X, dim) d = torch.where(fin, X - m.unsqueeze(dim), torch.zeros_like(X)) v = (d * d).sum(dim) / n.clamp(min=1) return torch.where(n > 0, torch.sqrt(v), torch.full_like(v, gpu_NAN)) def gpu_rowpoly(F, deg=3, least=100): """Each row of F divided by a polynomial of degree DEG in x = (i - n/2) / n fitted by least squares over its finite samples, rows of LEAST finite samples or fewer left as they are.""" X = gpu_dev(F) n = X.shape[1] x = (torch.arange(n, dtype=gpu_F64, device=gpu_DEVICE) - n / 2.0) / n V = torch.stack([x ** k for k in range(deg, -1, -1)], 1) fin = torch.isfinite(X) G = (fin.to(gpu_F64) @ (V[:, :, None] * V[:, None, :]).reshape(n, -1)).reshape(-1, deg + 1, deg + 1) b = torch.where(fin, X, torch.zeros_like(X)) @ V use = fin.sum(1) > least out = X.clone() if use.any(): c = torch.linalg.solve(G[use], b[use][:, :, None])[:, :, 0] out[use] = X[use] / (c @ V.T) return out def gpu_sysrem(R, sd, n=3): """SysRem (Tamuz et al. 2005) over the residual matrix R: N rank-one systematics, each the product of a per-row and a per-column factor fitted by six alternations weighted by each column's scatter SD, taken out of every row, NaN left as it is.""" R = gpu_dev(R) fin = torch.isfinite(R) X = torch.where(fin, R, torch.zeros_like(R)) W = torch.where(fin, 1.0 / torch.clamp(gpu_dev(sd), min=1e-12)[None, :] ** 2, torch.zeros_like(R)) for _ in range(n): a = torch.ones(X.shape[0], dtype=gpu_F64, device=gpu_DEVICE) c = torch.zeros(X.shape[1], dtype=gpu_F64, device=gpu_DEVICE) for _ in range(6): c = (W * X * a[:, None]).sum(0) / torch.clamp((W * a[:, None] ** 2).sum(0), min=1e-30) a = (W * X * c[None, :]).sum(1) / torch.clamp((W * c[None, :] ** 2).sum(1), min=1e-30) X = X - a[:, None] * c[None, :] return torch.where(fin, X, torch.full_like(X, gpu_NAN)) def gpu_xcorr(R, T, sd=None, vmax=300): """The inverse-variance cross-correlation of each residual row of R with the template T over -VMAX..VMAX samples, each sample weighted by its scatter SD (columns not finite in every row given no weight), normalised by the weighted template's norm over the samples it meets at each lag, so that a row of unit noise gives unit scatter: absorption positive; (rows, 2 VMAX + 1).""" R, T = gpu_dev(R), gpu_dev(T) n = R.shape[1] w = 1.0 / gpu_dev(sd) if sd is not None else torch.ones(n, dtype=gpu_F64, device=gpu_DEVICE) fin = torch.isfinite(R) Wt = torch.where(fin.all(0), w, torch.zeros_like(w)) X = torch.where(fin, R * w[None, :], torch.zeros_like(R)) * Wt[None, :] m = 1 << int(math.ceil(math.log2(2 * n))) ft = torch.conj(torch.fft.rfft(T, m)) den = torch.fft.irfft(torch.fft.rfft(Wt ** 2, m) * torch.conj(torch.fft.rfft(T ** 2, m)), m) pick = torch.cat([torch.arange(m - vmax, m, device=gpu_DEVICE), torch.arange(0, vmax + 1, device=gpu_DEVICE)]) norm = torch.sqrt(torch.clamp(den[pick], min=1e-30)) rows = max(1, int(gpu_BUDGET / (16 * m))) out = torch.empty((R.shape[0], 2 * vmax + 1), dtype=gpu_F64, device=gpu_DEVICE) for i0 in range(0, R.shape[0], rows): out[i0:i0 + rows] = -torch.fft.irfft(torch.fft.rfft(X[i0:i0 + rows], m) * ft, m)[:, pick] / norm return out def gpu_planet_frame(ccf, vp, w, kp_grid, vrest): """Cross-correlation rows summed in the planet's frame: for each trial semi-amplitude K_p and rest velocity, each row read at vrest + K_p VP[k] by linear interpolation on its one km/s grid (nothing beyond its ends) and weighted by W[k]; (K_p, rest velocity).""" ccf, vp, w, kp, vr = gpu_dev(ccf), gpu_dev(vp), gpu_dev(w), gpu_dev(kp_grid), gpu_dev(vrest) vmax = (ccf.shape[1] - 1) // 2 x = vr[None, None, :] + kp[:, None, None] * vp[None, :, None] + vmax j = torch.floor(x).clamp(0, 2 * vmax - 1).long() fr = x - j r = torch.arange(ccf.shape[0], device=gpu_DEVICE)[None, :, None] val = ccf[r, j] * (1.0 - fr) + ccf[r, j + 1] * fr val = torch.where((x >= 0) & (x <= 2 * vmax), val, torch.zeros_like(val)) return (w[None, :, None] * val).sum(1) / max(float(w.sum()), 1e-9) def gpu_kepler_E(M, e, iterations=16): """The eccentric anomaly of mean anomalies M and eccentricities E (broadcast), by Newton's method from M + e sin M (1 + e cos M).""" E = M + e * torch.sin(M) * (1 + e * torch.cos(M)) for _ in range(iterations): E = E - (E - e * torch.sin(E) - M) / (1 - e * torch.cos(E)) return E _gpu_CUDA = r""" #include #include __device__ double kepler_E(double t, double P, double tp, double ec) { double x = (t - tp) / P; double M = 6.283185307179586 * (x - floor(x)); double E = M + ec * sin(M) * (1.0 + ec * cos(M)); for (int it = 0; it < 40; ++it) { double d = (E - ec * sin(E) - M) / (1.0 - ec * cos(E)); E -= d; if (fabs(d) < 1e-15) break; } return E; } __device__ double kepler_shape(double t, double P, double tp, double ec, double w) { double E = kepler_E(t, P, tp, ec); double nu = 2.0 * atan2(sqrt(1.0 + ec) * sin(0.5 * E), sqrt(1.0 - ec) * cos(0.5 * E)); return cos(nu + w) + ec * cos(w); } __global__ void keplerian_kernel(const double* t, const double* P, const double* tp, const double* e, const double* w, double* out, long nb, long nt, long tstride, int shape) { long i = (long) blockIdx.x * blockDim.x + threadIdx.x; if (i >= nb * nt) return; long b = i / nt, k = i % nt; double tk = t[b * tstride + k]; out[i] = shape ? kepler_shape(tk, P[b], tp[b], e[b], w[b]) : kepler_E(tk, P[b], tp[b], e[b]); } at::Tensor keplerian_rows(at::Tensor t, at::Tensor P, at::Tensor tp, at::Tensor e, at::Tensor w, int64_t shape, int64_t stream) { long nb = P.size(0), nt = t.size(t.dim() - 1); long tstride = t.dim() == 2 ? nt : 0; auto out = at::empty({nb, nt}, t.options()); long n = nb * nt; if (n > 0) keplerian_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(t.data_ptr(), P.data_ptr(), tp.data_ptr(), e.data_ptr(), w.data_ptr(), out.data_ptr(), nb, nt, tstride, (int) shape); return out; } // the census model's residuals: problem q at night k, the linear part plus each Keplerian's |K| shape, less the velocity, over the error, times the mask __global__ void census_kernel(const double* p, const long long* owner, const double* T, const double* V, const double* S, const double* M, const double* X, double* out, long m, long n, long R, int nl, int nk, int kp) { long i = (long) blockIdx.x * blockDim.x + threadIdx.x; if (i >= m * n) return; long q = i / n, k = i % n, r = (long) owner[q]; const double* pq = p + q * kp; double mod = pq[0] * X[r * n + k]; for (int j = 1; j < nl; ++j) mod = mod + pq[j] * X[((long) j * R + r) * n + k]; double t = T[r * n + k]; for (int c = 0; c < nk; ++c) { const double* kq = pq + nl + 5 * c; mod = mod + fabs(kq[4]) * kepler_shape(t, kq[0], kq[1], fmin(kq[2] * kq[2] + kq[3] * kq[3], 0.9), atan2(kq[3], kq[2])); } out[i] = (mod - V[r * n + k]) / S[r * n + k] * M[r * n + k]; } at::Tensor census_residuals(at::Tensor p, at::Tensor owner, at::Tensor T, at::Tensor V, at::Tensor S, at::Tensor M, at::Tensor X, int64_t nl, int64_t nk, int64_t stream) { long m = p.size(0), R = T.size(0), n = T.size(1); auto out = at::empty({m, n}, p.options()); if (m * n > 0) census_kernel<<<(m * n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(p.data_ptr(), (const long long*) owner.data_ptr(), T.data_ptr(), V.data_ptr(), S.data_ptr(), M.data_ptr(), X.data_ptr(), out.data_ptr(), m, n, R, (int) nl, (int) nk, (int) p.size(1)); return out; } // one thread per symmetric positive-definite system: Cholesky in place, then forward and back substitution __global__ void spd_kernel(double* A, double* x, long nb, int k) { long q = (long) blockIdx.x * blockDim.x + threadIdx.x; if (q >= nb) return; double* a = A + q * k * k; double* b = x + q * k; for (int j = 0; j < k; ++j) { double d = a[j * k + j]; for (int c = 0; c < j; ++c) d -= a[j * k + c] * a[j * k + c]; d = sqrt(d); a[j * k + j] = d; for (int i = j + 1; i < k; ++i) { double s = a[i * k + j]; for (int c = 0; c < j; ++c) s -= a[i * k + c] * a[j * k + c]; a[i * k + j] = s / d; } } for (int i = 0; i < k; ++i) { double s = b[i]; for (int c = 0; c < i; ++c) s -= a[i * k + c] * b[c]; b[i] = s / a[i * k + i]; } for (int i = k - 1; i >= 0; --i) { double s = b[i]; for (int c = i + 1; c < k; ++c) s -= a[c * k + i] * b[c]; b[i] = s / a[i * k + i]; } } at::Tensor spd_solve(at::Tensor A, at::Tensor b, int64_t stream) { auto a = A.contiguous().clone(); auto x = b.contiguous().clone(); long nb = a.size(0); if (nb > 0) spd_kernel<<<(nb + 127) / 128, 128, 0, (cudaStream_t) stream>>>(a.data_ptr(), x.data_ptr(), nb, (int) a.size(1)); return x; } // each block sorts one tile's samples with their positions in shared memory, and each thread walks the sorted list for its window's median __global__ void running_median_kernel(const double* P, double* out, long n, long width, int size, int tile, int cap) { extern __shared__ double smem[]; double* val = smem; int* pos = (int*) (smem + cap); long r = blockIdx.y; long t0 = (long) blockIdx.x * tile; int count = (int) (n - t0 < tile ? n - t0 : tile); int len = count + size - 1; const double* row = P + r * width + t0; for (int i = threadIdx.x; i < cap; i += blockDim.x) { double x = i < len ? row[i] : INFINITY; val[i] = isnan(x) ? INFINITY : x; pos[i] = i < len ? i : 0x7fffffff; } __syncthreads(); for (int k = 2; k <= cap; k <<= 1) { for (int j = k >> 1; j > 0; j >>= 1) { for (int i = threadIdx.x; i < cap; i += blockDim.x) { int l = i ^ j; if (l > i) { double a = val[i], b = val[l]; int pa = pos[i], pb = pos[l]; bool greater = a > b || (a == b && pa > pb); if (greater == ((i & k) == 0)) { val[i] = b; val[l] = a; pos[i] = pb; pos[l] = pa; } } } __syncthreads(); } } for (int o = threadIdx.x; o < count; o += blockDim.x) { int need = size / 2; for (int i = 0; i < len; ++i) { int p = pos[i]; if (p >= o && p < o + size) { if (need == 0) { out[r * n + t0 + o] = val[i]; break; } --need; } } } } // each string's FNV-1a hash over its bytes, spaces and tabs dropped and ASCII letters in capitals __global__ void key_hash_kernel(const unsigned char* data, const long long* offsets, long long* out, long n) { long i = (long) blockIdx.x * blockDim.x + threadIdx.x; if (i >= n) return; unsigned long long h = 14695981039346656037ULL; for (long long k = offsets[i]; k < offsets[i + 1]; ++k) { unsigned char c = data[k]; if (c == ' ' || c == '\t') continue; if (c >= 'a' && c <= 'z') c -= 32; h = (h ^ c) * 1099511628211ULL; } out[i] = (long long) h; } at::Tensor key_hash(at::Tensor data, at::Tensor offsets, int64_t stream) { long n = offsets.size(0) - 1; auto out = at::empty({n}, offsets.options()); if (n > 0) key_hash_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(data.data_ptr(), (const long long*) offsets.data_ptr(), (long long*) out.data_ptr(), n); return out; } at::Tensor running_median_rows(at::Tensor P, int64_t n, int64_t size, int64_t stream) { long rows = P.size(0), width = P.size(1); int cap = 64; while (cap < 2 * (size - 1)) cap <<= 1; int tile = cap - (int) (size - 1); auto out = at::empty({rows, n}, P.options()); if (rows > 0 && n > 0) { dim3 grid((unsigned) ((n + tile - 1) / tile), (unsigned) rows); running_median_kernel<<>>(P.data_ptr(), out.data_ptr(), n, width, (int) size, tile, cap); } return out; } // the light of a quadratically limb-darkened disk of radius R, in the unit disk's radius __device__ float lit_disk(float R, float c0, float c1, float c2) { float R2 = R * R, q = fmaxf(1.0f - R2, 0.0f); return 3.14159265358979f * (c0 * R2 + c1 * (2.0f / 3.0f) * (1.0f - q * sqrtf(q)) + c2 * (R2 - 0.5f * R2 * R2)); } // the fraction of the disk's light a disk of radius k at separation z hides, as gpu_occulted computes it: the covered inner disk in closed form and the // partly covered annuli by Gauss-Legendre over r = r0 + (r1 - r0)(1 - cos psi) / 2, CPSI holding cos psi and SPW sin psi times the weights __device__ float hidden_light(float z, float k, float u1, float u2, const float* cpsi, const float* spw, int nodes) { float c0 = 1.0f - u1 - u2, c1 = u1 + 2.0f * u2, c2 = -u2; float zz = fmaxf(z, 1e-9f); if (zz <= k - 1.0f) return 1.0f; float inner = fminf(fmaxf(k - zz, 0.0f), 1.0f), r0 = fabsf(zz - k), r1 = fminf(zz + k, 1.0f), span = fmaxf(r1 - r0, 0.0f), acc = 0.0f; if (r0 < 1.0f) { for (int j = 0; j < nodes; ++j) { float r = r0 + span * (1.0f - cpsi[j]) * 0.5f; float c = (r * r + zz * zz - k * k) / fmaxf(2.0f * r * zz, 1e-12f); float mu = sqrtf(fmaxf(1.0f - r * r, 0.0f)); acc += (c0 + c1 * mu + c2 * mu * mu) * 2.0f * r * acosf(fminf(fmaxf(c, -1.0f), 1.0f)) * span * 0.5f * spw[j]; } } return (lit_disk(inner, c0, c1, c2) + acc) / lit_disk(1.0f, c0, c1, c2); } // one body (row of PR: k, P, a, inc, ecc, w, u1, u2) at one time, its light averaged over the time's NS instants (TS, time-major), as gpu_transit // computes it __global__ void transit_kernel(const float* ts, const float* pr, const float* cpsi, const float* spw, float* out, long nb, long nt, int ns, int nodes) { long i = (long) blockIdx.x * blockDim.x + threadIdx.x; if (i >= nb * nt) return; long b = i / nt, j = i % nt; const float* q = pr + b * 8; float k = q[0], P = q[1], a = q[2], si = sinf(q[3]), e = q[4], w = q[5], u1 = q[6], u2 = q[7]; const float twopi = 6.28318530717959f; float hp = 1.57079632679490f - w; float ea = atan2f(sqrtf(1.0f - e * e) * sinf(hp), e + cosf(hp)); float base = ea - e * sinf(ea), sum = 0.0f; for (int s = 0; s < ns; ++s) { float M = fmodf(base + twopi * ts[j * ns + s] / P, twopi); if (M < 0.0f) M += twopi; float E = M + e * sinf(M) * (1.0f + e * cosf(M)); for (int it = 0; it < 12; ++it) E = E - (E - e * sinf(E) - M) / (1.0f - e * cosf(E)); float ta = 2.0f * atan2f(sqrtf(1.0f + e) * sinf(0.5f * E), sqrtf(1.0f - e) * cosf(0.5f * E)); float sn = sinf(w + ta); float z = a * (1.0f - e * e) / (1.0f + e * cosf(ta)) * sqrtf(fmaxf(1.0f - sn * sn * si * si, 0.0f)); z = sn > 0.0f ? z : -z; sum += (z >= 0.0f && z < 1.0f + k) ? 1.0f - hidden_light(z, k, u1, u2, cpsi, spw, nodes) : 1.0f; } out[i] = sum / ns; } at::Tensor transit_rows(at::Tensor ts, at::Tensor pr, at::Tensor cpsi, at::Tensor spw, int64_t ns, int64_t stream) { long nb = pr.size(0), nt = ts.size(0) / ns; auto out = at::empty({nb, nt}, ts.options()); long n = nb * nt; if (n > 0) transit_kernel<<<(n + 255) / 256, 256, 0, (cudaStream_t) stream>>>(ts.data_ptr(), pr.data_ptr(), cpsi.data_ptr(), spw.data_ptr(), out.data_ptr(), nb, nt, (int) ns, (int) cpsi.size(0)); return out; } """ _gpu_kernel_module = [] def _gpu_msvc_environment(): """The Visual C++ build environment taken into this process from vcvars64.bat where cl is not already on the path, for the CUDA kernels' first build on Windows.""" if os.name != "nt" or shutil.which("cl"): return root = os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)") found = subprocess.run([os.path.join(root, "Microsoft Visual Studio", "Installer", "vswhere.exe"), "-latest", "-products", "*", "-property", "installationPath"], capture_output=True, text=True).stdout.strip() bat = os.path.join(found, "VC", "Auxiliary", "Build", "vcvars64.bat") text = subprocess.run('"%s" >nul && set' % bat, capture_output=True, text=True, shell=True).stdout for line in text.splitlines(): if "=" in line: key, val = line.split("=", 1) os.environ[key] = val def _gpu_kernels(): """The compiled kernels, the Keplerian curves, the census residuals, the positive-definite solves, the running medians, the identifier hashes and the transit light curves, built once and cached by torch, or None where there is no CUDA device or no compiler.""" if not _gpu_kernel_module: mod = None if gpu_DEVICE.type == "cuda": try: from torch.utils.cpp_extension import load_inline _gpu_msvc_environment() os.environ.setdefault("TORCH_CUDA_ARCH_LIST", "%d.%d" % torch.cuda.get_device_capability()) decl = ("torch::Tensor keplerian_rows(torch::Tensor t, torch::Tensor P, torch::Tensor tp, torch::Tensor e, torch::Tensor w, int64_t shape, " "int64_t stream);\ntorch::Tensor census_residuals(torch::Tensor p, torch::Tensor owner, torch::Tensor T, torch::Tensor V, " "torch::Tensor S, torch::Tensor M, torch::Tensor X, int64_t nl, int64_t nk, int64_t stream);\ntorch::Tensor spd_solve(torch::Tensor A, " "torch::Tensor b, int64_t stream);\ntorch::Tensor running_median_rows(torch::Tensor P, int64_t n, int64_t size, int64_t stream);\n" "torch::Tensor key_hash(torch::Tensor data, torch::Tensor offsets, int64_t stream);\ntorch::Tensor transit_rows(torch::Tensor ts, " "torch::Tensor pr, torch::Tensor cpsi, torch::Tensor spw, int64_t ns, int64_t stream);") mod = load_inline(name="orbitlight_kernels4", cpp_sources=decl, cuda_sources=_gpu_CUDA, extra_cuda_cflags=["-O3"], verbose=False, functions=["keplerian_rows", "census_residuals", "spd_solve", "running_median_rows", "key_hash", "transit_rows"]) except Exception: mod = None _gpu_kernel_module.append(mod) return _gpu_kernel_module[0] def _gpu_stream(): """The current CUDA stream's handle, on which the compiled kernels launch.""" return torch.cuda.current_stream().cuda_stream def _gpu_kernel_rows(t, P, tp, e, w, shape): """The compiled kernel for one orbit per row (b, 1) at times shared by every orbit (1, n) or of its own (b, n): the shape cos(nu + w) + e cos w, or with SHAPE false the eccentric anomaly; None where the kernel does not apply.""" if t.dim() == 2 and P.dim() == 2 and P.shape[1] == 1 and _gpu_kernels() is not None: b = max(P.shape[0], tp.shape[0], e.shape[0], w.shape[0], t.shape[0]) if t.shape[0] in (1, b) and all(z.dim() == 2 and z.shape[1] == 1 for z in (tp, e, w)): args = [z.reshape(-1).expand(b).contiguous() for z in (P, tp, e, w)] return _gpu_kernels().keplerian_rows(t[0].contiguous() if t.shape[0] == 1 else t.contiguous(), *args, int(shape), _gpu_stream()) return None def gpu_anomaly(t, P, tp, e): """The eccentric anomaly at times T of orbits (P, tp, e), each broadcast against T.""" t, P, tp, e = (gpu_dev(z) for z in (t, P, tp, e)) E = _gpu_kernel_rows(t, P, tp, e, torch.zeros_like(P), False) if E is not None: return E return gpu_kepler_E(2 * math.pi * torch.remainder((t - tp) / P, 1.0), e) def gpu_keplerian(t, P, tp, e, w): """The unit Keplerian velocity curve cos(nu + w) + e cos w at times T for orbits (P, tp, e, w), each broadcast against T.""" t, P, tp, e, w = (gpu_dev(z) for z in (t, P, tp, e, w)) out = _gpu_kernel_rows(t, P, tp, e, w, True) if out is not None: return out E = gpu_kepler_E(2 * math.pi * torch.remainder((t - tp) / P, 1.0), e) nu = 2 * torch.atan2(torch.sqrt(1 + e) * torch.sin(E / 2), torch.sqrt(1 - e) * torch.cos(E / 2)) return torch.cos(nu + w) + e * torch.cos(w) def gpu_gls(t, y, dy=None, freqs=None, chunk=None): """The generalised Lomb-Scargle periodogram (Zechmeister and Kuerster 2009) with a floating mean, in the standard normalisation: at each frequency the share of the weighted variance about the weighted mean that a sinusoid takes out. Y may hold many series at the times T as rows (b, n); the power is (b, frequencies), or (frequencies,) for one series.""" t, Y = gpu_dev(t), gpu_dev(y) one = Y.dim() == 1 Y = Y[None, :] if one else Y w = torch.ones_like(t) if dy is None else 1.0 / gpu_dev(dy) ** 2 w = w / w.sum() f = gpu_dev(freqs) Yb = Y @ w Yc = Y - Yb[:, None] YY = (Yc * Yc) @ w chunk = chunk or max(1, int(gpu_BUDGET / (8 * 4 * len(t)))) out = torch.empty((Y.shape[0], len(f)), dtype=gpu_F64, device=gpu_DEVICE) tc = t - t.mean() for i0 in range(0, len(f), chunk): ph = 2 * math.pi * f[i0:i0 + chunk, None] * tc[None, :] c, s = torch.cos(ph), torch.sin(ph) C, S = c @ w, s @ w CC = (c * c) @ w - C * C SS = (s * s) @ w - S * S CS = (c * s) @ w - C * S YC = (Yc * w[None, :]) @ c.T YS = (Yc * w[None, :]) @ s.T D = CC * SS - CS * CS out[:, i0:i0 + chunk] = (SS[None, :] * YC ** 2 + CC[None, :] * YS ** 2 - 2 * CS[None, :] * YC * YS) / (YY[:, None] * D[None, :]) return out[0] if one else out def gpu_baluev(z, fmax, t, dy=None): """Baluev's (2008) false-alarm level of the highest peak Z of a standard-normalised generalised Lomb-Scargle periodogram searched up to FMAX: the single-frequency level joined to the Davies bound's expected number of upcrossings.""" from scipy.special import gammaln t = np.asarray(t, float) w = np.ones_like(t) if dy is None else np.asarray(dy, float) ** -2 w = w / w.sum() n = len(t) nh, nk = n - 1, n - 3 z = np.clip(np.asarray(z, float), 0.0, 1.0) single = (1.0 - z) ** (0.5 * nk) teff = math.sqrt(4 * math.pi * (np.dot(w, t ** 2) - np.dot(w, t) ** 2)) gam = math.sqrt(2.0 / nh) * math.exp(gammaln(nh / 2.0) - gammaln((nh - 1) / 2.0)) tau = fmax * teff * gam * (1.0 - z) ** (0.5 * (nk - 1)) * np.sqrt(0.5 * nh * z) # 1 - (1 - single) exp(-tau) return -np.expm1(-tau) + single * np.exp(-tau) def gpu_baluev_level(fap, fmax, t, dy=None): """The power at which gpu_baluev() gives the false-alarm level FAP, by bisection.""" lo, hi = 0.0, 1.0 for _ in range(100): mid = 0.5 * (lo + hi) lo, hi = (mid, hi) if float(gpu_baluev(mid, fmax, t, dy)) > fap else (lo, mid) return 0.5 * (lo + hi) def gpu_gls_fit(t, y, dy, f): """The floating-mean sinusoid at frequency F fitted to Y by weighted least squares: (offset, cosine and sine amplitudes).""" t, y = np.asarray(t, float), np.asarray(y, float) w = np.ones_like(t) if dy is None else np.asarray(dy, float) ** -2 X = np.column_stack([np.ones_like(t), np.cos(2 * np.pi * f * t), np.sin(2 * np.pi * f * t)]) * np.sqrt(w)[:, None] return np.linalg.lstsq(X, y * np.sqrt(w), rcond=None)[0] def gpu_solve_spd(A, b): """The solutions x of the symmetric positive-definite systems A x = b, A (m, k, k) and b (m, k): Cholesky in the compiled kernel on the GPU, torch's solver elsewhere.""" if A.is_cuda and _gpu_kernels() is not None: return _gpu_kernels().spd_solve(A, b, _gpu_stream()) return torch.linalg.solve(A, b[:, :, None])[:, :, 0] def gpu_lm(fun, p0, lo=None, hi=None, f_scale=None, iters=200, tol=1e-10, graph=False): """Least squares for many problems by Levenberg-Marquardt: FUN maps parameter rows (m, k) and the problem each belongs to (m,) to residuals (m, n), a problem's unused residuals zero; P0 (b, k) the starts; LO and HI (k,) or (b, k) bounds, every step projected into them and a parameter on a bound whose gradient points out of the box held there for the step; F_SCALE, where given, the soft L1 loss rho(z) = 2 (sqrt(1 + z) - 1) on (r / F_SCALE)^2 by iteratively reweighted steps. The Jacobian by central differences. A problem stops once a step improves its cost by less than TOL of it or no damping finds a better point. With GRAPH, on the GPU, every problem takes each step, those stopped left as they are, one step is captured as a CUDA graph and replayed, and the problems' state is read every ten steps; FUN must then launch device work alone. Returns the parameters (b, k) and each problem's sum of squared residuals at them, F_SCALE's loss applied where given.""" p0 = gpu_dev(p0) b, k = p0.shape lo = gpu_dev(lo).expand(b, k) if lo is not None else torch.full_like(p0, -float("inf")) hi = gpu_dev(hi).expand(b, k) if hi is not None else torch.full_like(p0, float("inf")) p = torch.minimum(torch.maximum(p0, lo), hi) def cost(r): if f_scale is None: return (r * r).sum(1) z = (r / f_scale) ** 2 return (2.0 * f_scale ** 2 * (torch.sqrt(1.0 + z) - 1.0)).sum(1) every = torch.arange(b, device=gpu_DEVICE) r = fun(p, every) c = cost(r) mu = torch.full((b,), 1e-3, dtype=gpu_F64, device=gpu_DEVICE) active = torch.ones(b, dtype=torch.bool, device=gpu_DEVICE) if graph and gpu_DEVICE.type == "cuda": rows = every.repeat_interleave(2 * k) def step(): h = 1e-7 * (1.0 + p.abs()) up = torch.minimum(p + h, hi) dn = torch.maximum(p - h, lo) steps = torch.cat([p[:, None, :] + torch.diag_embed(up - p), p[:, None, :] + torch.diag_embed(dn - p)], 1) rr = fun(steps.reshape(-1, k), rows).reshape(b, 2 * k, -1) J = ((rr[:, :k] - rr[:, k:]) / (up - dn).clamp(min=1e-300)[:, :, None]).transpose(1, 2) sw = torch.ones_like(r) if f_scale is None else (1.0 + (r / f_scale) ** 2) ** -0.25 Jw, rw = J * sw[:, :, None], r * sw g = (Jw.transpose(1, 2) @ rw[:, :, None])[:, :, 0] held = ((p <= lo) & (g > 0)) | ((p >= hi) & (g < 0)) Jw = Jw * (~held)[:, None, :] g = torch.where(held, torch.zeros_like(g), g) A = Jw.transpose(1, 2) @ Jw D = torch.diagonal(A, dim1=1, dim2=2).clamp(min=1e-30) A = A + torch.diag_embed(held.to(gpu_F64)) pn = torch.minimum(torch.maximum(p - gpu_solve_spd(A + mu[:, None, None] * torch.diag_embed(D), g), lo), hi) rn = fun(pn, every) cn = cost(rn) better = active & torch.isfinite(cn) & (cn < c) small = better & ((c - cn) <= tol * c.clamp(min=1e-30)) p.copy_(torch.where(better[:, None], pn, p)) r.copy_(torch.where(better[:, None], rn, r)) c.copy_(torch.where(better, cn, c)) mu.copy_(torch.where(active, torch.where(better, mu / 3.0, mu * 4.0).clamp(1e-12, 1e12), mu)) active.copy_(active & ~(small | (mu >= 1e12))) side = torch.cuda.Stream() side.wait_stream(torch.cuda.current_stream()) cap = torch.cuda.CUDAGraph() with torch.cuda.stream(side): step() cap.capture_begin() step() cap.capture_end() torch.cuda.current_stream().wait_stream(side) for it in range(1, iters): cap.replay() if it % 10 == 0 and not bool(active.any()): break return p, c for _ in range(iters): ia = torch.nonzero(active)[:, 0] pa, ra, ca, ma = p[ia], r[ia], c[ia], mu[ia] na = len(ia) la, ha = lo[ia], hi[ia] # central differences, one-sided at a bound h = 1e-7 * (1.0 + pa.abs()) up = torch.minimum(pa + h, ha) dn = torch.maximum(pa - h, la) steps = torch.cat([pa[:, None, :] + torch.diag_embed(up - pa), pa[:, None, :] + torch.diag_embed(dn - pa)], 1) rr = fun(steps.reshape(-1, k), ia.repeat_interleave(2 * k)).reshape(na, 2 * k, -1) J = ((rr[:, :k] - rr[:, k:]) / (up - dn).clamp(min=1e-300)[:, :, None]).transpose(1, 2) # the soft L1 loss as weights on the residuals and the Jacobian, rho'(z)^(1/2) = (1 + z)^(-1/4) sw = torch.ones_like(ra) if f_scale is None else (1.0 + (ra / f_scale) ** 2) ** -0.25 Jw, rw = J * sw[:, :, None], ra * sw g = (Jw.transpose(1, 2) @ rw[:, :, None])[:, :, 0] # a parameter on a bound whose descent would leave the box is held there for this step held = ((pa <= la) & (g > 0)) | ((pa >= ha) & (g < 0)) Jw = Jw * (~held)[:, None, :] g = torch.where(held, torch.zeros_like(g), g) A = Jw.transpose(1, 2) @ Jw D = torch.diagonal(A, dim1=1, dim2=2).clamp(min=1e-30) A = A + torch.diag_embed(held.to(gpu_F64)) pn = pa - gpu_solve_spd(A + ma[:, None, None] * torch.diag_embed(D), g) pn = torch.minimum(torch.maximum(pn, la), ha) rn = fun(pn, ia) cn = cost(rn) better = torch.isfinite(cn) & (cn < ca) small = better & ((ca - cn) <= tol * ca.clamp(min=1e-30)) p[ia] = torch.where(better[:, None], pn, pa) r[ia] = torch.where(better[:, None], rn, ra) c[ia] = torch.where(better, cn, ca) mu[ia] = torch.where(better, ma / 3.0, ma * 4.0).clamp(1e-12, 1e12) active[ia] = ~(small | (mu[ia] >= 1e12)) if not bool(active.any()): break return p, c def gpu_ensemble(logp, p0, steps, thin=10, seed=11, graph=False): """Ensemble MCMC on the device by differential-evolution moves (ter Braak 2006), one half of the walkers moved against the other: LOGP maps rows (b, d) to log-probabilities, P0 (walkers, d) starts the chain, and with GRAPH each step is a replayed CUDA graph. Returns every THIN-th step and each walker's acceptance fraction.""" x = gpu_dev(p0).clone() W, d = x.shape halves = (torch.arange(W // 2, device=gpu_DEVICE), torch.arange(W // 2, W, device=gpu_DEVICE)) lp = logp(x) g0 = torch.full((1,), 2.38 / math.sqrt(2.0 * d), dtype=gpu_F64, device=gpu_DEVICE) one = torch.ones(1, dtype=gpu_F64, device=gpu_DEVICE) torch.manual_seed(seed) chain = torch.empty(((steps + thin - 1) // thin, W, d), dtype=gpu_F64, device=gpu_DEVICE) moved = torch.zeros(W, dtype=gpu_F64, device=gpu_DEVICE) at = torch.zeros(1, dtype=torch.long, device=gpu_DEVICE) def step(): for a, b in (halves, halves[::-1]): na, nb = len(a), len(b) j = torch.randint(0, nb, (na,), device=gpu_DEVICE) 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 * (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]) lp[a] = torch.where(take, lq, lp[a]) moved[a] += take.to(gpu_F64) # each block of THIN steps writes one row, its last state kept chain.index_copy_(0, torch.div(at, thin, rounding_mode="floor"), x[None]) at.add_(1) if graph and gpu_DEVICE.type == "cuda": side = torch.cuda.Stream() side.wait_stream(torch.cuda.current_stream()) cap = torch.cuda.CUDAGraph() with torch.cuda.stream(side): step() cap.capture_begin() step() cap.capture_end() torch.cuda.current_stream().wait_stream(side) for _ in range(steps - 1): cap.replay() else: for _ in range(steps): step() return gpu_host(chain), gpu_host(moved / steps) def gpu_profile(logp, lo, hi, index, edges, pop=64, gens=1500, seeds=(7, 11, 13, 17)): """A log-probability's profile over one parameter: for each band of parameter INDEX between consecutive EDGES, the others within LO and HI, the best of LOGP (rows (b, d) to log-probabilities on the device) found by differential evolution run for every band at once, POP members a band for GENS generations (rand/1, crossover 0.9, the scale drawn from 0.5 to 1 each generation) from each of SEEDS, the better kept; then each band takes its neighbours' best parameters, moved into the band, wherever they fit better, until none improves. Returns each band's best log-probability and its parameters.""" G, d = len(edges) - 1, len(lo) LOb, HIb = gpu_dev(np.tile(lo, (G, 1))), gpu_dev(np.tile(hi, (G, 1))) LOb[:, index], HIb[:, index] = gpu_dev(edges[:-1]), gpu_dev(edges[1:]) rows = torch.arange(G, device=gpu_DEVICE)[:, None] cols = torch.arange(d, device=gpu_DEVICE) fb, xb = None, None for seed in seeds: gen = torch.Generator(device=gpu_DEVICE) gen.manual_seed(seed) x = LOb[:, None, :] + (HIb - LOb)[:, None, :] * torch.rand((G, pop, d), generator=gen, dtype=gpu_F64, device=gpu_DEVICE) f = logp(x.reshape(-1, d)).reshape(G, pop) for _ in range(gens): r = torch.randint(0, pop, (3, G, pop), generator=gen, device=gpu_DEVICE) scale = 0.5 + 0.5 * torch.rand(1, generator=gen, dtype=gpu_F64, device=gpu_DEVICE) v = x[rows, r[0]] + scale * (x[rows, r[1]] - x[rows, r[2]]) cross = (torch.rand((G, pop, d), generator=gen, dtype=gpu_F64, device=gpu_DEVICE) < 0.9) | (cols == torch.randint(0, d, (G, pop, 1), generator=gen, device=gpu_DEVICE)) trial = torch.minimum(torch.maximum(torch.where(cross, v, x), LOb[:, None, :]), HIb[:, None, :]) ft = logp(trial.reshape(-1, d)).reshape(G, pop) better = ft > f x, f = torch.where(better[..., None], trial, x), torch.where(better, ft, f) k = f.argmax(1) fs, xs = f[rows[:, 0], k], x[rows[:, 0], k] if fb is None: fb, xb = fs, xs else: keep = fs > fb fb, xb = torch.where(keep, fs, fb), torch.where(keep[:, None], xs, xb) # Each band then tries its neighbours' best parameters, moved into the band, keeping them where they fit better, until no band improves. inner = torch.arange(G, device=gpu_DEVICE) for _ in range(4 * G): moved = False for shift in (1, -1): cand = torch.minimum(torch.maximum(torch.roll(xb, shift, 0), LOb), HIb) fc = logp(cand) ok = (fc > fb) & ((inner >= 1) if shift == 1 else (inner <= G - 2)) xb, fb = torch.where(ok[:, None], cand, xb), torch.where(ok, fc, fb) moved = moved or bool(ok.any()) if not moved: break return gpu_host(fb), gpu_host(xb) def gpu_bls(t, y, dy, periods, durations, oversample=10): """Box least squares (Kovacs et al. 2002) on the device: at each trial period, the box of DURATIONS no longer than a quarter of the period and the phase with the highest depth over error, the periods taken in blocks and each block's phase cut into bins of 1/OVERSAMPLE of the shortest duration. Returns its signal-to-noise, depth, duration and mid-transit time per period.""" t, y, P = gpu_dev(t), gpu_dev(y), gpu_dev(periods) Ph = np.asarray(periods, float) w = 1.0 / gpu_dev(dy) ** 2 W, WY, t0 = w.sum(), (w * y).sum(), t.min() step = min(durations) / oversample best = [torch.full((len(P),), -float("inf"), dtype=gpu_F64, device=gpu_DEVICE)] + [torch.zeros(len(P), dtype=gpu_F64, device=gpu_DEVICE) for _ in range(3)] c0 = 0 while c0 < len(P): chunk = max(1, int(gpu_BUDGET / (48 * max(len(t), 2 * int(math.ceil(Ph[c0] / step)))))) nb = max(2, int(math.ceil(float(Ph[c0:c0 + chunk].max()) / step))) chunk = max(1, min(chunk, int(gpu_BUDGET / (48 * max(len(t), 2 * nb))))) Pc = P[c0:c0 + chunk] bins = torch.clamp((torch.remainder((t[None, :] - t0) / Pc[:, None], 1.0) * nb).long(), max=nb - 1) Wb = torch.zeros((len(Pc), nb), dtype=gpu_F64, device=gpu_DEVICE).scatter_add_(1, bins, w.expand(len(Pc), -1)) Yb = torch.zeros((len(Pc), nb), dtype=gpu_F64, device=gpu_DEVICE).scatter_add_(1, bins, (w * y).expand(len(Pc), -1)) del bins width = Pc / nb fits = [D for D in durations if D <= 0.25 * float(Ph[c0:c0 + chunk].min())] Ls = [torch.clamp(torch.round(D / width).long(), min=1, max=nb - 1) for D in fits] # cumulative sums with the first bins repeated as far as the longest box reaches, for boxes that wrap past phase one Lmax = max([int(L.max()) for L in Ls] + [1]) zero = torch.zeros((len(Pc), 1), dtype=gpu_F64, device=gpu_DEVICE) Wc = torch.cat([zero, torch.cumsum(torch.cat([Wb, Wb[:, :Lmax]], 1), 1)], 1) Yc = torch.cat([zero, torch.cumsum(torch.cat([Yb, Yb[:, :Lmax]], 1), 1)], 1) for D, L in zip(fits, Ls): idx = torch.arange(nb, device=gpu_DEVICE)[None, :] + L[:, None] Win, Yin = Wc.gather(1, idx) - Wc[:, :nb], Yc.gather(1, idx) - Yc[:, :nb] Wout = W - Win ok = (Win > 0) & (Wout > 0) Wi, Wo = Win.clamp(min=1e-300), Wout.clamp(min=1e-300) depth = (WY - Yin) / Wo - Yin / Wi snr = torch.where(ok, depth / torch.sqrt(1.0 / Wi + 1.0 / Wo), torch.full_like(depth, -float("inf"))) top, s = snr.max(1) up = top > best[0][c0:c0 + chunk] best[0][c0:c0 + chunk] = torch.where(up, top, best[0][c0:c0 + chunk]) best[1][c0:c0 + chunk] = torch.where(up, depth.gather(1, s[:, None])[:, 0], best[1][c0:c0 + chunk]) best[2][c0:c0 + chunk] = torch.where(up, torch.full_like(top, D), best[2][c0:c0 + chunk]) best[3][c0:c0 + chunk] = torch.where(up, t0 + (s + 0.5 * L) * width, best[3][c0:c0 + chunk]) c0 += len(Pc) return tuple(gpu_host(x) for x in best) # The spectra machinery the modes share: loading, grids, residuals, cross-correlation, the planet's frame and line-by-line velocities. # the speed of light (km/s) spectra_C = 299792.458 spectra_BANDS = {"optical": dict(lo=3800.0, hi=7880.0, telluric=((6270.0, 6330.0), (6440.0, 6620.0), (6860.0, 6970.0), (7150.0, 7360.0), (7580.0, 7720.0)), instruments=("ESPRESSO", "HARPS", "UVES", "FEROS", "SOPHIE", "HARPN")), "nir": dict(lo=9500.0, hi=25000.0, telluric=((11050.0, 11700.0), (13300.0, 14900.0), (17900.0, 19700.0), (24000.0, 25000.0)), instruments=("SPIRou", "NIRPS", "CRIRES", "NIRSPEC")), # the solar mode's span, for templates alone "visible": dict(lo=3800.0, hi=9500.0, telluric=((6270.0, 6330.0), (6440.0, 6620.0), (6860.0, 6970.0), (7150.0, 7360.0), (7580.0, 7720.0)), instruments=())} spectra_SKY = (5889.95, 5895.92) spectra_GRIDS = {} # the errors a missing, truncated or malformed FITS product raises, which skip the spectrum; any other error stops the run spectra_UNREADABLE = (OSError, ValueError, KeyError, IndexError, TypeError) def spectra_band(inst): """The band an instrument's spectra belong to.""" return next(b for b, d in spectra_BANDS.items() if inst in d["instruments"]) def spectra_grid(band="optical"): """A band's common wavelength grid (A, air), uniform in velocity at 1 km/s.""" if band not in spectra_GRIDS: lo, hi = spectra_BANDS[band]["lo"], spectra_BANDS[band]["hi"] n = int(np.log(hi / lo) * spectra_C) spectra_GRIDS[band] = lo * np.exp(np.arange(n) / spectra_C) return spectra_GRIDS[band] def spectra_gaps(g, wl): """The grid samples G whose nearest valid pixels WL on either side lie more than 3 km/s apart, where interpolation would stand in for missing data, as across the gap between two detectors.""" j = np.clip(np.searchsorted(wl, g), 1, len(wl) - 1) return (wl[j] / wl[j - 1] - 1.0) * spectra_C > 3.0 def spectra_onto(items, grid, size=501, clean_errors=False, dtype=float): """Spectra, each (wl, f, e) at wavelengths WL, read on GRID by linear interpolation over their samples of positive finite flux (with CLEAN_ERRORS, of positive finite error too) and divided by their running medians over SIZE samples (gpu_running_median), gaps given each spectrum's median: the fluxes and errors on the grid as rows of DTYPE, the errors None where E is, and the wavelengths each read.""" F, E, used = np.full((len(items), len(grid)), np.nan, dtype), None, [] if items and items[0][2] is not None: E = np.full((len(items), len(grid)), np.nan, dtype) step = max(1, int(gpu_BUDGET // (64 * len(grid)))) for b0 in range(0, len(items), step): xs, fs, es = [], [], [] for wl, f, e in items[b0:b0 + step]: ok = np.isfinite(f) & (f > 0) if clean_errors: ok &= np.isfinite(e) & (e > 0) xs.append(wl[ok]) fs.append(f[ok]) es.append(e[ok] if E is not None else None) used += xs FI = gpu_interp_rows(grid, xs, fs) cont = gpu_running_median(torch.where(torch.isfinite(FI), FI, gpu_nanmedian(FI, 1)[:, None]), size) F[b0:b0 + len(xs)] = gpu_host(FI / cont) if E is not None: E[b0:b0 + len(xs)] = gpu_host(gpu_interp_rows(grid, xs, es) / cont) return F, E, used def spectra_normalise(F, ref, band, E=None): """Rows on a band's grid divided by the median of the rows REF marks, the near-infrared's deep bands set aside, a cubic in wavelength divided out of each row and the telluric bands set aside, less one: the residuals, each wavelength's scatter among the REF rows floored at a tenth of its median, the errors E divided by the same median where given, and the median, as tensors.""" g = gpu_dev(spectra_grid(band)) master = gpu_nanmedian(F[ref], 0) R = F / master if band == "nir": # the near infrared's telluric bands and the samples where the median lies at 0.2 or below set aside before the fit R[:, ~(master > 0.2)] = gpu_NAN for lo, hi in spectra_BANDS[band]["telluric"]: R[:, (g > lo) & (g < hi)] = gpu_NAN R = gpu_rowpoly(R, 3) for lo, hi in spectra_BANDS[band]["telluric"]: R[:, (g > lo) & (g < hi)] = gpu_NAN R = R - 1.0 # each wavelength's scatter, the weight of the inverse-variance cross-correlation, floored at a tenth of its median sd = gpu_nanstd(R[ref], 0) floor = gpu_nanmedian(sd, 0) sd = torch.where(torch.isfinite(sd) & (sd > 0), torch.maximum(sd, 0.1 * floor), floor) return R, sd, (E / master if E is not None else None), master def spectra_sysrem(R, sd, n=3): """SysRem (Tamuz et al. 2005) over the residual matrix: N rank-one systematics, each the product of a per-spectrum and a per-wavelength factor fitted by alternation weighted by each wavelength's scatter SD, taken out of every spectrum, NaN left as it is.""" return gpu_host(gpu_sysrem(R, sd, n)) def spectra_ccf(R, T, sd=None, vmax=300): """Inverse-variance cross-correlation of each residual row with a template over -VMAX..VMAX km/s (one sample a km/s on the grid), each sample weighted by its scatter SD, the sum normalised by the weighted template's norm so a row of unit noise gives unit scatter: absorption positive.""" return gpu_host(gpu_xcorr(R, T, sd, vmax)) def lbl_lines(T, good): """A template's lines on the 0.4 km/s grid: its minima 4 per cent deep or more, each over the samples within 1.2 times its half-depth width, where GOOD holds over the whole window and no earlier line overlaps it: (start, end, minimum) per line.""" lines = [] for m in np.where((T[1:-1] < T[:-2]) & (T[1:-1] <= T[2:]) & (T[1:-1] < 0.96))[0] + 1: half = 1.0 - (1.0 - T[m]) / 2.0 lft, rgt = m, m while lft > 0 and T[lft] < half and m - lft < 40: lft -= 1 while rgt < len(T) - 1 and T[rgt] < half and rgt - m < 40: rgt += 1 hw = max(m - lft, rgt - m) l0, r0 = m - int(1.2 * hw) - 1, m + int(1.2 * hw) + 2 if l0 < 0 or r0 > len(T) or not good[l0:r0].all() or (lines and l0 < lines[-1][1]): continue lines.append((l0, r0, m)) return np.array(lines, int).reshape(-1, 3) def lbl_shifts(F, E, T, lines, chunk=512): """Each spectrum's shift in each line (m/s) by Bouchy's derivative estimate, the residual against the template T projected on its derivative with the line's own linear continuum solved beside it, with its photon error, in blocks of CHUNK lines: (V, SV), (spectra, lines), NaN where a line's equations are singular.""" dT = gpu_dev(np.gradient(T)) Td, Fd, Ed = gpu_dev(T), gpu_dev(F), gpu_dev(E) S, L = Fd.shape[0], len(lines) V = torch.full((S, L), gpu_NAN, dtype=gpu_F64, device=gpu_DEVICE) SV = torch.full((S, L), gpu_NAN, dtype=gpu_F64, device=gpu_DEVICE) for c0 in range(0, L, chunk): ln = lines[c0:c0 + chunk] width = ln[:, 1] - ln[:, 0] W = int(width.max()) k = torch.arange(W, device=gpu_DEVICE) l0, wd = torch.as_tensor(ln[:, 0], device=gpu_DEVICE), torch.as_tensor(width, device=gpu_DEVICE) inside = (k[None, :] < wd[:, None]).to(gpu_F64) idx = (l0[:, None] + k[None, :]).clamp(max=len(T) - 1) A = torch.stack([-dT[idx], torch.ones_like(inside), k[None, :].to(gpu_F64) - wd[:, None] / 2.0], -1) * inside[..., None] resid = (Fd[:, idx] - Td[idx][None]) * inside[None] wt = inside[None] / torch.clamp(Ed[:, idx], min=1e-4) ** 2 N = torch.einsum("slw,lwp,lwq->slpq", wt, A, A) b = torch.einsum("slw,lwp,slw->slp", wt, A, resid) ok = torch.linalg.det(N).abs() > 1e-12 cov = torch.linalg.inv(torch.where(ok[..., None, None], N, torch.eye(3, dtype=gpu_F64, device=gpu_DEVICE))) sol = (cov @ b[..., None])[..., 0] V[:, c0:c0 + chunk] = torch.where(ok, sol[..., 0] * 400.0, torch.full_like(sol[..., 0], gpu_NAN)) SV[:, c0:c0 + chunk] = torch.where(ok, torch.sqrt(torch.clamp(cov[..., 0, 0], min=0.0)) * 400.0, torch.full_like(sol[..., 0], gpu_NAN)) return gpu_host(V), gpu_host(SV) def lbl_corr(V, x, least): """Each column of V's Pearson correlation with X over the rows where both are finite, and its two-sided p-value from Student's t with n - 2 degrees of freedom; NaN where fewer than LEAST rows.""" from scipy.stats import t as student x = np.asarray(x, float) ok = np.isfinite(V) & np.isfinite(x)[:, None] n = ok.sum(0) with np.errstate(all="ignore"): xm = np.where(ok, x[:, None], 0.0).sum(0) / n vm = np.where(ok, V, 0.0).sum(0) / n dx, dv = np.where(ok, x[:, None] - xm, 0.0), np.where(ok, V - vm, 0.0) r = np.clip((dx * dv).sum(0) / np.sqrt((dx * dx).sum(0) * (dv * dv).sum(0)), -1.0, 1.0) p = 2.0 * student.sf(np.abs(r) * np.sqrt((n - 2) / np.maximum(1.0 - r * r, 1e-300)), n - 2) use = n >= least return np.where(use, r, np.nan), np.where(use, p, np.nan) def lbl_grid(): """The line-by-line grid, uniform in log wavelength at 0.4 km/s from 3800 to 6880 A.""" return 3800.0 * np.exp(np.arange(int(np.log(6880.0 / 3800.0) * spectra_C / 0.4)) * 0.4 / spectra_C) def lbl_indices(F, grid): """Each row of F on GRID's Ca II H and K index (S, uncalibrated: triangular cores of 1.09 A over continuum bands of 20 A) and H alpha index (a 1.6 A core over its two side bands).""" def band(i, centre, half, tri): k = np.abs(grid - centre) < half w_ = (1.0 - np.abs(grid[k] - centre) / half) if tri else np.ones(k.sum()) return float(np.nansum(F[i, k] * w_) / np.nansum(w_ * np.isfinite(F[i, k]))) S = np.array([(band(i, 3968.47, 1.09, True) + band(i, 3933.66, 1.09, True)) / (band(i, 3901.07, 10.0, False) + band(i, 4001.07, 10.0, False)) for i in range(len(F))]) HA = np.array([band(i, 6562.81, 0.8, False) / (0.5 * (band(i, 6550.87, 5.375, False) + band(i, 6580.31, 4.375, False))) for i in range(len(F))]) return S, HA def lbl_velocities(F, E, robust=False): """Spectra F (errors E) on the line-by-line grid measured line by line against their median: the median's lines (lbl_lines) and every spectrum's shift in each with its error (lbl_shifts), then three passes that set aside the shifts more than 5 robust standard deviations from their spectrum's median and give each line a jitter, the excess of its residuals' mean square about the spectra's weighted means over its errors' (with ROBUST, of their median square over 0.455, a normal law's, over its errors' median square): the lines, the shifts with those set aside NaN, their errors, and each shift's variance with its line's jitter.""" T = gpu_host(gpu_nanmedian(gpu_dev(F), 0)) lines = lbl_lines(T, np.isfinite(F).all(0) & np.isfinite(T)) V, SV = lbl_shifts(F, E, T, lines) jit = np.zeros(len(lines)) for _ in range(3): s2 = SV ** 2 + jit[None, :] ** 2 rv = np.nansum(V / s2, 1) / np.nansum(1.0 / s2, 1) res = V - rv[:, None] z = res / np.sqrt(s2) zc = z - np.nanmedian(z, 1)[:, None] V = np.where(np.abs(zc) < 5.0 * 1.4826 * np.nanmedian(np.abs(zc), 1)[:, None], V, np.nan) if robust: jit = np.sqrt(np.clip(np.nan_to_num(np.nanmedian(res ** 2, 0) / 0.455 - np.nanmedian(SV ** 2, 0)), 0.0, None)) else: jit = np.sqrt(np.clip(np.nan_to_num(np.nanmean(res ** 2 - SV ** 2, 0)), 0.0, None)) return lines, V, SV, SV ** 2 + jit[None, :] ** 2 def spectra_planet_frame(ccf, vp, w, kp_grid, vrest): """Cross-correlation rows summed in the planet's frame: a map over the trial semi-amplitudes K_p and rest velocities, VP holding each row's sin(2 pi phase) and W its weight.""" return gpu_host(gpu_planet_frame(ccf, vp, w, kp_grid, vrest)) def spectra_load_many(paths, threads=8): """spectra_load over PATHS on THREADS threads, in order, None for each product that does not load.""" def one(path): try: return spectra_load(path) except spectra_UNREADABLE: return None return archive_pmap(one, list(paths), threads) def spectra_read(paths): """The spectra at PATHS as spectra_load reads them, (w, f, e, meta) each, those that do not load left out.""" return [s for s in spectra_load_many(paths) if s is not None] def spectra_vsys(spectra, fallback=None): """A series' systemic velocity (km/s): the median of the pipeline velocities where the products carry them, else FALLBACK where given, else the SIMBAD mirror's for the star nearest the spectra's position within 10 arcsec, else the median of the observing blocks' target velocities, else zero.""" rvs = [s[3]["rv"] for s in spectra if s[3].get("rv") is not None] if rvs: return float(np.median(rvs)) if fallback is not None: return float(fallback) pos = [(s[3]["ra"], s[3]["dec"]) for s in spectra if s[3].get("ra") is not None and s[3].get("dec") is not None] if pos: v = archive_simbad_velocity_near(float(np.median([p[0] for p in pos])), float(np.median([p[1] for p in pos]))) if v is not None: return v obs = [s[3]["rv_ob"] for s in spectra if s[3].get("rv_ob") is not None] return float(np.median(obs)) if obs else 0.0 def spectra_align(F, master, max_kms=20): """Each row's velocity against the median spectrum (km/s): the whole-sample shift on the one km/s grid within MAX_KMS at which the row's lines match the median's best by least squares over the samples the median absorbs by 5 per cent or more, refined by a parabola through the best three.""" master = gpu_dev(master) use = torch.isfinite(master) & (master < 0.95) M = torch.where(use, master - 1.0, torch.zeros_like(master)) X = gpu_dev(F) - 1.0 X = torch.where(torch.isfinite(X), X, torch.zeros_like(X)) shifts = np.arange(-max_kms, max_kms + 1) # each row's cost at every whole-sample shift, the row wrapped round at its ends cost = gpu_host(torch.stack([(((torch.roll(X, -int(s), dims=1) - M[None, :]) ** 2) * use[None, :]).sum(1) for s in shifts], 1)) out = np.zeros(F.shape[0]) for i in range(F.shape[0]): k = int(np.argmin(cost[i])) if 0 < k < len(shifts) - 1: a, b, c = cost[i, k - 1], cost[i, k], cost[i, k + 1] den = a - 2 * b + c out[i] = shifts[k] + (0.5 * (a - c) / den if den > 0 else 0.0) else: out[i] = shifts[k] return out def spectra_residuals(spectra, vsys, band, align=True, info=None): """Residuals on the band's grid: each spectrum in the primary's frame (its header velocity, else VSYS, then its own shift against the median spectrum when ALIGN) over its running median, divided by the median spectrum, a cubic taken out, telluric regions and the samples across a gap half or more of the spectra share NaN; with each wavelength's scatter.""" g = spectra_grid(band) def onto(spectra, shifts): F, _, used = spectra_onto([(w / (1.0 + ((meta["rv"] if meta.get("rv") is not None else vsys) + dv) / spectra_C), f, None) for (w, f, e, meta), dv in zip(spectra, shifts)], g) return F, np.array([spectra_gaps(g, u) for u in used]) F, gaps = onto(spectra, np.zeros(len(spectra))) # a gap most of the spectra share, as between two detectors, set aside common = gaps.mean(0) >= 0.5 F[:, common] = np.nan if align: shifts = spectra_align(F, gpu_nanmedian(gpu_dev(F), 0)) moved = np.abs(shifts) >= 0.5 if moved.any(): F[moved] = onto([s for s, m in zip(spectra, moved) if m], shifts[moved])[0] F[:, common] = np.nan if info is not None: info["vstar"] = np.array([(meta["rv"] if meta.get("rv") is not None else vsys) + (dv if mv else 0.0) for (_, _, _, meta), dv, mv in zip(spectra, shifts, moved)]) every = torch.ones(len(F), dtype=torch.bool, device=gpu_DEVICE) R, sd, _, master = spectra_normalise(gpu_dev(F), every, band) return gpu_host(R), gpu_host(sd), gpu_host(master) def spectra_template(spectra, vsys, band): """A template star's absorption pattern on the band's grid: one minus its median normalised spectrum in its own frame, negative values zero.""" return spectra_depths(spectra_residuals(spectra, vsys, band)[2]) def spectra_depths(master): """A normalised spectrum's line depths: one minus it, negative values and gaps zero.""" return np.where(np.isfinite(master), np.clip(1.0 - master, 0.0, None), 0.0) def spectra_lambert(phase): """Lambert's phase function at orbital phase PHASE (0 at inferior conjunction): zero there and one at superior conjunction, where the lit face is full.""" alpha = 2.0 * np.pi * np.abs(np.asarray(phase, float) - 0.5) return (np.sin(alpha) + (np.pi - alpha) * np.cos(alpha)) / np.pi def spectra_unpattern(ccf, half=40): """The star's own pattern taken out of every cross-correlation row at its own strength: the rows' median shape, scaled to each row by least squares within HALF km/s of the star's velocity and subtracted over the whole row, then the rows' remaining median.""" vmax = (ccf.shape[1] - 1) // 2 pattern = np.median(ccf, axis=0) core = slice(vmax - half, vmax + half + 1) pc = pattern[core] scale = (ccf[:, core] * pc[None, :]).sum(1) / max(float((pc ** 2).sum()), 1e-30) out = ccf - scale[:, None] * pattern[None, :] return out - np.median(out, axis=0)[None, :] def spectra_components(ccf, k): """The cross-correlation rows with their K leading principal components taken out, the shapes the star's own residual pattern takes from night to night, which a companion's trail, moving from row to row, does not share.""" if not k: return ccf U, S, Vt = np.linalg.svd(ccf, full_matrices=False) return ccf - (U[:, :k] * S[:k]) @ Vt[:k] def spectra_lay(w, f, T, v, depth, band="optical"): """The flux F at wavelengths W with the line depths T, given on a band's grid, laid into it at DEPTH and moved by V km/s.""" return f * (1.0 - depth * np.interp(w, spectra_grid(band) * (1.0 + v / spectra_C), T, left=0.0, right=0.0)) def spectra_kp(p, a_au=0.05): """A planet's orbital speed (km/s) on a circular orbit of the archive's semi-major axis, A_AU where it gives none.""" return 2 * np.pi * (p["pl_orbsmax"] or a_au) * 1.495978707e8 / (p["pl_orbper"] * 86400.0) def spectra_load(path): """A spectrum as air wavelengths (A) in the barycentric frame, flux and error, with its mid-time (MJD), the pipeline's stellar velocity (km/s) where the header holds one, and its instrument.""" from astropy.io import fits with fits.open(path) as h: H = h[0].header if "HIERARCH OHP DRS BJD" in H: # SOPHIE's one-dimensional spectrum of the object's fibre, already in air and the barycentric frame, its flux relative and its error from the signal-to-noise of the order near 5300 A f = np.asarray(h[0].data, float) w = float(H["CRVAL1"]) + float(H["CDELT1"]) * np.arange(len(f)) snr = archive_num(H.get("HIERARCH OHP DRS CAL EXT SN26"), float("nan")) e = np.sqrt(np.abs(f) * abs(float(np.nanmedian(f[(w > 5200.0) & (w < 5400.0)])))) / snr if snr and snr > 0 else np.sqrt(np.abs(f)) return w, f, e, dict(mjd=float(H["HIERARCH OHP DRS BJD"]) - 2400000.5, rv=None, rv_ob=None, inst="SOPHIE", snr=snr, berv=float(H["HIERARCH OHP DRS BERV"]), ra=None, dec=None) if "HIERARCH TNG QC BJD" in H: # HARPS-N's newer one-dimensional spectrum, a row a sample, in the barycentric frame, its samples of any quality flag set aside t = h[1].data f = np.where(np.asarray(t["quality"]) == 0, np.asarray(t["flux"], float), np.nan) return np.asarray(t["wavelength_air"], float), f, np.asarray(t["error"], float), dict(mjd=float(H["HIERARCH TNG QC BJD"]) - 2400000.5, rv=archive_num(H.get("HIERARCH TNG QC CCF RV")), rv_ob=None, inst="HARPN", snr=archive_num(H.get("HIERARCH TNG QC ORDER50 SNR"), float("nan")), berv=float(H["HIERARCH TNG QC BERV"]), ra=None, dec=None) inst = str(H.get("INSTRUME", "")).strip() mjd = float(H.get("MJD-OBS", np.nan)) + float(H.get("EXPTIME", 0)) / 172800.0 rv, rv_ob = None, None # the pipeline's velocity where the product carries one; the observing block's target velocity, often a placeholder, kept apart for key in ("HIERARCH ESO QC CCF RV", "HIERARCH ESO DRS CCF RVC", "HIERARCH ESO DRS CCF RV"): if key in H and np.isfinite(float(H[key])): rv = float(H[key]) break ob = archive_num(H.get("HIERARCH ESO TEL TARG RADVEL")) if ob is not None and 0.0 < abs(ob) < 500.0: rv_ob = ob if inst.upper().startswith("SPIROU") or "SPIROU" in str(H.get("INSTRUME", "")).upper() or len(h) > 1 and h[1].name in ("FluxA", "FLUXA"): # the CADC t product: per-order flux (telluric corrected), wavelength (nm, vacuum) and blaze in image extensions ext = {x.name.upper(): x for x in h[1:]} f = np.asarray(ext["FLUXA"].data if "FLUXA" in ext else h[1].data, float) w = np.asarray(ext["WAVEA"].data, float) * 10.0 bl = np.asarray(ext["BLAZEA"].data, float) if "BLAZEA" in ext else np.ones_like(f) with np.errstate(all="ignore"): f = f / bl e = np.sqrt(np.abs(f)) order = np.argsort(w.ravel()) w, f, e = w.ravel()[order], f.ravel()[order], e.ravel()[order] w = archive_vac_to_air(w) # the wavelengths are the observatory's; the barycentric correction and the order 35 signal-to-noise sit in the extensions' headers H1 = h[1].header if len(h) > 1 else {} berv = next((float(x[k]) for x in (H, H1) for k in ("BERV",) if k in x and np.isfinite(float(x[k]))), None) if berv is None: berv = archive_barycentric_correction(float(H["RA_DEG"]), float(H["DEC_DEG"]), mjd, "CFHT") if "RA_DEG" in H else 0.0 w = w * (1.0 + berv / spectra_C) rv = rv if rv is not None else next((float(x[k]) for x in (H, H1) for k in ("CCFRV",) if k in x and np.isfinite(float(x[k]))), None) snr = next((float(x[k]) for x in (H1, H) for k in ("EXTSN035", "SNR35", "SPEMSNR") if k in x and np.isfinite(float(x[k]))), np.nan) return w, f, e, dict(mjd=mjd, rv=rv, inst="SPIRou", snr=snr, berv=berv, ra=archive_num(H.get("RA_DEG")), dec=archive_num(H.get("DEC_DEG"))) t = h[1].data names = {n.upper(): n for n in t.columns.names} wname = names.get("WAVE_AIR") or names.get("WAVE") or t.columns.names[0] w = np.asarray(t[wname][0], float) f = np.asarray(t[names["FLUX"]][0] if "FLUX" in names else t[t.columns.names[1]][0], float) e = np.asarray(t[names["ERR"]][0], float) if "ERR" in names else np.sqrt(np.abs(f)) if not np.any(np.isfinite(e) & (e > 0)): # a product without errors (the older HARPS reductions) takes the photon-counting proxy e = np.sqrt(np.abs(f)) ucd = str(h[1].header.get("TUCD%d" % (t.columns.names.index(wname) + 1), "")) unit = str(h[1].header.get("TUNIT%d" % (t.columns.names.index(wname) + 1), "")).strip().lower() spec = str(H.get("SPECSYS", h[1].header.get("SPECSYS", ""))).upper() berv = None for key in ("HIERARCH ESO QC BERV", "HIERARCH ESO DRS BERV"): if key in H: berv = float(H[key]) break if berv is None: site = "Paranal" if inst.upper() in ("ESPRESSO", "UVES", "CRIRES", "XSHOOTER") else "LaSilla" berv = archive_barycentric_correction(float(H["RA"]), float(H["DEC"]), mjd, site) snr = float(H.get("SNR", np.nan)) ra, dec = archive_num(H.get("RA")), archive_num(H.get("DEC")) if unit == "nm": w = w * 10.0 elif unit in ("um", "micron", "micrometer", "micrometre") or w.max() < 100: w = w * 1e4 if "obs.atmos" not in ucd and wname.upper() != "WAVE_AIR": w = archive_vac_to_air(w) if not spec.startswith("BARY"): w = w * (1.0 + berv / spectra_C) return w, f, e, dict(mjd=mjd, rv=rv, rv_ob=rv_ob, inst=inst, snr=snr, berv=berv, ra=ra, dec=dec) planets_DOC = """Planets in archived radial velocities. The HARPS-RVBank's SERVAL velocities and activity indicators (Trifonov et al. 2020) are joined to every other instrument's public velocities in DACE, and each star's velocities are searched for Keplerians around and beside the planets the NASA Exoplanet Archive lists for it. A signal is then tested across three reductions of the same HARPS spectra (SERVAL's, the HARPS pipeline's in DACE and line-by-line velocities measured here), the star's activity indicators, the two halves of its nights, its other instruments, Gaia's astrometry and its TESS light curves, and its orbit is sampled. bank the bank's star list and velocities from VizieR, and the archive's planets dace DACE's public velocities of the census's stars, each star found by position rvcat the stars of ESO's HARPS radial-velocity catalogue the bank does not hold, with the catalogue's velocities as their bank, as a data root tables the stars of the published HIRES tables the census does not search, with those velocities as their bank, as a data root sophie the stars of the SOPHIE archive, with its pipeline's velocities as their bank, as a data root harpsn the stars of the TNG archive's public HARPS-N spectra, with its pipeline's velocities as their bank, as a data root neid the stars of NEID's archive, with its pipeline's velocities as their bank, as a data root elodie the stars of the ELODIE archive, with its velocities as their bank, as a data root carmenes the stars of CARMENES's first data release, with its two reductions as their bank and second reduction, as a data root peers the root's stars given the other data roots' velocities of them targets the archive's HARPS targets (or another spectrograph's) beyond the census, set up as a data root of their own measure a targets root's stars measured from their spectra: cross-correlation velocities as its bank, line-by-line velocities beside them census a share of the stars searched 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; 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 planets.csv vet signals across reductions, indicators, halves, other instruments and Gaia, of one star or of a list orbits a star's Keplerians sampled tess a star's TESS light curves at its signals' periods: rotation and transits tois TESS's planet candidates weighed with archived velocities at their transit ephemerides validate TESS's planet candidates validated statistically with TRICERATOPS system a planetary system's case: models, aliases, stability, detection limits and figures weigh a long-period companion's true mass from velocities and Hipparcos-Gaia astrometry ledger each new body's predicted orbit tested against observations made after its discovery; failures are rejected at the next followup controls what the decision does to settled candidates and to open ones, read from the root's records with nothing weighed; with --indicators, how often an activity indicator holds power at a known planet's period strict the strict-periodicity test of Hara et al. (2022) on the root's known and new signals and those rejected for activity sparse the census's stars' sinusoids searched one at a time, by RELAX and from the l1 periodogram, scored against the blind census on the archive's planets recovery a range of periods tried before the search is carried over it: confirmed planets found there, what it adds and what noise alone gives window what the search's detrending costs a transit of each length figure each signal past the search's vetting of one star drawn from its light curves dip one lone dip of a star read closely: every light curve of its sector, its neighbours and the orbits' conjunctions companions-read the root's new companions one by one, with Gaia's marks and the catalogues that hold them progress the TESS stage's stars searched by kind of light curve, its rate and the time left epochs-trial the reading of Gaia DR4's epoch astrometry tried on ESA's pre-release""" planets_ROOT = archive_data("planets") planets_RESULTS = archive_results("planets") # HARPS's fibre upgrade of 2015 June, which moved its velocities by an offset of their own (MJD) planets_HARPS_UPGRADE = 57172.5 planets_INDICATORS = ("S", "Halpha", "FWHM", "BIS", "CRX", "dLW") def planets_path(*parts): """Path under the planets data root.""" return os.path.join(planets_ROOT, *parts) # what a root planets_tables set up says of its bank, the spectrograph it comes from, the upgrade that moved its zero point (MJD) and the labels of its two reductions; the HARPS-RVBank's otherwise planets_BANK_INFO = json.load(open(planets_path("bank.json"))) if os.path.exists(planets_path("bank.json")) else {} planets_BANK_FAMILY, planets_UPGRADE = planets_BANK_INFO.get("family", "HARPS"), planets_BANK_INFO.get("upgrade", planets_HARPS_UPGRADE) # the tables a new data root takes from the root it is set up from, each of which it would otherwise fetch or build again planets_SHARED = ("known.csv", "solutions.csv", "toi.csv", "ctoi.csv", "imaging.csv", "exoplanet_eu.csv", "eclipsing_binaries.npy", "eclipsing_candidates.npy", "tess/index.npz", "tess/sectors.json") def planets_share_tables(source, out): """The tables of planets_SHARED and the SIMBAD index taken from the data root SOURCE into the data root OUT where it lacks them, the index by hard links where the disk allows.""" pairs = [(os.path.join(source, "planets", *name.split("/")), os.path.join(out, "planets", *name.split("/"))) for name in planets_SHARED] pairs += [(p, os.path.join(out, "simbad_index", os.path.basename(p))) for p in glob.glob(os.path.join(source, "simbad_index", "*"))] for src, kept in pairs: if os.path.exists(src) and not os.path.exists(kept): os.makedirs(os.path.dirname(kept), exist_ok=True) try: os.link(src, kept) if "simbad_index" in kept else shutil.copyfile(src, kept) except OSError: shutil.copyfile(src, kept) def planets_write(path, rows, keys=None): """ROWS, dicts, written to PATH as CSV with the columns KEYS, by default the first row's.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) keys = keys or (list(rows[0].keys()) if rows else []) with open(path, "w", newline="", encoding="utf-8") as fh: w = csv.DictWriter(fh, fieldnames=keys, extrasaction="ignore") w.writeheader() w.writerows(rows) return path def planets_read(path): """A CSV file's rows as dicts.""" return list(csv.DictReader(open(path, encoding="utf-8"))) def planets_num(x): """Catalogue value as a finite float, else NaN.""" v = archive_num(x) return float("nan") if v is None else v def planets_late_type(sp): """An F, G, K or M star of luminosity class III or fainter.""" sp = (sp or "").strip() return bool(sp) and sp[0] in "FGKM" and not sp.startswith(("Fe", "Ge")) and not any(c in sp for c in ("Ia", "Ib", "Iab", "II/", "II-", " II", "II ")) def planets_mass(sp): """The spectral type's mass (solar masses) behind the minimum masses.""" sp = (sp or "").strip() return 1.5 if any(c in sp for c in ("III", "IV/III")) else {"F": 1.2, "G": 1.0, "K": 0.75, "M": 0.45}.get(sp[:1], 1.0) def planets_star_mass(star): """A star's mass (solar masses): its row's where its root's table gives one (planets_carmenes), else its spectral type's.""" return archive_num(star.get("Mass")) or planets_mass(star.get("SpType")) def planets_kepler(t, P, tp, e, w): """The unit Keplerian velocity curve, cos(nu + w) + e cos w.""" M = 2 * np.pi * (((t - tp) / P) % 1.0) E = M + e * np.sin(M) for _ in range(30): E = E - (E - e * np.sin(E) - M) / (1.0 - e * np.cos(E)) nu = 2 * np.arctan2(np.sqrt(1 + e) * np.sin(E / 2), np.sqrt(1 - e) * np.cos(E / 2)) return np.cos(nu + w) + e * np.cos(w) def planets_least_mass(f, m1): """The companion's mass (solar masses) whose mass function m^3/(m1+m)^2 is F, by bisection over every element of F and M1 at once.""" f, m1 = np.asarray(f, float), np.asarray(m1, float) lo, hi = np.zeros(np.broadcast(f, m1).shape), np.full(np.broadcast(f, m1).shape, 100.0) for _ in range(80): mid = 0.5 * (lo + hi) below = mid ** 3 / (m1 + mid) ** 2 < f lo, hi = np.where(below, mid, lo), np.where(below, hi, mid) out = 0.5 * (lo + hi) return float(out) if out.ndim == 0 else out def planets_msini(P, K, e, m1): """Minimum mass in Jupiter masses of a Keplerian of period P (d), semi-amplitude K (m/s) and eccentricity e about a star of m1 solar masses.""" return planets_least_mass(1.0361e-7 * (1 - e ** 2) ** 1.5 * (K / 1000.0) ** 3 * P, m1) * 1047.57 def planets_bank(): """The bank's star list and velocities from VizieR (J/A+A/636/A74) and the NASA Exoplanet Archive's planets with their hosts' names, positions and proper motions, written under ROOT as bank_stars.csv, bank_velocities.csv and known.csv.""" stars = archive_tap("vizier", 'SELECT "recno", "Nrv", "Name", "RAJ2000", "DEJ2000", "SpType", "Teff", "Bmag", "Vmag", "Gmag", "Dist", "SimbadName" ' 'FROM "J/A+A/636/A74/list"') planets_write(planets_path("bank_stars.csv"), stars) vel = archive_tap("vizier", 'SELECT "Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", ' '"FWHMDRS", "BIS", "SNRDRS" FROM "J/A+A/636/A74/rvbank"') planets_write(planets_path("bank_velocities.csv"), vel) known = archive_exoplanets(planets_KNOWN) planets_write(planets_path("known.csv"), known) print("%d stars, %d velocities, %d catalogued planets" % (len(stars), len(vel), len(known)), flush=True) 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): """The archive's default parameters (known.csv) and every published solution (solutions.csv) in ROOT, fetched again once DAYS old, the old copy kept where the archive does not answer. Returns the solutions.""" for name, query in (("known.csv", planets_KNOWN), ("solutions.csv", planets_SOLUTIONS)): path = planets_path(name) if os.path.exists(path) and time.time() - os.path.getmtime(path) < days * 86400.0: continue try: rows = archive_exoplanets(query) except Exception as exc: if not os.path.exists(path): raise print("the archive did not answer (%s); %s kept" % (str(exc)[:120], name), flush=True) continue tmp = archive_tmp(path) planets_write(tmp, rows) archive_place(tmp, path) return planets_read(planets_path("solutions.csv")) 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: idx.update(by_name.get(archive_simbad_key(n), ())) if math.isfinite(ra) and math.isfinite(dec): # the proper motion carries a position less than 0.1 deg in sixteen years j = order[np.searchsorted(dsorted, dec - 0.1):np.searchsorted(dsorted, dec + 0.1)] cosd = math.cos(math.radians(dec)) 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) < 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 x in planets_exofop()} for r in sig: if r["status"] not in ("new", "candidate", "likely"): 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_false_decide(sig, stars): """The new bodies and candidates of SIG at a star, by SIMBAD's object, and within 5 per cent of a period the California Legacy Survey judged false (ROOT/cls_false_positives.csv, as planets_tables keeps it) rejected, the Survey's cause named in catalogued.""" path = planets_path("cls_false_positives.csv") if not os.path.exists(path): return false = planets_read(path) names = {r["name"]: (stars.get(r["name"], {}).get("SimbadName") or r["name"]).strip() for r in sig if r["status"] in ("new", "candidate")} oids = archive_simbad_oids(sorted(set(names.values()) | {x["SimbadName"] for x in false if x["SimbadName"]})) by = {} for x in false: if x["SimbadName"] in oids: by.setdefault(oids[x["SimbadName"]], []).append(x) for r in sig: if r["status"] in ("new", "candidate"): P = planets_num(r.get("orbit_P") or r["P"]) hit = next((x for x in by.get(oids.get(names[r["name"]]), []) if abs(P / planets_num(x["Per"]) - 1.0) < 0.05), None) if hit: r.update(status="rejected", reason="a published false positive", catalogued="; ".join([y for y in (r.get("catalogued"),) if y] + ["California Legacy Survey false positive, cause %s" % hit["Cause"]])) # each published survey's reading of a signal it tabulates: Butler et al.'s (2017) and the California Legacy Survey's (Rosenthal et al. 2021) planets_SURVEY_READINGS = dict(Published="planet", Candidate="candidate", SRC="candidate", Activity="activity", K="planet", C="candidate", A="activity", R="activity", N="artifact", S="star") def planets_survey_signals(): """The signals the published HIRES surveys tabulate, Butler et al.'s (2017) table 2 and the California Legacy Survey's planets.dat (Rosenthal et al. 2021): each with its survey, star, period, median period where the survey gives one, and reading (planets_SURVEY_READINGS), kept beside the data roots in vizier_index/survey_signals.csv once read, since the catalogues are fixed; an error where no site serves them.""" path = os.path.join(os.path.dirname(archive_DATA), "vizier_index", "survey_signals.csv") if os.path.exists(path): return planets_read(path) butler, cls = archive_vizier_file("J/AJ/153/208/table2.dat"), archive_vizier_file("J/ApJS/255/8/planets.dat") if not butler or not cls: raise IOError("no VizieR site served the published surveys' signals") rows = [dict(survey="Butler et al. 2017", star=x[5:15].strip(), P=float(x[25:35]), P_median="", reading=planets_SURVEY_READINGS[x[60:69].strip()]) for x in butler.splitlines() if x.strip()] for x in cls.splitlines(): if x.strip(): f = x.split("|") cps = f[1].strip().upper() rows.append(dict(survey="California Legacy Survey", star="HD " + cps if cps[0].isdigit() else cps, P=float(f[12]), P_median=float(f[13]), reading=planets_SURVEY_READINGS[f[2].strip()])) os.makedirs(os.path.dirname(path), exist_ok=True) tmp = archive_tmp(path) planets_write(tmp, rows, ["survey", "star", "P", "P_median", "reading"]) archive_place(tmp, path) return planets_read(path) def planets_survey_match(kind, P, signals): """The signal of SIGNALS, a star's rows of planets_survey_signals, that a decided signal of KIND at the period P is, or None: within 5 per cent, a companion within 25 per cent, or within a factor of two of one the survey reads as a star, since a long orbit seen in part binds its period only loosely, on the survey's side as on this one.""" def same(x): for Q in (planets_num(x["P"]), planets_num(x["P_median"])): if kind != "companion": if abs(P / Q - 1.0) < 0.05: return True elif 0.5 < P / Q < 2.0 if x["reading"] == "star" else abs(P / Q - 1.0) < 0.25: return True return False return next((x for x in signals if same(x)), None) def planets_survey_decide(sig, stars): """The new bodies, candidates and likely planets of SIG set against the signals the published surveys tabulate at their stars, by SIMBAD's object (planets_survey_signals, planets_survey_match), the survey named in catalogued. One it reads as activity or an artifact is rejected as a published false positive; any other is known, an independent validation where it is a TESS candidate's.""" rows = [r for r in sig if r["status"] in ("new", "candidate", "likely")] signals = planets_survey_signals() names = {r["name"]: (stars.get(r["name"], {}).get("SimbadName") or r["name"]).strip() for r in rows} forms = {x["star"]: planets_name_forms(x["star"]) + [re.sub(r"(?<=\d)[A-Z]$", "", x["star"])] for x in signals} oids = archive_simbad_oids(sorted(set(names.values()) | {f for fs in forms.values() for f in fs})) by = {} for x in signals: oid = next((oids[f] for f in forms[x["star"]] if f in oids), None) if oid is not None: by.setdefault(oid, []).append(x) for r in rows: hit = planets_survey_match(r["kind"], planets_num(r.get("orbit_P") or r["P"]), by.get(oids.get(names[r["name"]]), [])) if hit: note = "; ".join([y for y in (r.get("catalogued"),) if y] + ["%s, %s at %.4g d" % (hit["survey"], hit["reading"], planets_num(hit["P"]))]) if hit["reading"] in ("activity", "artifact"): r.update(status="rejected", reason="a published false positive", catalogued=note) else: r.update(status="known", reason="catalogued", contribution="independent validation" if r["kind"] == "validated" else "", catalogued=note) 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): parts = str(text or "").strip().split(":") try: value = [float(p) for p in parts] except ValueError: return float("nan") if len(value) == 1: return value[0] return (-1.0 if parts[0].startswith("-") else 1.0) * (abs(value[0]) + value[1] / 60.0 + (value[2] if len(value) > 2 else 0.0) / 3600.0) * scale return angle(x.get("RA"), 15.0), angle(x.get("Dec"), 1.0) def planets_bank_arrays(): """The bank's usable velocities as arrays, read from bank_velocities.csv once and kept beside it in bank_velocities.npz while the table is unchanged: each row's star and its (MJD, velocity, error, S where the table gives it, H alpha, FWHM, bisector, CRX, dLW).""" src, cache = planets_path("bank_velocities.csv"), planets_path("bank_velocities.npz") stamp = "%d %d" % (os.path.getsize(src), int(os.path.getmtime(src))) if os.path.exists(cache): with np.load(cache) as z: if str(z["stamp"]) == stamp: return z["name"], z["rows"] name, rows = [], [] for r in csv.DictReader(open(src, encoding="utf-8")): v, e = planets_num(r["DRVmlcnzp"]), planets_num(r["e_DRVmlcnzp"]) if math.isfinite(v) and math.isfinite(e) and abs(v) < 1e6 and 0 < e < 1e3: name.append(r["Name"]) rows.append([float(r["BJD"]) - 2400000.5, v, e, planets_num(r.get("S")), planets_num(r["Halpha"]), planets_num(r["FWHMDRS"]), planets_num(r["BIS"]), planets_num(r["CRX"]), planets_num(r["dLW"])]) name, rows = np.array(name, dtype=str), np.array(rows, float).reshape(-1, 9) tmp = archive_tmp(cache) with open(tmp, "wb") as fh: np.savez(fh, stamp=stamp, name=name, rows=rows) archive_place(tmp, cache) return name, rows def planets_bank_series(names=None): """The bank's velocities by star, of NAMES alone where given: rows of (MJD, velocity, error, S, H alpha, FWHM, bisector, CRX, dLW), the S index left for DACE to fill.""" name, rows = planets_bank_arrays() keep = np.isin(name, sorted(names)) if names is not None else np.ones(len(name), bool) bank = {} for n, r in zip(name[keep].tolist(), rows[keep].tolist()): bank.setdefault(n, []).append(r) return bank def planets_bank_raw(names): """The bank's rows of the stars NAMES, by star.""" out = {} for r in csv.DictReader(open(planets_path("bank_velocities.csv"), encoding="utf-8")): if r["Name"] in names: out.setdefault(r["Name"], []).append(r) return out def planets_eligible(stars, bank): """The stars the census searches: late types whose bank velocities cover 15 nights or more over 100 days or more.""" out = [] for n, rows in bank.items(): t = np.array([x[0] for x in rows]) if planets_late_type(stars.get(n, {}).get("SpType")) and len(np.unique(np.floor(t + 0.3))) >= 15 and t.max() - t.min() >= 100: out.append(n) return sorted(out) def planets_targets(out, min_nights=15, min_span=100.0, threads=6, inst="HARPS"): """The archive's HARPS targets (or INST's) beyond the census, set up for a census of their own in the data root OUT, its instrument in OUT/planets/measure.json and each target named by SIMBAD's object nearest its J2000 position within 10 arcsec. Every target of ESO's spectra above a signal-to-noise ratio of 20 with MIN_NIGHTS nights or more over MIN_SPAN days or more is kept, targets within 10 arcsec of one another joined under the name with the most nights, and a star the census already searches, recognised by its name or within 3 arcmin of its J2000 position, left out. Each is matched to its Gaia DR3 source, the brightest of G = 3 to 13.5 within 30 arcsec, and its position carried back to J2000 by the source's proper motion; targets sharing a source are joined, and those within 10 arcsec of a census star at J2000 are left out. The source's colour and absolute magnitude give its class (F from BP-RP 0.45, G from 0.78, K from 0.98 and M from 1.85, luminosity class III where M_G is brighter than 2.5), and its G and colour its V (Riello et al. 2021). The targets are written as OUT/planets/bank_stars.csv, with an empty bank_velocities.csv, an empty dace.csv and the archive's planets beside them, so that `planets dace` and `census` run in OUT as they run here.""" q = ("SELECT target_name, AVG(s_ra) AS ra, AVG(s_dec) AS dec, COUNT(DISTINCT FLOOR(t_min + 0.3)) AS nights, MIN(t_min) AS t0, MAX(t_min) AS t1 " "FROM ivoa.ObsCore WHERE instrument_name = '%s' AND dataproduct_type = 'spectrum' AND snr > 20 GROUP BY target_name" % inst) rows = [r for r in archive_tap("eso", q) if int(r["nights"]) >= min_nights and float(r["t1"]) - float(r["t0"]) >= min_span and r["ra"] and r["dec"]] rows.sort(key=lambda r: -int(r["nights"])) print("%d %s targets with %d nights over %d days in the archive" % (len(rows), inst, min_nights, min_span), flush=True) sep = lambda a, b: math.hypot((a[0] - b[0]) * math.cos(math.radians(a[1])), a[1] - b[1]) * 3600.0 stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} eligible = [n for n in planets_eligible(stars, planets_bank_series()) if stars[n].get("RAJ2000")] searched = [(float(stars[n]["RAJ2000"]), float(stars[n]["DEJ2000"])) for n in eligible] norm = lambda s: (lambda x: "GJ" + x[2:] if x.startswith("GL") else x)(re.sub(r"[\s_.\-]", "", str(s or "")).upper()) known = {norm(x) for n in eligible for x in (n, stars[n].get("SimbadName")) if x} kept = [] for r in rows: pos = (float(r["ra"]), float(r["dec"])) # a census star, by name or within 3 arcmin of its J2000 position if norm(r["target_name"]) in known or any(sep(pos, s) < 180.0 for s in searched): continue if not any(sep(pos, k["pos"]) < 10.0 for k in kept): kept.append(dict(name=archive_tag(r["target_name"].strip()), pos=pos, nights=int(r["nights"]), span=float(r["t1"]) - float(r["t0"]))) print("%d beyond the census, names joined; matching each to Gaia DR3" % len(kept), flush=True) def gaia(k): # a cone-only query keeps the archive on its sky index q_ = ("SELECT source_id, ra, dec, pmra, pmdec, phot_g_mean_mag, bp_rp, parallax, ruwe FROM gaiadr3.gaia_source WHERE CONTAINS(POINT('ICRS', ra, dec), " "CIRCLE('ICRS', %.6f, %.6f, %.6f)) = 1" % (k["pos"][0], k["pos"][1], 30.0 / 3600.0)) try: g = [x for x in archive_tap("gaia", q_, timeout=120) if 3.0 < (planets_num(x.get("phot_g_mean_mag")) or 99.0) < 13.5] except Exception: g = [] return k, (min(g, key=lambda x: planets_num(x["phot_g_mean_mag"])) if g else None) out_rows, names, sources = [], set(), set() for k, g in archive_pmap(gaia, kept, threads=threads): G, c, plx, pmra, pmdec = (planets_num(g.get(x)) for x in ("phot_g_mean_mag", "bp_rp", "parallax", "pmra", "pmdec")) if g else (float("nan"),) * 5 if not (math.isfinite(G) and math.isfinite(c)) or g["source_id"] in sources: continue # the Gaia position carried back from 2016.0 to J2000 dec0 = float(g["dec"]) - (pmdec if math.isfinite(pmdec) else 0.0) * 16.0 / 3.6e6 ra0 = float(g["ra"]) - (pmra if math.isfinite(pmra) else 0.0) * 16.0 / 3.6e6 / math.cos(math.radians(dec0)) if any(sep((ra0, dec0), s) < 10.0 for s in searched): continue sources.add(g["source_id"]) cls = "A" if c < 0.45 else "F" if c < 0.78 else "G" if c < 0.98 else "K" if c < 1.85 else "M" giant = math.isfinite(plx) and plx > 0 and G + 5.0 * math.log10(plx / 100.0) < 2.5 name = k["name"] if k["name"] not in names else "%s_%d" % (k["name"], len(names)) names.add(name) out_rows.append(dict(Name=name, SpType=cls + ("III" if giant else "V"), Vmag=round(G - (-0.02704 + 0.01424 * c - 0.2156 * c * c + 0.01426 * c ** 3), 2), RAJ2000=round(ra0, 6), DEJ2000=round(dec0, 6), SimbadName=archive_simbad_near(ra0, dec0) or "", nights=k["nights"], span_d=round(k["span"]), gaia_source_id=g["source_id"], ruwe=g.get("ruwe", ""))) folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) planets_write(os.path.join(folder, "bank_stars.csv"), out_rows, list(out_rows[0].keys())) with open(os.path.join(folder, "bank_velocities.csv"), "w", newline="", encoding="utf-8") as f: f.write(open(planets_path("bank_velocities.csv"), encoding="utf-8").readline()) planets_write(os.path.join(folder, "dace.csv"), [], planets_DACE_KEYS) planets_share_tables(archive_DATA, out) json.dump(dict(inst=inst, min_nights=min_nights, min_span=min_span, stars=len(out_rows)), open(os.path.join(folder, "measure.json"), "w"), separators=(",", ":")) print("%d %s targets with %d nights over %d days; %d after joining names; %d with a Gaia source beyond the census, %d of them F to M" % ( len(rows), inst, min_nights, min_span, len(kept), len(out_rows), sum(1 for r in out_rows if planets_late_type(r["SpType"]))), flush=True) # ESO's catalogue of HARPS pipeline velocities, one row per spectrum (doi:10.18727/archive/33) planets_RVCAT = "https://dataportal.eso.org/dataportal_new/file/ADP.2023-12-04T15:16:53.464" def planets_rvcat(out, min_nights=4): """The stars of ESO's HARPS radial-velocity catalogue (HARPS_RVCAT_2023_DR1) that the HARPS-RVBank does not hold, set up as a data root of their own with the catalogue's pipeline velocities as its bank, so that census, merge, followup and ledger run there as they run here. A spectrum keeps its drift-corrected CCF velocity and error where it is of a star, the velocity is within 1000 km/s, the error lies between 0 and 1 km/s and SIMBAD's object lies within 10 arcsec of the pointing, or as far as its proper motion carries it from J2000 to the observation. Spectra are grouped by SIMBAD's identifier, each star keeping the instrument mode and mask of most of its spectra, named after its most frequent target name, with SIMBAD's spectral type, magnitudes and J2000 position; a star the bank holds, by SIMBAD identifier, name or within 3 arcmin of its position, and one with fewer than MIN_NIGHTS nights are left out. Writes OUT/planets/bank_stars.csv, bank_velocities.csv, an empty dace.csv, the archive's planets and rvcat.json.""" from astropy.io import fits path = planets_path("HARPS_RVCAT_2023_DR1.fits") if not os.path.exists(path): archive_save(path, archive_get(planets_RVCAT, timeout=1800)) d = fits.getdata(path, 1) col = lambda k: np.asarray(d[k]) text = lambda k: np.char.strip(col(k).astype(str)) rv, err, sid = col("drs_ccf_rvc").astype(float), col("drs_dvrms").astype(float), text("main_id_simbad") mjd = col("mjd_obs").astype(float) pm = np.hypot(np.nan_to_num(col("pmra_simbad").astype(float)), np.nan_to_num(col("pmdec_simbad").astype(float))) reach = 10.0 + 1.2 * pm / 1000.0 * np.abs((mjd - 51544.5) / 365.25) ok = (np.char.startswith(np.char.upper(text("dpr_type")), "STAR") & np.isfinite(rv) & (np.abs(rv) < 1000.0) & np.isfinite(err) & (err > 0) & (err < 1000.0) & (sid != "") & (col("angDist_simbad").astype(float) < reach)) norm = lambda s: (lambda x: "GJ" + x[2:] if x.startswith("GL") else x)(re.sub(r"[\s_.\-*]", "", str(s or "")).upper()) bank = planets_read(planets_path("bank_stars.csv")) held = {norm(x) for r in bank for x in (r["Name"], r.get("SimbadName")) if x} bpos = np.array([[planets_num(r["RAJ2000"]), planets_num(r["DEJ2000"])] for r in bank]) mode, mask, obj = text("ins_mode"), text("drs_mask"), text("tel_object") groups = {} for i in np.where(ok)[0]: groups.setdefault(sid[i], []).append(i) stars, vel, names = [], [], set() for s, idx in sorted(groups.items()): idx = np.array(idx) keys = [(mode[i], mask[i]) for i in idx] top = max(set(keys), key=keys.count) idx = idx[[k == top for k in keys]] if len(np.unique(np.floor(mjd[idx] + 0.3))) < min_nights: continue i0 = idx[0] ra, dec = float(d["ra_simbad"][i0]), float(d["dec_simbad"][i0]) sep = np.hypot((bpos[:, 0] - ra) * math.cos(math.radians(dec)), bpos[:, 1] - dec) * 3600.0 targets = [obj[i] for i in idx] name = archive_tag(max(set(targets), key=targets.count).replace(" ", "")) if norm(s) in held or norm(name) in held or np.nanmin(sep) < 180.0: continue name = name if name not in names else "%s_%d" % (name, len(names)) names.add(name) num = lambda k: archive_num(d[k][i0], "") stars.append(dict(recno=len(stars) + 1, Nrv=len(idx), Name=name, RAJ2000=round(ra, 6), DEJ2000=round(dec, 6), SpType=str(d["sp_type_simbad"][i0]).strip(), Teff="", Bmag=num("Bmag_simbad"), Vmag=num("Vmag_simbad"), Gmag="", Dist="", SimbadName=s)) vel += [dict(Name=name, BJD=float(d["drs_bjd"][i]), DRVmlcnzp=round(1000.0 * rv[i], 3), e_DRVmlcnzp=round(float(err[i]), 3), FWHMDRS=float(d["drs_ccf_fwhm"][i]), BIS=float(d["drs_bis_span"][i]), SNRDRS=float(d["drs_snr"][i])) for i in idx] folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) planets_write(os.path.join(folder, "bank_stars.csv"), stars, ["recno", "Nrv", "Name", "RAJ2000", "DEJ2000", "SpType", "Teff", "Bmag", "Vmag", "Gmag", "Dist", "SimbadName"]) planets_write(os.path.join(folder, "bank_velocities.csv"), vel, ["Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", "FWHMDRS", "BIS", "SNRDRS"]) planets_write(os.path.join(folder, "dace.csv"), [], planets_DACE_KEYS) planets_share_tables(archive_DATA, out) json.dump(dict(catalogue="HARPS_RVCAT_2023_DR1", doi="10.18727/archive/33", spectra=int(ok.sum()), stars=len(stars), velocities=len(vel)), open(os.path.join(folder, "rvcat.json"), "w"), separators=(",", ":")) print("%d of %d spectra with a velocity and a SIMBAD object; %d stars the bank does not hold with %d nights or more, %d of them F to M, %d velocities" % ( int(ok.sum()), len(rv), len(stars), min_nights, sum(1 for r in stars if planets_late_type(r["SpType"])), len(vel)), flush=True) # the published velocity tables planets_tables reads, at VizieR's sites: the California Legacy Survey's stars, velocities and false positives (Rosenthal et al. 2021), Butler et al.'s (2017) HIRES stars with those velocities as Tal-Or et al. (2019) corrected them, and the Lick # planet search's stars and velocities (Fischer et al. 2014); the publications' codes name the series planets_TABLES = dict(cls_stars="J/ApJS/255/8/table2", cls="J/ApJS/255/8/table6", cls_false="J/ApJS/255/8/table7", butler_stars="J/AJ/153/208/targets", butler="J/MNRAS/484/L8/table1", lick_stars="J/ApJS/210/5/table1", lick="J/ApJS/210/5/table2") planets_TABLE_CODES = dict(cls="2021ApJS..255....8R", butler="2019MNRAS.484L...8T", lick="2014ApJS..210....5F") # HIRES's detector upgrade of 2004 August (MJD) planets_HIRES_UPGRADE = 53220.0 def planets_simbad_stars(oids): """The position, main identifier, spectral type and magnitudes of SIMBAD's objects OIDS, from the mirror's tables: oid to a dict of ra, dec, main, sp and mags, filter to magnitude.""" import pyarrow as pa import pyarrow.compute as pc basic = archive_simbad_table("basic", ("oid", "ra", "dec", "main_id", "sp_type")) basic = basic.filter(pc.is_in(basic["oid"], value_set=pa.array(sorted(set(oids)), type=basic["oid"].type))) place = {o: dict(ra=a, dec=d, main=m, sp=s, mags={}) for o, a, d, m, s in zip(*(basic[c].to_pylist() for c in ("oid", "ra", "dec", "main_id", "sp_type")))} flux = archive_simbad_table("flux", ("oidref", "filter", "flux")) flux = flux.filter(pc.is_in(flux["oidref"], value_set=pa.array(sorted(place), type=flux["oidref"].type))) for o, f, x in zip(*(flux[c].to_pylist() for c in ("oidref", "filter", "flux"))): place[o]["mags"][f] = x return place def planets_tables(out, min_nights=4): """The stars of the published HIRES tables (planets_TABLES) the census does not search, set up as a data root of their own, so that census, merge, followup and ledger run there as they run here. A star is known by SIMBAD's object of its name; its bank is the California Legacy Survey's HIRES velocities where it holds the star and Tal-Or et al.'s otherwise, each with its S index, before and after HIRES's upgrade of 2004 two series; where the Survey holds it Tal-Or et al.'s velocities are the same spectra's second reduction, and the Survey's APF and Lick velocities, or the Lick search's own, dewar by dewar, its other instruments, written as OUT/planets/dace.csv. Left out are a star the census searches, by SIMBAD's object or within 10 arcsec of its J2000 position, one SIMBAD does not place, and one with fewer than MIN_NIGHTS nights. Writes OUT/planets/bank_stars.csv, bank_velocities.csv, dace.csv, cls_false_positives.csv, the archive's planets and bank.json.""" # each table read once, kept in OUT/planets/tables/, a pause after each os.makedirs(os.path.join(out, "planets", "tables"), exist_ok=True) tables = {} for k, source in planets_TABLES.items(): kept = os.path.join(out, "planets", "tables", k + ".csv") if os.path.exists(kept): tables[k] = planets_read(kept) continue tables[k] = archive_vizier_table(source) tmp = archive_tmp(kept) planets_write(tmp, tables[k], list(tables[k][0])) archive_place(tmp, kept) time.sleep(30) print(", ".join("%s %d rows" % (k, len(v)) for k, v in tables.items()), flush=True) hd = lambda n: "HD %s" % n if n.isdigit() else n lick_names = {r["Name"]: hd(r["Name"]) for r in tables["lick_stars"]} butler_names = {r["Name"]: r["SimbadName"] for r in tables["butler_stars"]} cls_names = {r["CPS"]: r["SimbadName"] for r in tables["cls_stars"]} every = sorted({n for names in (lick_names, butler_names, cls_names) for n in names.values() if n}) oids = archive_simbad_oids(every) bank0 = planets_read(planets_path("bank_stars.csv")) census = [r for r in bank0 if r["Name"] in planets_eligible({x["Name"]: x for x in bank0}, planets_bank_series())] held = set(archive_simbad_oids(sorted({r["SimbadName"] for r in census if r.get("SimbadName")})).values()) cra, cdec = np.array([planets_num(r["RAJ2000"]) for r in census]), np.array([planets_num(r["DEJ2000"]) for r in census]) place = planets_simbad_stars(oids.values()) by = {} of = lambda names, k: oids.get(names.get(k)) for r in tables["cls"]: o = of(cls_names, r["CPS"]) if o and archive_num(r["RVel"]) is not None and archive_num(r["e_RVel"]): by.setdefault(o, {}).setdefault("cls_" + r["Inst"], []).append((float(r["BJD"]), float(r["RVel"]), float(r["e_RVel"]), planets_num(r.get("SVal")))) for r in tables["butler"]: o = of(butler_names, r["Name"]) if o and archive_num(r["RVcor"]) is not None and archive_num(r["e_RVcor"]): by.setdefault(o, {}).setdefault("butler", []).append((float(r["BJD"]), float(r["RVcor"]), float(r["e_RVcor"]), planets_num(r.get("S")))) for r in tables["lick"]: o = of(lick_names, r["Name"]) if o and archive_num(r["RVel"]) is not None and archive_num(r["e_RVel"]): by.setdefault(o, {}).setdefault("lick_%s" % r["CCD"], []).append((float(r["JD"]) + 2400000.0, float(r["RVel"]), float(r["e_RVel"]), float("nan"))) star_rows, vel, dace, names, left = [], [], [], set(), dict(census=0, place=0, nights=0, no_hires=0) mjd = lambda x: x - 2400000.5 for o, sets in sorted(by.items()): p = place.get(o) if o in held: left["census"] += 1 continue if not p or p["ra"] is None or p["dec"] is None: left["place"] += 1 continue ra, dec = float(p["ra"]), float(p["dec"]) if len(cra) and np.nanmin(np.hypot(((cra - ra + 180.0) % 360.0 - 180.0) * math.cos(math.radians(dec)), cdec - dec)) * 3600.0 < 10.0: left["census"] += 1 continue cps = sets.get("cls_j", []) + sets.get("cls_k", []) bank = sorted(cps or sets.get("butler", [])) if not bank: left["no_hires"] += 1 continue if len({math.floor(mjd(x[0]) + 0.3) for x in bank}) < min_nights: left["nights"] += 1 continue name = archive_tag(re.sub(r"^[*\s]+", "", " ".join(str(p["main"]).split())).replace(" ", "")) name = name if name not in names else "%s_%d" % (name, len(names)) names.add(name) vmag, bmag = archive_num(p["mags"].get("V"), ""), archive_num(p["mags"].get("B"), "") star_rows.append(dict(recno=len(star_rows) + 1, Nrv=len(bank), Name=name, RAJ2000=round(ra, 6), DEJ2000=round(dec, 6), SpType=str(p["sp"] or "").strip(), Teff="", Bmag=bmag, Vmag=vmag, Gmag="", Dist="", SimbadName=str(p["main"]).strip())) vel += [dict(Name=name, BJD=x[0], DRVmlcnzp=x[1], e_DRVmlcnzp=x[2], S=x[3] if math.isfinite(x[3]) else "") for x in bank] row = lambda inst, code, x: dict(name=name, dace_name=name, inst=inst, drs=code, mode="", mjd=mjd(x[0]), rv=x[1], rv_err=x[2], qc="", smw=x[3] if math.isfinite(x[3]) else "", halpha="", fwhm="", bis="", sn50="") if cps: dace += [row("HIRES-PRE04" if mjd(x[0]) < planets_HIRES_UPGRADE else "HIRES-POST04", planets_TABLE_CODES["butler"], x) for x in sets.get("butler", [])] dace += [row("APF", planets_TABLE_CODES["cls"], x) for x in sets.get("cls_apf", [])] if sets.get("cls_lick"): dace += [row("LICK", planets_TABLE_CODES["cls"], x) for x in sets["cls_lick"]] else: dace += [row("LICK%s" % k[5:], planets_TABLE_CODES["lick"], x) for k, xs in sets.items() if k.startswith("lick_") for x in xs] folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) planets_write(os.path.join(folder, "bank_stars.csv"), star_rows, ["recno", "Nrv", "Name", "RAJ2000", "DEJ2000", "SpType", "Teff", "Bmag", "Vmag", "Gmag", "Dist", "SimbadName"]) planets_write(os.path.join(folder, "bank_velocities.csv"), vel, ["Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", "FWHMDRS", "BIS", "SNRDRS", "S"]) planets_write(os.path.join(folder, "dace.csv"), dace, planets_DACE_KEYS) planets_write(os.path.join(folder, "cls_false_positives.csv"), tables["cls_false"]) planets_share_tables(archive_DATA, out) json.dump(dict(family="HIRES", upgrade=planets_HIRES_UPGRADE, label="HIRES, first reduction", second_label="HIRES, second reduction", catalogues=planets_TABLE_CODES), open(os.path.join(folder, "bank.json"), "w"), separators=(",", ":")) late = sum(1 for r in star_rows if planets_late_type(r["SpType"])) print("%d stars, %d of them F to M, %d bank velocities, %d of other series; left out: %s" % (len(star_rows), late, len(vel), len(dace), left), flush=True) # the SOPHIE archive at Haute-Provence: its tables' query, the one-dimensional spectrum of a sequence, and the date (MJD) of the fibre change of 2011 that moved its zero point (Perruchot et al. 2011) planets_SOPHIE, planets_SOPHIE_FILE, planets_SOPHIE_UPGRADE = "http://atlas.obs-hp.fr/sophie/sophie.cgi?", "c=i&a=mime:application/fits&o=sophie:[s1d,%s]", 55730.0 # HARPS-N's change of detector of 2012 September, which moved its zero point (MJD) planets_HARPSN_UPGRADE = 56197.0 # NEID's archive at the NASA Exoplanet Science Institute, and the date (MJD) of its return to the sky after the fire of 2022, a series on either side planets_NEID_TAP, planets_NEID_UPGRADE = "https://neid.ipac.caltech.edu/TAP/sync", 59880.0 def planets_zero_curve(keys, t, v, e, width=90.0, least=8): """The slow drift of a spectrograph's zero point from its quieter stars: each series of KEYS's velocities V (m/s) at times T with errors E taken about its own weighted mean, the series of ten velocities or more whose robust scatter lies in the lower half of those, and in each bin of WIDTH days the median over those series of their mean there, where LEAST series have one; three passes, each series' mean taken after the last pass's curve. Returns the bins' times and the curve about its median, read between them by linear interpolation; a bin's median of whole series leaves no one star's own signal in it.""" ids = np.unique(keys, return_inverse=True)[1] w = 1.0 / (np.asarray(e, float) ** 2 + 4.0) bins = np.floor((t - t.min()) / width).astype(int) order = np.argsort(ids, kind="stable") starts = np.searchsorted(ids[order], np.arange(int(ids.max()) + 1)) groups = np.split(order, starts[1:]) at, curve = np.array([t.min(), t.max()]), np.zeros(2) for _ in range(3): z = np.interp(t, at, curve) means = np.bincount(ids, w * (v - z)) / np.bincount(ids, w) r = v - z - means[ids] scatter = np.array([1.4826 * np.median(np.abs(r[g] - np.median(r[g]))) if len(g) >= 10 else np.inf for g in groups]) quiet = scatter <= np.median(scatter[np.isfinite(scatter)]) use = quiet[ids] pairs = bins[use].astype(np.int64) * (int(ids.max()) + 1) + ids[use] keys_, inv = np.unique(pairs, return_inverse=True) star_mean = np.bincount(inv, (w * (v - means[ids]))[use]) / np.bincount(inv, w[use]) star_bin = keys_ // (int(ids.max()) + 1) have = [(b, float(np.median(star_mean[star_bin == b]))) for b in np.unique(star_bin) if (star_bin == b).sum() >= least] at = t.min() + (np.array([b for b, _ in have]) + 0.5) * width curve = np.array([x for _, x in have]) curve = curve - np.median(curve) return at, curve def planets_name_forms(name): """The forms in which SIMBAD may know a star an observing archive names NAME: as it stands with the catalogue number's leading zeros gone, and written as the survey it comes from writes it.""" n = re.sub(r"^(HD|HIP|GJ|GL|HR|TYC)0+(?=\d)", r"\1", name.strip()) x = re.sub(r"[\s_-]", "", n).upper() forms = [n] for pattern, form in ((r"^TOI0*(\d+)$", "TOI-%s"), (r"^K0*(\d+)$", "KOI-%s"), (r"^KOI0*(\d+)$", "KOI-%s"), (r"^EP(\d+)$", "EPIC %s"), (r"^EPIC(\d+)$", "EPIC %s"), (r"^KIC(\d+)$", "KIC %s"), (r"^GL(\d+.*)$", "GJ %s"), (r"^GJ(\d+.*)$", "GJ %s"), (r"^WASP(\d+)$", "WASP-%s"), (r"^KEPLER(\d+)$", "Kepler-%s"), (r"^HATP(\d+)$", "HAT-P-%s"), (r"^XO(\d+)$", "XO-%s"), (r"^TRES(\d+)$", "TrES-%s"), (r"^KELT(\d+)$", "KELT-%s"), (r"^QATAR(\d+)$", "Qatar-%s"), (r"^COROT(\d+)$", "CoRoT-%s"), (r"^K2(\d+)$", "K2-%s")): m = re.match(pattern, x) if m: forms.append(form % m.group(1)) return forms def planets_archive_root(out, rows, family, label, spectra, upgrade, min_nights, code): """A spectrograph's whole archive set up as a data root of its own, so that census, merge, followup and ledger run there as they run here: ROWS, a dict for each science velocity with its object's name, position (J2000, degrees), mask, mode ("main", "second" for the same spectra's other reduction, or another, a mode of its own being another instrument's), time (MJD), velocity and error (m/s), width, bisector, signal-to-noise and the identifier of its spectrum. A star is known to SIMBAD by the archive's name for it (planets_name_forms) where that object lies within five arcminutes of the archive's position, or else as the brightest of its objects within 10 arcsec of that position, names of one object joined. Its bank is its velocities in the main mode under the mask most of them share, on either side of the date UPGRADE that moved the zero point, less the slow drift of the zero point its quieter stars show (planets_zero_curve). A second reduction, less its own drift, is written as OUT/planets/dace.csv; where the archive holds none, one comes from the star's own one-dimensional spectra, listed in OUT/planets/spectra.csv, measured when a signal or a companion wants it (planets_lbl, planets_reduce, planets_companion). Left out are a star SIMBAD does not place and one with fewer than MIN_NIGHTS nights. Writes OUT/planets/bank_stars.csv, bank_velocities.csv, dace.csv, spectra.csv, zero_points.csv, the archive's planets and bank.json.""" objects = sorted({r["objname"] for r in rows}) first = {} for r in rows: first.setdefault(r["objname"], r) forms = {n: planets_name_forms(n) for n in objects} oids = archive_simbad_oids(sorted({f for fs in forms.values() for f in fs})) place = planets_simbad_stars(oids.values()) def agrees(n, o): # a name holds where its object lies within five arcminutes of the archive's position, which a programme's own label for a star need not p, x = place.get(o), first[n] if not p or p["ra"] is None or p["dec"] is None: return False sep = math.hypot(((float(p["ra"]) - x["ra"] + 180.0) % 360.0 - 180.0) * math.cos(math.radians(float(p["dec"]))), float(p["dec"]) - x["dec"]) * 3600.0 return not sep >= 300.0 oid_of = {n: next((oids[f] for f in forms[n] if f in oids and agrees(n, oids[f])), None) for n in objects} unplaced = [n for n in objects if oid_of[n] is None] near = archive_simbad_within([(first[n]["ra"], first[n]["dec"]) for n in unplaced]) place.update(planets_simbad_stars([o for x in near for o in x])) for n, candidates in zip(unplaced, near): known = [o for o in candidates if o in place] # the star the spectrograph pointed at, the brightest object there, the nearest where SIMBAD gives none a magnitude lit = [o for o in known if archive_num(place[o]["mags"].get("V")) is not None] oid_of[n] = min(lit, key=lambda o: place[o]["mags"]["V"]) if lit else known[0] if known else None by = {} for r in rows: if oid_of[r["objname"]] is not None: by.setdefault(oid_of[r["objname"]], []).append(r) left = dict(place=sum(1 for n in objects if oid_of[n] is None), nights=0) commonest = lambda xs: [x for x in xs if x["mask"] == max(set(y["mask"] for y in xs), key=[y["mask"] for y in xs].count)] bank, other, second = {}, {}, {} for o, xs in by.items(): bank[o] = sorted(commonest([x for x in xs if x["mode"] == "main"]), key=lambda x: x["mjd"]) if any(x["mode"] == "main" for x in xs) else [] second[o] = sorted(commonest([x for x in xs if x["mode"] == "second"]), key=lambda x: x["mjd"]) if any(x["mode"] == "second" for x in xs) else [] other[o] = sorted(commonest([x for x in xs if x["mode"] not in ("main", "second")]), key=lambda x: x["mjd"]) if any(x["mode"] not in ("main", "second") for x in xs) else [] keep = [o for o in bank if place[o]["ra"] is not None and place[o]["dec"] is not None and len({math.floor(x["mjd"] + 0.3) for x in bank[o]}) >= min_nights] left["nights"] = len(bank) - len(keep) series = np.array([2 * o + (x["mjd"] >= upgrade) for o in keep for x in bank[o]], np.int64) tt, vv, ee = (np.array([x[k] for o in keep for x in bank[o]], float) for k in ("mjd", "v", "e")) at, curve = planets_zero_curve(series, tt, vv, ee) at2, curve2 = None, None if any(second[o] for o in keep): at2, curve2 = planets_zero_curve(np.array([2 * o + (x["mjd"] >= upgrade) for o in keep for x in second[o]], np.int64), *(np.array([x[k] for o in keep for x in second[o]], float) for k in ("mjd", "v", "e"))) star_rows, vel, dace, listed, names = [], [], [], [], set() for o in keep: p = place[o] counts = {} for x in bank[o]: counts[x["objname"]] = counts.get(x["objname"], 0) + 1 top = max(counts, key=counts.get) name = archive_tag(planets_name_forms(top)[0].replace(" ", "")) name = name if name not in names else "%s_%d" % (name, len(names)) names.add(name) star_rows.append(dict(recno=len(star_rows) + 1, Nrv=len(bank[o]), Name=name, RAJ2000=round(float(p["ra"]), 6), DEJ2000=round(float(p["dec"]), 6), SpType=str(p["sp"] or "").strip(), Teff="", Bmag=archive_num(p["mags"].get("B"), ""), Vmag=archive_num(p["mags"].get("V"), ""), Gmag=archive_num(p["mags"].get("G"), ""), Dist="", SimbadName=str(p["main"]).strip())) vel += [dict(Name=name, BJD=x["mjd"] + 2400000.5, DRVmlcnzp=round(x["v"] - float(np.interp(x["mjd"], at, curve)), 3), e_DRVmlcnzp=round(x["e"], 3), FWHMDRS=x["fwhm"], BIS=x["span"], SNRDRS=x["snr"]) for x in bank[o]] listed += [dict(name=name, seq=x["id"], mjd=round(x["mjd"], 5), snr=x["snr"]) for x in bank[o]] dace += [dict(name=name, dace_name=name, inst="%s-%s" % (family, x["mode"]), drs="CCF", mode="", mjd=x["mjd"], rv=x["v"], rv_err=x["e"], qc="", smw="", halpha="", fwhm=x["fwhm"], bis=x["span"], sn50=x["snr"]) for x in other[o]] dace += [dict(name=name, dace_name=name, inst=family, drs=code, mode="", mjd=x["mjd"], rv=round(x["v"] - float(np.interp(x["mjd"], at2, curve2)), 3), rv_err=round(x["e"], 3), qc="", smw="", halpha="", fwhm=x["fwhm"], bis=x["span"], sn50=x["snr"]) for x in second[o]] folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) planets_write(os.path.join(folder, "bank_stars.csv"), star_rows, ["recno", "Nrv", "Name", "RAJ2000", "DEJ2000", "SpType", "Teff", "Bmag", "Vmag", "Gmag", "Dist", "SimbadName"]) planets_write(os.path.join(folder, "bank_velocities.csv"), vel, ["Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", "FWHMDRS", "BIS", "SNRDRS", "S"]) planets_write(os.path.join(folder, "dace.csv"), dace, planets_DACE_KEYS) planets_write(os.path.join(folder, "spectra.csv"), listed, ["name", "seq", "mjd", "snr"]) planets_write(os.path.join(folder, "zero_points.csv"), [dict(mjd=round(float(a_), 2), zero=round(float(c), 3)) for a_, c in zip(at, curve)], ["mjd", "zero"]) planets_share_tables(archive_DATA, out) json.dump(dict(family=family, upgrade=upgrade, label=label, second_label=family + ", second reduction", spectra=spectra, catalogues={family: code}), open(os.path.join(folder, "bank.json"), "w"), separators=(",", ":")) print("%d stars, %d of them F to M, %d bank velocities, %d of its other mode, the zero point's %d bins from %+.1f to %+.1f m/s; left out: %s" % (len(star_rows), sum(1 for r in star_rows if planets_late_type(r["SpType"])), len(vel), len(dace), len(at), curve.min(), curve.max(), left), flush=True) def planets_sophie(out, min_nights=4): """The stars of the SOPHIE archive (planets_SOPHIE) set up as a data root (planets_archive_root): the pipeline's cross-correlation velocities of its science spectra with realistic errors below 50 m/s, the high-resolution mode its main one, the high-efficiency mode's velocities another instrument's, across the fibre change of 2011.""" from astropy.coordinates import SkyCoord def table(ask): lines = archive_get(planets_SOPHIE + ask + "&a=csv%5B%2C%5D", timeout=900).decode("latin-1", "replace").splitlines() return list(csv.DictReader(io.StringIO("\n".join(x for x in lines if x and not x.startswith("#"))))) mode = {r["seq"]: r["mode"] for r in table("n=sophie&d=seq,mode")} raw = sorted(table("n=sophiescc&d=seq,objname,mask,ccf_offline,rv,fwhm,err,span,obstype,sn26,bjd,ra,dec"), key=lambda x: x["ccf_offline"]) # the archive's positions are B1950's ra, dec = np.array([planets_num(r["ra"]) for r in raw]), np.array([planets_num(r["dec"]) for r in raw]) good = np.isfinite(ra) & np.isfinite(dec) icrs = SkyCoord(ra[good], dec[good], unit="deg", frame="fk4").icrs ra[good], dec[good] = icrs.ra.deg, icrs.dec.deg rows, seen = [], set() # the online reduction of a sequence and mask ahead of an offline one for r, a_, d_ in zip(raw, ra.tolist(), dec.tolist()): t, v, e = (planets_num(r[k]) for k in ("bjd", "rv", "err")) m = mode.get(r["seq"]) if r["obstype"] == "SCI" and m in ("HR", "HE") and math.isfinite(t) and math.isfinite(v) and 0 < e < 0.05 and (r["seq"], r["mask"]) not in seen: seen.add((r["seq"], r["mask"])) rows.append(dict(objname=r["objname"], ra=a_, dec=d_, mask=r["mask"], mode="main" if m == "HR" else m, mjd=t - 2400000.5, v=1000.0 * v, e=1000.0 * e, fwhm=r["fwhm"], span=r["span"], snr=r["sn26"], id=r["seq"])) print("%d velocities of the science spectra" % len(rows), flush=True) planets_archive_root(out, rows, "SOPHIE", "SOPHIE, pipeline", "SOPHIE", planets_SOPHIE_UPGRADE, min_nights, "SOPHIE archive") # the TNG archive's table service and files, and the keys of the two reductions' headers: the newer's cross-correlation product and the older's bisector product, each's time, velocity, error, line width, bisector span, signal-to-noise and mask planets_TNG_TAP, planets_TNG_FILES = "http://archives.ia2.inaf.it/vo/tap/tng/", "http://archives.ia2.inaf.it/files/tng/" planets_TNG_READ = dict(new=("QC BJD", "QC CCF RV", "QC CCF RV ERROR", "QC CCF FWHM", "QC CCF BIS SPAN", "QC ORDER50 SNR", "QC CCF MASK"), old=("DRS BJD", "DRS CCF RVC", "DRS CCF NOISE", "DRS CCF FWHM", "DRS BIS SPAN", "DRS SPE EXT SN50", "DRS CCF MASK")) def planets_tng_listing(): """The TNG archive's public HARPS-N science products that hold each exposure's velocity in either reduction, the solar programme's left out, from its table service by an asynchronous job: a row for each with its file, object, place and date.""" ask = urllib.parse.urlencode(dict(REQUEST="doQuery", LANG="ADQL", FORMAT="csv", MAXREC=5000000, PHASE="RUN", QUERY="SELECT EXP_ID, OBJECT, RA, DEC, DATE_OBS FROM tng.TNG_TAP WHERE INSTRUMENT = 'HARPN' AND OBS_MODE = 'SCIENCE' AND policy = 'FREE' AND PROGRAM <> 'SOLAR' AND (EXP_ID LIKE 'r.HARPN.%CCF_A.fits.gz' OR EXP_ID LIKE 'HARPN.%bis%_A.fits.gz')")).encode() job = urllib.request.urlopen(urllib.request.Request(planets_TNG_TAP + "async", data=ask, headers=archive_UA), timeout=300).geturl() for _ in range(360): phase = archive_get(job + "/phase", timeout=60).decode().strip() if phase in ("COMPLETED", "ERROR", "ABORTED"): break time.sleep(10) if phase != "COMPLETED": raise IOError("the TNG archive's job ended %s" % phase) rows = csv.DictReader(io.StringIO(archive_get(job + "/results/result", timeout=1800).decode("utf-8", "replace"))) return [r for r in rows if r["EXP_ID"].endswith("_CCF_A.fits.gz") and r["EXP_ID"].startswith("r.") or "_bis_" in r["EXP_ID"]] def planets_harpsn(out, min_nights=4, threads=6): """The stars of the TNG archive's public HARPS-N spectra set up as a data root (planets_archive_root): each exposure's pipeline velocity in the archive's two reductions, the newer's its bank and the older's, corrected for its drift, its second reduction, each with its error, line width, bisector and signal-to-noise, read from its product's header and kept in OUT/planets/harpsn_products.csv as they arrive, so that a setup cut short goes on where it stopped; the newer's spectra measured line by line where a signal wants a third.""" from astropy.io import fits folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) kept = os.path.join(folder, "harpsn_products.csv") keys = ["file", "object", "ra", "dec", "kind", "bjd", "rv", "err", "fwhm", "span", "snr", "mask", "check"] done = {r["file"] for r in planets_read(kept)} if os.path.exists(kept) else set() listing = planets_tng_listing() print("%d public products, %d already read" % (len(listing), len(done)), flush=True) lock = threading.Lock() if not done: planets_write(kept, [], keys) fh = open(kept, "a", newline="", encoding="utf-8") writer = csv.DictWriter(fh, fieldnames=keys) def angle(text, scale): parts = (text or "").split(":") return (-1.0 if parts[0].strip().startswith("-") else 1.0) * scale * sum(abs(planets_num(p)) / 60.0 ** i for i, p in enumerate(parts)) def read(r): kind = "new" if r["EXP_ID"].startswith("r.") else "old" raw = archive_get(planets_TNG_FILES + r["EXP_ID"], timeout=300, retries=2, soft=True) if not raw: return try: H = fits.getheader(io.BytesIO(gzip.decompress(raw))) except (OSError, ValueError, EOFError, zlib.error): return row = dict(zip(("bjd", "rv", "err", "fwhm", "span", "snr", "mask"), (H.get("HIERARCH TNG " + k, "") for k in planets_TNG_READ[kind]))) row.update(file=r["EXP_ID"], object=r["OBJECT"].strip(), ra=round(angle(r["RA"], 15.0), 6), dec=round(angle(r["DEC"], 1.0), 6), kind=kind, check=H.get("HIERARCH TNG QC SCIRED CHECK", "")) with lock: writer.writerow(row) fh.flush() todo = [r for r in listing if r["EXP_ID"] not in done] for i in range(0, len(todo), 500): if planets_search_ends(): sys.exit(3) archive_pmap(read, todo[i:i + 500], threads) print("%d of %d read" % (min(i + 500, len(todo)), len(todo)), flush=True) fh.close() rows = [] for r in planets_read(kept): t, v, e = planets_num(r["bjd"]), planets_num(r["rv"]), planets_num(r["err"]) if math.isfinite(t) and math.isfinite(v) and 0 < e < 0.05 and r["check"] != "0" and r["object"].upper() not in ("SUN", "NONE", ""): rows.append(dict(objname=r["object"], ra=planets_num(r["ra"]), dec=planets_num(r["dec"]), mask=r["mask"], mode="main" if r["kind"] == "new" else "second", mjd=t - 2400000.5, v=1000.0 * v, e=1000.0 * e, fwhm=r["fwhm"], span=r["span"], snr=r["snr"], id=r["file"].split("_CCF_")[0])) print("%d velocities of the science spectra" % len(rows), flush=True) planets_archive_root(out, rows, "HARPS-N", "HARPS-N, newer pipeline", "HARPN", planets_HARPSN_UPGRADE, min_nights, "TNG archive") # ELODIE's table of its cross-correlations at Haute-Provence, the floors (m/s) of its velocities with simultaneous thorium and without, and the masks it publishes for all planets_ELODIE, planets_ELODIE_FLOOR, planets_ELODIE_MASKS = "http://atlas.obs-hp.fr/elodie/fE.cgi?n=e501&a=csv%5B%2C%5D", dict(main=7.0, OBJ=30.0), ("R37000K0", "R37000F0") def planets_elodie(out, min_nights=4): """The stars of the ELODIE archive (planets_ELODIE) set up as a data root (planets_archive_root): the velocities of its object fibre's cross-correlations above a signal-to-noise of 20, already barycentric, those with simultaneous thorium its main ones and the others another instrument's, each with Queloz's (1995) error, 0.04 km/s times the root of the correlation's width over its contrast and the signal-to-noise, joined to the mode's floor (planets_ELODIE_FLOOR). The table gives each exposure's night alone, taken at its middle at Haute-Provence, a tenth of a day or two from its time, as the orbits of days and more allow. A second reduction comes from the other roots' velocities of its stars (planets_peers).""" text = archive_get(planets_ELODIE, timeout=900).decode("latin-1", "replace") rows = [] for f in csv.reader(io.StringIO("\n".join(x for x in text.splitlines() if x and x[0] not in "#$"))): if len(f) < 17 or f[-11].strip() != "obj" or f[-10].strip() not in planets_ELODIE_MASKS: continue sn, v, width, contrast = (planets_num(x) for x in (f[-7], f[-6], f[-5], f[-4])) place = re.fullmatch(r"J(\d\d)(\d\d)(\d\d\.\d)([+-])(\d\d)(\d\d)(\d\d)", f[-16].strip()) if not (sn >= 20.0 and abs(v) > 0.0 and width > 0.0 and contrast > 0.02 and place): continue mode = "main" if f[-9].strip().startswith("OBTH") else "OBJ" night = datetime.datetime.strptime(f[-13].strip(), "%Y%m%d") - datetime.datetime(1858, 11, 17) h, m, s, sign, dd, dm, ds = place.groups() rows.append(dict(objname=",".join(f[:-16]).strip(), ra=15.0 * (int(h) + int(m) / 60.0 + float(s) / 3600.0), dec=(-1.0 if sign == "-" else 1.0) * (int(dd) + int(dm) / 60.0 + int(ds) / 3600.0), mask=f[-10].strip(), mode=mode, mjd=night.days + 0.98, v=1000.0 * v, e=math.hypot(planets_ELODIE_FLOOR[mode], 40.0 * math.sqrt(width) / (sn * contrast)), fwhm=width, span="", snr=sn, id="%s/%s" % (f[-13].strip(), f[-12].strip()))) print("%d velocities of the object fibre" % len(rows), flush=True) planets_archive_root(out, rows, "ELODIE", "ELODIE, pipeline", None, 99999.0, min_nights, "ELODIE archive") def planets_neid(out, min_nights=4): """The stars of NEID's archive set up as a data root (planets_archive_root): the pipeline's velocities of its science spectra past their proprietary months, neither flagged nor rejected by the archive, with errors below 50 m/s, at the flux-weighted mean time of each exposure, the high-resolution mode its main one and the high-efficiency mode's velocities another instrument's, on either side of the fire of 2022. The archive's table holds one reduction, so that a second comes from the other roots' velocities of its stars (planets_peers) or from their HARPS spectra measured line by line (planets_reduce).""" rows, today = [], time.time() / 86400.0 + 40587.0 for r in archive_tap(planets_NEID_TAP, "SELECT object, qrad, qdecd, obsmode, obstype, flagged, rejected, ccflines, obsmjd, ccfjdsum, ccfrvmod, dvrms, extsnr, l2propint, l2filename FROM neidl2", method="POST"): t, v, e, mid = planets_num(r["obsmjd"]), planets_num(r["ccfrvmod"]), planets_num(r["dvrms"]), planets_num(r["ccfjdsum"]) - 2400000.5 if r["obstype"].strip() == "Sci" and r["flagged"].strip() == "0" and r["rejected"].strip() == "0" and planets_num(r["ccflines"]) > 0 and math.isfinite(v) and 0 < e < 0.05 and t + 30.44 * planets_num(r["l2propint"]) <= today: rows.append(dict(objname=r["object"].strip(), ra=planets_num(r["qrad"]), dec=planets_num(r["qdecd"]), mask="", mode="main" if r["obsmode"].strip() == "hr" else r["obsmode"].strip().upper(), mjd=mid if abs(mid - t) < 1.0 else t, v=1000.0 * v, e=1000.0 * e, fwhm="", span="", snr=r["extsnr"], id=r["l2filename"].strip())) print("%d velocities of the science spectra" % len(rows), flush=True) planets_archive_root(out, rows, "NEID", "NEID, pipeline", None, planets_NEID_UPGRADE, min_nights, "NEID archive") # CARMENES's first data release (Ribas et al. 2023): its stars at VizieR's sites, each star's velocities and the nightly zero points at the project's archive, and the publication's code, which names the series planets_CARMENES_STARS, planets_CARMENES_FILES, planets_CARMENES_CODE = "J/A+A/670/A139/table1", "https://carmenes.cab.inta-csic.es/gto/getDR1DataPublic.action?id=", "2023A&A...670A.139R" def planets_carmenes(out, min_nights=4, threads=4): """The stars of CARMENES's first data release (planets_CARMENES_STARS) set up as a data root of their own, so that census, merge, followup and ledger run there as they run here. A star is known to SIMBAD by its Karmn identifier or its name. Its velocities are those of the spectra the release leaves unflagged: SERVAL's less each night's zero point as its bank and first reduction, and RACCOON's cross-correlation velocities less the same zero point as its second reduction, written as OUT/planets/dace.csv, with RACCOON's line width and bisector, SERVAL's chromatic index and line width, H alpha, sodium, and the mean of the three Ca II infrared lines' indices in the S index's place. The release's mass, radius, temperature and rotation period of each star are kept in its row. A star the census also searches stays, since these are other spectra. Left out are one SIMBAD does not place and one with fewer than MIN_NIGHTS nights. Writes OUT/planets/bank_stars.csv, bank_velocities.csv, dace.csv, the archive's planets and bank.json.""" raw = archive_get(planets_VIZIER_SITES[0] + "/ftp/cats/" + planets_CARMENES_STARS.rpartition("/")[0] + "/table1.dat", timeout=120, retries=2, soft=True) table = [dict(Karmn=x[:11].strip(), Name=x[12:36].strip(), NAVC=x[37:40].strip(), Mass=x[45:51].strip(), Rad=x[59:65].strip(), Teff=x[73:77].strip(), Prot=x[82:88].strip()) for x in raw.decode("latin-1").splitlines() if x.strip()] if raw else archive_vizier_table(planets_CARMENES_STARS) zero = {} for line in archive_get(planets_CARMENES_FILES + "carmenes.dr1.nzp.csv", timeout=300).decode("ascii", "replace").splitlines()[1:]: cells = line.split(",") if len(cells) >= 2 and math.isfinite(planets_num(cells[0])) and math.isfinite(planets_num(cells[1])): zero[int(float(cells[0]))] = float(cells[1]) said = lambda r: ("Karmn %s" % r["Karmn"], " ".join(r["Name"].split())) oids = archive_simbad_oids(sorted({n for r in table for n in said(r)})) place = planets_simbad_stars([oids[n] for r in table for n in said(r) if n in oids]) def fetch(r): raw = archive_get(planets_CARMENES_FILES + urllib.parse.quote(r["Karmn"] + "_SERVAL+RACOON.csv"), timeout=300, soft=True) return r, raw.decode("utf-8", "replace") if raw and raw[:4] == b"BJD," else None star_rows, vel, dace, names, left = [], [], [], set(), dict(no_velocities=0, place=0, nights=0) for r, text in archive_pmap(fetch, table, threads): if text is None: left["no_velocities"] += 1 continue p = next((place[oids[n]] for n in said(r) if oids.get(n) in place and place[oids[n]]["ra"] is not None and place[oids[n]]["dec"] is not None), None) if not p: left["place"] += 1 continue name = archive_tag(said(r)[1].replace(" ", "")) name = name if name not in names else "%s_%d" % (name, len(names)) first, second = [], [] for x in csv.DictReader(io.StringIO(text)): num = lambda k: planets_num(x.get(k)) t = num("BJD") if num("FLAG") != 0.0 or not math.isfinite(t): continue ca = [y for y in (num("CAIRT1"), num("CAIRT2"), num("CAIRT3")) if math.isfinite(y)] S = sum(ca) / len(ca) if ca else "" if math.isfinite(num("AVC")) and math.isfinite(num("E_AVC")): first.append(dict(Name=name, BJD=x["BJD"], DRVmlcnzp=x["AVC"], e_DRVmlcnzp=x["E_AVC"], CRX=x["CRX"], e_CRX=x["E_CRX"], dLW=x["DLW"], e_dLW=x["E_DLW"], Halpha=x["HALPHA"], e_Halpha=x["E_HALPHA"], NaD1=x["NAD1"], NaD2=x["NAD2"], FWHMDRS=x["CCF_FWHM"], BIS=x["CCF_BIS"], SNRDRS=x["SNREF"], S=S)) z = zero.get(math.floor(t)) if z is not None and math.isfinite(num("CCF_RV")) and math.isfinite(num("CCF_E_RV")): second.append(dict(name=name, dace_name=name, inst="CARMENES", drs=planets_CARMENES_CODE, mode="", mjd=t - 2400000.5, rv=1000.0 * num("CCF_RV") - z, rv_err=1000.0 * num("CCF_E_RV"), qc="", smw=S, halpha=x["HALPHA"], fwhm=x["CCF_FWHM"], bis=x["CCF_BIS"], sn50=x["SNREF"])) if len({math.floor(float(x["BJD"]) - 2400000.5 + 0.3) for x in first}) < min_nights: left["nights"] += 1 continue names.add(name) sp = str(p["sp"] or "").strip() star_rows.append(dict(recno=len(star_rows) + 1, Nrv=len(first), Name=name, RAJ2000=round(float(p["ra"]), 6), DEJ2000=round(float(p["dec"]), 6), SpType=sp if planets_late_type(sp) else "MV", Teff=archive_num(r.get("Teff"), ""), Bmag=archive_num(p["mags"].get("B"), ""), Vmag=archive_num(p["mags"].get("V"), ""), Gmag=archive_num(p["mags"].get("G"), ""), Dist="", SimbadName=str(p["main"]).strip(), Mass=archive_num(r.get("Mass"), ""), Rad=archive_num(r.get("Rad"), ""), Prot=archive_num(r.get("Prot"), ""), Karmn=r["Karmn"])) vel += first dace += second folder = os.path.join(out, "planets") os.makedirs(folder, exist_ok=True) planets_write(os.path.join(folder, "bank_stars.csv"), star_rows, ["recno", "Nrv", "Name", "RAJ2000", "DEJ2000", "SpType", "Teff", "Bmag", "Vmag", "Gmag", "Dist", "SimbadName", "Mass", "Rad", "Prot", "Karmn"]) planets_write(os.path.join(folder, "bank_velocities.csv"), vel, ["Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", "FWHMDRS", "BIS", "SNRDRS", "S"]) planets_write(os.path.join(folder, "dace.csv"), dace, planets_DACE_KEYS) planets_share_tables(archive_DATA, out) json.dump(dict(family="CARMENES", upgrade=99999.0, label="CARMENES, first reduction", second_label="CARMENES, second reduction", catalogues=dict(carmenes=planets_CARMENES_CODE)), open(os.path.join(folder, "bank.json"), "w"), separators=(",", ":")) print("%d stars, %d first-reduction velocities, %d second-reduction velocities; left out: %s" % (len(star_rows), len(vel), len(dace), left), flush=True) def planets_measure(streams=12, least=4): """The stars of a root planets_targets set up, measured from their archived spectra of the root's instrument (measure.json): each star's line-by-line and cross-correlation velocities from the same spectra (planets_lbl), the cross-correlation velocities written as the root's bank, each with its spectrum's line-by-line error, and the line-by-line velocities kept beside them as the second reduction, so that census, merge, followup and ledger run in the root. A star already measured is passed over; one with fewer than LEAST spectra is listed with why in measure_failed.txt.""" inst = json.load(open(planets_path("measure.json")))["inst"] stars = planets_read(planets_path("bank_stars.csv")) listings = archive_eso_listings([(float(s["RAJ2000"]), float(s["DEJ2000"])) for s in stars], inst, 20.0) for i, (s, listing) in enumerate(zip(stars, listings)): if os.path.exists(planets_path("ccf", archive_tag(s["Name"]) + ".npz")): continue try: planets_lbl(s["Name"], streams=streams, least=least, listing=listing, inst=inst, ccf=True) except (SystemExit, Exception) as exc: with open(planets_path("measure_failed.txt"), "a", encoding="utf-8") as fh: fh.write("%s\t%s\n" % (s["Name"], str(exc)[:200].replace("\n", " "))) print("%d of %d stars" % (i + 1, len(stars)), flush=True) rows = [] for s in stars: p = planets_path("ccf", archive_tag(s["Name"]) + ".npz") if os.path.exists(p): d = np.load(p) rows += [dict(Name=s["Name"], BJD=float(t) + 2400000.5, DRVmlcnzp=round(float(v), 3), e_DRVmlcnzp=round(float(e), 3), SNRDRS=float(sn)) for t, v, e, sn in zip(d["mjd"], d["v"], d["rv_err"], d["snr"]) if math.isfinite(v) and math.isfinite(e) and e > 0] planets_write(planets_path("bank_velocities.csv"), rows, ["Name", "BJD", "DRVmlcnzp", "e_DRVmlcnzp", "CRX", "e_CRX", "dLW", "e_dLW", "Halpha", "e_Halpha", "NaD1", "NaD2", "FWHMDRS", "BIS", "SNRDRS"]) print("%s: %d velocities of %d stars written as the bank" % (inst, len(rows), len({r["Name"] for r in rows})), flush=True) def planets_bank_label(): """The label of a root's bank velocities in a vet record: the HARPS-RVBank's SERVAL velocities, ESO's pipeline velocities in a root planets_rvcat set up, the cross-correlation velocities of a root planets_measure measured, or the label a root planets_tables set up gives its own.""" if planets_BANK_INFO: return planets_BANK_INFO["label"] if os.path.exists(planets_path("rvcat.json")): return "ESO HARPS pipeline" return "orbitlight cross-correlation" if os.path.exists(planets_path("measure.json")) else "bank SERVAL" planets_DACE_KEYS = ["name", "dace_name", "inst", "drs", "mode", "mjd", "rv", "rv_err", "qc", "smw", "halpha", "fwhm", "bis", "sn50"] def planets_dace(threads=3, radius_arcsec=60.0, names=None, timeout=120.0): """DACE's public velocities of the census's stars, or in a root that planets_targets or planets_rvcat set up of every F to M star in bank_stars.csv, written as ROOT/dace.csv. Each star is looked up in DACE's spectroscopy database within RADIUS_ARCSEC of its J2000 position; DACE's target whose catalogue name is the bank's, else the one nearest the position, is the one whose time series is fetched: every instrument's series from the standard pipeline's CCF velocities and from publications. One row per velocity: the bank's name, DACE's, the instrument, the pipeline or publication, the mode, the time (MJD), the velocity and its error (m/s), the pipeline's quality flag, the Mount Wilson S index, H alpha, the CCF's FWHM and bisector span, and the signal-to-noise ratio at order 50, where given. Stars DACE has no frames for are listed in dace_absent.txt. Each call to DACE is given TIMEOUT seconds and tried four times.""" from astropy.coordinates import Angle, SkyCoord from dace_query.spectroscopy import Spectroscopy logging.disable(logging.ERROR) stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} every = os.path.exists(planets_path("measure.json")) or os.path.exists(planets_path("rvcat.json")) names = [n.strip() for n in names] if names else (sorted(n for n in stars if planets_late_type(stars[n].get("SpType"))) if every else planets_eligible(stars, planets_bank_series())) compact = lambda s: "".join(str(s).split()).upper() def retry(f, *args, **kw): for attempt in range(4): got = planets_call(f, timeout, *args, **kw) if got is not None: return got time.sleep(10 * (attempt + 1)) return None def target(n): s = stars[n] ra, dec = float(s["RAJ2000"]), float(s["DEJ2000"]) r = retry(Spectroscopy.query_region, sky_coord=SkyCoord(ra, dec, unit="deg"), angle=Angle(radius_arcsec, unit="arcsec"), limit=100000, output_format="dict") if not r or not r.get("target_name"): return None best = None for tn, cat, ra2, dec2 in zip(r["target_name"], r["target_catname"], r["ra_deg"], r["dec_deg"]): if not tn: continue d = math.hypot((float(ra2) - ra) * math.cos(math.radians(dec)), float(dec2) - dec) * 3600.0 key = (compact(cat) not in (compact(n), compact(s.get("SimbadName", ""))), d) if best is None or key < best[0]: best = (key, tn) return best[1] if best else None def one(n): tn = target(n) if tn is None: return n, None, [] g = retry(Spectroscopy.get_timeseries, tn, sorted_by_instrument=True, output_format="numpy") or {} rows = [] for inst, d in g.items(): for drs, d2 in d.items(): for mode, d3 in d2.items(): m = len(d3["rjd"]) col = lambda key: d3[key] if key in d3 else [float("nan")] * m for row in zip(d3["rjd"], d3["rv"], d3["rv_err"], col("drs_qc"), col("spectro_smw"), col("spectro_halpha"), col("ccf_fwhm"), col("ccf_bispan"), col("spectro_sn50")): try: vals = [float(x) for x in row] except (TypeError, ValueError): continue if all(math.isfinite(x) for x in vals[:3]): rows.append([n, tn, str(inst), str(drs), str(mode), vals[0] - 0.5] + vals[1:]) return n, tn, rows os.makedirs(planets_ROOT, exist_ok=True) lock = threading.Lock() with open(planets_path("dace.csv"), "w", newline="", encoding="utf-8") as fh, open(planets_path("dace_absent.txt"), "w", encoding="utf-8") as absent: w = csv.writer(fh) w.writerow(planets_DACE_KEYS) done = 0 with cf.ThreadPoolExecutor(threads) as ex: for f in cf.as_completed([ex.submit(one, n) for n in names]): n, tn, rows = f.result() with lock: if tn is None: absent.write(n + "\n") w.writerows(rows) done += 1 if done % 25 == 0: fh.flush() print("%d of %d stars" % (done, len(names)), flush=True) print("done: %d stars" % len(names), flush=True) def planets_peers(sources): """Each star of the root given the velocities the other data roots SOURCES hold of it, a star being the same by SIMBAD's object: each root's bank, its first reduction and its eras together, as an instrument named by its spectrograph, appended to ROOT/dace.csv in place of what this step last put there. A census then fits them with the root's own and a vet tests each spectrograph's alone, so that a signal one spectrograph finds is held against another's; a star whose velocities this changes loses its vet record and its system analysis, so that the next decision makes them again. Returns the stars it changes.""" here = planets_read(planets_path("bank_stars.csv")) said = lambda r: (r.get("SimbadName") or r["Name"]).strip() mine = archive_simbad_oids(sorted({said(r) for r in here})) home = {mine[said(r)]: r["Name"] for r in here if said(r) in mine} rows, counted = [], {} for source in sources: info, measured = os.path.join(source, "planets", "bank.json"), os.path.join(source, "planets", "measure.json") family = json.load(open(info)).get("family") if os.path.exists(info) else json.load(open(measured))["inst"] if os.path.exists(measured) else "HARPS" theirs = planets_read(os.path.join(source, "planets", "bank_stars.csv")) oids = archive_simbad_oids(sorted({said(r) for r in theirs})) given = {r["Name"]: home[oids[said(r)]] for r in theirs if oids.get(said(r)) in home} for x in csv.DictReader(open(os.path.join(source, "planets", "bank_velocities.csv"), encoding="utf-8")): name = given.get(x["Name"]) v, e = planets_num(x["DRVmlcnzp"]), planets_num(x["e_DRVmlcnzp"]) if name and math.isfinite(v) and math.isfinite(e) and abs(v) < 1e6 and 0 < e < 1e3: rows.append(dict(name=name, dace_name=x["Name"], inst=family, drs="CCF peer", mode="", mjd=float(x["BJD"]) - 2400000.5, rv=v, rv_err=e, qc="", smw=x.get("S", ""), halpha=x.get("Halpha", ""), fwhm=x.get("FWHMDRS", ""), bis=x.get("BIS", ""), sn50=x.get("SNRDRS", ""))) counted[family] = len(given) path = planets_path("dace.csv") before = planets_read(path) kept = [r for r in before if r["drs"] != "CCF peer"] # a spectrograph the root's own tables already hold of a star is not given it again, nor the root's own, so that no spectra count twice own = json.load(open(planets_path("bank.json"))).get("family") if os.path.exists(planets_path("bank.json")) else json.load(open(planets_path("measure.json")))["inst"] if os.path.exists(planets_path("measure.json")) else None have = {(r["name"], planets_family(r["inst"] or "")) for r in kept} rows = [x for x in rows if planets_family(x["inst"] or "") != planets_family(own or "HARPS") and (x["name"], planets_family(x["inst"] or "")) not in have] tmp = archive_tmp(path) planets_write(tmp, kept + rows, planets_DACE_KEYS) archive_place(tmp, path) tally = lambda xs: {n: sum(1 for x in xs if x["name"] == n) for n in {x["name"] for x in xs}} old, new = tally([r for r in before if r["drs"] == "CCF peer"]), tally(rows) changed = sorted(n for n in set(old) | set(new) if old.get(n) != new.get(n)) for n in changed: for p in (os.path.join(planets_RESULTS, "vet", archive_tag(n) + ".json"), os.path.join(planets_RESULTS, "system", archive_tag(n), "analysis.json")): if os.path.exists(p): os.remove(p) print("%d stars here; %d velocities of the other roots' stars: %s; %d stars changed" % (len(here), len(rows), counted, len(changed)), flush=True) return changed def planets_dace_series(names=None): """DACE's velocities by star and series (instrument, pipeline or publication, mode), of NAMES alone where given, those the pipeline's quality control failed left out: rows of (MJD, velocity, error, S, H alpha, FWHM, bisector, CRX, dLW), the last two empty.""" raw = {} for r in csv.DictReader(open(planets_path("dace.csv"), encoding="utf-8")): if names is not None and r["name"] not in names: continue v, e = planets_num(r["rv"]), planets_num(r["rv_err"]) if math.isfinite(v) and math.isfinite(e) and 0 < e < 1e3 and planets_num(r["qc"]) != 0.0: raw.setdefault(r["name"], {}).setdefault((r["inst"], r["drs"], r["mode"]), []).append( [planets_num(r["mjd"]), v, e, planets_num(r["smw"]), planets_num(r["halpha"]), planets_num(r["fwhm"]), planets_num(r["bis"]), float("nan"), float("nan")]) return raw def planets_family(inst): """An instrument's family, its eras and upgrades together (HARPS03 and HARPS15, HIRES-PRE04 and HIRES-POST04, HARPN and HARPS-N).""" f = re.sub(r"(\d+|-PRE04|-POST04|\+)$", "", inst) return {"HARPN": "HARPS-N"}.get(f, f) def planets_join(n, insts, bank_rows, sptype): """A star's series with the bank's HARPS, or the spectrograph a root's bank comes from, in place of DACE's: the bank's velocities before and after its upgrade as two series, each given the S index of DACE's velocity of that spectrograph within 5 minutes of it, and, for F, G and K stars, DACE's velocities of it further than that from every bank velocity, as series of their own: for HARPS those of its pipeline, for another spectrograph those of the second reduction a root planets_tables set up holds.""" harps = {k: x for k, x in insts.items() if planets_family(k[0]) == planets_BANK_FAMILY} out = {k: x for k, x in insts.items() if planets_family(k[0]) != planets_BANK_FAMILY} reduction = lambda k: "CCF" in k[1] or planets_BANK_FAMILY != "HARPS" rows = [list(x) for x in bank_rows] dace = sorted((x for k, xs in harps.items() if reduction(k) for x in xs), key=lambda x: x[0]) td = np.array([x[0] for x in dace]) tb = np.array([x[0] for x in rows]) if len(td) and len(tb): j = np.clip(np.searchsorted(td, tb), 0, len(td) - 1) j = np.where((j > 0) & (np.abs(td[j - 1] - tb) < np.abs(td[j] - tb)), j - 1, j) for i in np.where(np.abs(td[j] - tb) < 5.0 / 1440.0)[0]: if math.isfinite(dace[j[i]][3]): rows[i][3] = dace[j[i]][3] bank_name = "%s bank" % planets_BANK_FAMILY if planets_BANK_INFO else "HARPS-RVBank" for label, sel in (("pre", [x for x in rows if x[0] < planets_UPGRADE]), ("post", [x for x in rows if x[0] >= planets_UPGRADE])): if sel: out[(bank_name, "SERVAL CCF" if not planets_BANK_INFO else planets_BANK_INFO["label"], label)] = sel if (sptype or " ")[0] != "M": sb = np.sort(tb) for k, xs in harps.items(): if not reduction(k): continue if len(sb): tk = np.array([x[0] for x in xs]) jj = np.clip(np.searchsorted(sb, tk), 0, len(sb) - 1) near = np.minimum(np.abs(sb[jj] - tk), np.abs(sb[np.maximum(jj - 1, 0)] - tk)) xs = [x for x, d in zip(xs, near) if d >= 5.0 / 1440.0] if xs: out[(k[0], k[1], k[2] + " unbanked")] = xs return out def planets_clean(rows): """A series without the velocities whose errors exceed five times its median error or which lie further from its median than 15 times its scaled median absolute deviation or 30 m/s, whichever is more.""" x = np.array(rows) x = x[x[:, 2] <= 5.0 * np.median(x[:, 2])] med = np.median(x[:, 1]) return x[np.abs(x[:, 1] - med) <= max(15.0 * 1.4826 * np.median(np.abs(x[:, 1] - med)), 30.0)].tolist() def planets_choose(insts): """One set of series per instrument family: the pipeline's CCF series where there are any, each instrument and mode from its pipeline version with the most velocities, else the series of the one publication with the most velocities; a publication's series is set aside when half its times or more fall within 5 minutes of the times already kept, and every series whose median error exceeds 20 m/s.""" fams = {} for k in insts: fams.setdefault(planets_family(k[0]), []).append(k) kept = [] for fam, ks in sorted(fams.items(), key=lambda x: -sum(len(insts[k]) for k in x[1] if "CCF" in k[1])): drs = [k for k in ks if "CCF" in k[1]] if drs: best = {} for k in drs: if (k[0], k[2]) not in best or len(insts[k]) > len(insts[best[(k[0], k[2])]]): best[(k[0], k[2])] = k kept += list(best.values()) else: pubs = {} for k in ks: pubs.setdefault(k[1], []).append(k) bib = max(pubs, key=lambda b: sum(len(insts[k]) for k in pubs[b])) have = np.sort(np.array([x[0] for k in kept for x in insts[k]] or [-1e9])) for k in pubs[bib]: tk = np.array([x[0] for x in insts[k]]) j = np.clip(np.searchsorted(have, tk), 1, max(len(have) - 1, 1)) near = np.minimum(np.abs(have[np.minimum(j, len(have) - 1)] - tk), np.abs(have[j - 1] - tk)) if np.mean(near < 5.0 / 1440.0) < 0.5: kept.append(k) return [k for k in kept if insts[k] and np.median([x[2] for x in insts[k]]) <= 20.0] def planets_series(n, dace, bank, sptype): """A star's chosen series, cleaned and numbered from the one with most velocities: rows of (MJD, velocity, error, series number, S, H alpha, FWHM, bisector, CRX, dLW), and the series' labels.""" insts = {k: planets_clean(x) for k, x in planets_join(n, dace.get(n, {}), bank.get(n, []), sptype).items() if x} insts = {k: x for k, x in insts.items() if x} keep = sorted(planets_choose(insts), key=lambda k: -len(insts[k])) return [x[:3] + [float(i)] + x[3:] for i, k in enumerate(keep) for x in insts[k]], [" ".join(x for x in k if x) for k in keep] def planets_nightly(rows): """Rows averaged per night and series (nights split at La Silla's local noon), the velocity weighted by its inverse variance, the indicators by count.""" s = np.asarray(rows, float) _, inv = np.unique(np.floor(s[:, 0] + 0.3) * 100.0 + s[:, 3], return_inverse=True) m = int(inv.max()) + 1 w = 1.0 / s[:, 2] ** 2 W = np.bincount(inv, w, m) cols = [np.bincount(inv, s[:, 0], m) / np.bincount(inv, minlength=m), np.bincount(inv, w * s[:, 1], m) / W, 1.0 / np.sqrt(W)] for j in range(3, s.shape[1]): ok = np.isfinite(s[:, j]) cnt = np.bincount(inv[ok], minlength=m) cols.append(np.where(cnt > 0, np.bincount(inv[ok], s[ok, j], m) / np.maximum(cnt, 1), np.nan)) return np.column_stack(cols) def planets_known(path): """The archive's planets by host, and a function finding a star's host by name or by its position carried back to J2000.""" norm = lambda s: (lambda x: "GJ" + x[2:] if x.startswith("GL") and x[2:3].isdigit() else x)(re.sub(r"[\s_]", "", str(s or "")).upper()) host_names, host_pos, planets_of = {}, {}, {} for p in planets_read(path): planets_of.setdefault(p["hostname"], []).append(dict(name=p["pl_name"], P=planets_num(p["pl_orbper"]), K=planets_num(p["pl_rvamp"]), e=planets_num(p["pl_orbeccen"]))) for col in ("hostname", "hd_name", "hip_name"): if p.get(col): host_names.setdefault(norm(p[col]), p["hostname"]) if p["hostname"] not in host_pos: dec = planets_num(p["dec"]) host_pos[p["hostname"]] = (planets_num(p["ra"]) - 16.0 * np.nan_to_num(planets_num(p["sy_pmra"])) / 3.6e6 / math.cos(math.radians(dec)), dec - 16.0 * np.nan_to_num(planets_num(p["sy_pmdec"])) / 3.6e6) hosts = list(host_pos) hpos = np.array([host_pos[h] for h in hosts]) def host_of(name, simbad, ra, dec): for nm in (name, simbad): k = norm(nm) for key in (k, k[:-1] if len(k) > 2 and k.endswith("A") and k[-2].isdigit() else None): if key and key in host_names: return host_names[key] if not (math.isfinite(ra) and math.isfinite(dec)): return None d = np.degrees(np.arccos(np.clip(np.sin(np.radians(dec)) * np.sin(np.radians(hpos[:, 1])) + np.cos(np.radians(dec)) * np.cos(np.radians(hpos[:, 1])) * np.cos(np.radians(ra - hpos[:, 0])), -1, 1))) * 3600.0 i = int(np.nanargmin(d)) return hosts[i] if d[i] < 10.0 else None return planets_of, host_of def planets_model(p, t, X, nk): """The linear part (offsets, trend, activity) and nk Keplerians, each (P, tp, sqrt(e) cos w, sqrt(e) sin w, K).""" nl = X.shape[1] out = X @ p[:nl] for k in range(nk): P, tp, c, s, K = p[nl + 5 * k:nl + 5 * k + 5] out = out + abs(K) * planets_kepler(t, P, tp, min(c * c + s * s, 0.9), math.atan2(s, c)) return out def planets_fit_many(t, v, sig, X, keps, bounds_frac): """The joint fit of the linear part X and the Keplerians from each set of starts in KEPS (planets_fit_batch): the set whose fit leaves the least chi-square, with that chi-square.""" return planets_fit_batch([(t, v, sig, X, keps, bounds_frac)])[0] def planets_fit_batch(asks, budget=2e8): """The fits of many requests ASKS, each (t, v, sig, X, keps, bounds), together by Levenberg-Marquardt (gpu_lm): the linear part X and the Keplerians from each set of starts in keps, least squares with the soft L1 loss at 3 sigma, each period held within its fraction of its start and each sqrt(e) cos w and sqrt(e) sin w within 0.95, the linear part solved first. Every start of every request is a problem, the problems of one shape (as many linear terms and Keplerians, nights within a factor of two) solved in blocks of at most BUDGET residuals per evaluation, each request's nights padded to its block's longest and the padding given no weight; for each request the start whose fit leaves the least chi-square, with that chi-square.""" probs = [] for a, (t, v, sig, X, keps, fr) in enumerate(asks): lin = np.linalg.lstsq(X / sig[:, None], v / sig, rcond=None)[0] nl, nk = X.shape[1], len(keps[0]) for kep in keps: p0 = np.array(list(lin) + [x for k in kep for x in k], float) lo, hi = np.full(len(p0), -np.inf), np.full(len(p0), np.inf) for i, f_ in enumerate(fr): j = nl + 5 * i lo[j], hi[j] = kep[i][0] * (1 - f_), kep[i][0] * (1 + f_) lo[j + 2:j + 4], hi[j + 2:j + 4] = -0.95, 0.95 probs.append((a, nl, nk, len(t), np.clip(p0, lo + 1e-9, hi - 1e-9), lo, hi)) shapes = {} for q, pr in enumerate(probs): shapes.setdefault((pr[1], pr[2], int(np.ceil(np.log2(max(pr[3], 2))))), []).append(q) params, chi2 = [None] * len(probs), np.full(len(probs), np.inf) for (nl, nk, bucket), members in shapes.items(): block = max(16, int(budget / ((2 * (nl + 5 * nk) + 1) * 2 ** bucket))) for b0 in range(0, len(members), block): sel = members[b0:b0 + block] reqs = sorted({probs[q][0] for q in sel}) row = {a: i for i, a in enumerate(reqs)} n = max(len(asks[a][0]) for a in reqs) T, V, S, M = (np.zeros((len(reqs), n)) for _ in range(4)) XX = np.zeros((nl, len(reqs), n)) for i, a in enumerate(reqs): t, v, sig, X = asks[a][:4] m = len(t) T[i, :m], V[i, :m], S[i, :m], M[i, :m], XX[:, i, :m] = t, v, sig, 1.0, X.T T[i, m:], S[i, m:] = t[0], 1.0 T, V, S, M, XX = (gpu_dev(z) for z in (T, V, S, M, XX)) owner = torch.as_tensor([row[probs[q][0]] for q in sel], device=gpu_DEVICE) kern = _gpu_kernels() if gpu_DEVICE.type == "cuda" else None def resid(p, idx): if kern is not None: return kern.census_residuals(p.contiguous(), owner[idx].contiguous(), T, V, S, M, XX.contiguous(), nl, nk, _gpu_stream()) r = owner[idx] m_ = p[:, :1] * XX[0][r] for j in range(1, nl): m_ = m_ + p[:, j:j + 1] * XX[j][r] for i in range(nk): P, tp, c, s, K = (p[:, nl + 5 * i + j:nl + 5 * i + j + 1] for j in range(5)) m_ = m_ + K.abs() * gpu_keplerian(T[r], P, tp, torch.clamp(c * c + s * s, max=0.9), torch.atan2(s, c)) return (m_ - V[r]) / S[r] * M[r] p, _ = gpu_lm(resid, np.array([probs[q][4] for q in sel]), np.array([probs[q][5] for q in sel]), np.array([probs[q][6] for q in sel]), f_scale=3.0, graph=kern is not None) c2 = gpu_host((resid(p, torch.arange(len(sel), device=gpu_DEVICE)) ** 2).sum(1)) for q, pq, cq in zip(sel, gpu_host(p), c2): params[q], chi2[q] = pq, cq of = {} for q, pr in enumerate(probs): of.setdefault(pr[0], []).append(q) out = [] for a in range(len(asks)): best = min(of[a], key=lambda q: chi2[q]) out.append((params[best], float(chi2[best]))) return out def planets_starts(t, r, sig, P, eccs=(0.05, 0.3, 0.6)): """Keplerian starts at period P over the eccentricities ECCS and four arguments of periastron, their amplitude and phase from a circular orbit fitted linearly to the residuals R.""" X = np.column_stack([np.cos(2 * np.pi * t / P), np.sin(2 * np.pi * t / P), np.ones_like(t)]) c = np.linalg.lstsq(X / sig[:, None], r / sig, rcond=None)[0] K0, phi = max(math.hypot(c[0], c[1]), 0.5), math.atan2(c[1], c[0]) return [[P, P * (phi + w0) / (2 * np.pi), math.sqrt(e0) * math.cos(w0), math.sqrt(e0) * math.sin(w0), K0] for e0 in eccs for w0 in np.radians((0.0, 90.0, 180.0, 270.0))] def planets_search(name, rows, labels, star, planets_of, host_of, blind=False, state=None): """One star's model and signals. The velocities and indicators are averaged per night and series; each series with three nights or more gets an offset, and the model holds the indicators (each standardised within its series) that correlate with the velocities at p below 0.01 once a quadratic is out of them, and Keplerians: first the archive's planets of the star, each started at its catalogue period and eccentricity and held within 1 per cent of the period, then signals found one at a time in the residuals by a generalised Lomb-Scargle periodogram from 1.5 d to twice the span, the periods within 5 per cent or a resolution element of a signal already in the model set aside, each standing at a Baluev false-alarm level below 1e-3 and fitted jointly with everything before it, up to eight, with a jitter for each series added to its errors. A linear trend, or a quadratic over 300 d of span or more, joins the model last, only where it lowers the BIC by more than 10 with the Keplerians in, so that a long orbit is searched as a Keplerian rather than taken up by a trend. BLIND leaves the archive's planets out of the model, records them beside it, and searches for up to two more signals than they number, so that the search can be scored on them. Before the search, nights further from the model than six times the residuals' scaled median absolute deviation and five times the median error are set aside, at most one in twenty. Each found signal carries its flags: an indicator whose own periodogram has power within 5 per cent of its period at a false-alarm level below 0.01, nearness to a catalogued planet's period or to the 1-day and 1-year aliases of the signals before it, a period longer than the span, and a jitter above 10 m/s. Returns the star's record and signal rows, or None for a star the census passes; a dict STATE receives the final model's times, residuals, errors with the jitters, series numbers and periods.""" steps = planets_search_steps(name, rows, labels, star, planets_of, host_of, blind, state) try: ask = next(steps) while True: ask = steps.send(planets_fit_many(*ask)) except StopIteration as done: return done.value def planets_search_stream(jobs): """planets_search for many stars together, each job its arguments (name, rows, labels, star, planets_of, host_of, blind, state): the stars' searches advanced in rounds, each round's fits of every star solved together (planets_fit_batch), each star's (index, result) yielded as soon as its search ends.""" steps, asks = {}, {} for i, job in enumerate(jobs): g = planets_search_steps(*job) try: asks[i], steps[i] = next(g), g except StopIteration as done: yield i, done.value while asks: keys = list(asks) for i, answer in zip(keys, planets_fit_batch([asks[i] for i in keys])): try: asks[i] = steps[i].send(answer) except StopIteration as done: del asks[i] yield i, done.value def planets_search_many(jobs): """planets_search_stream's results in the jobs' order.""" out = [None] * len(jobs) for i, got in planets_search_stream(jobs): out[i] = got return out def planets_search_steps(name, rows, labels, star, planets_of, host_of, blind=False, state=None): """planets_search's steps as a generator: each joint fit is yielded as planets_fit_many's arguments (t, v, sig, X, keps, bounds) and answered with its parameters and chi-square; returns the star's record and signal rows, or None.""" from scipy.stats import pearsonr s = planets_nightly(rows) inst = s[:, 3].astype(int) keep = np.bincount(inst)[inst] >= 3 s, inst = s[keep], inst[keep] t, v, e = s[:, 0], s[:, 1], s[:, 2] span = float(t.max() - t.min()) if len(t) else 0.0 sptype = star.get("SpType", "") rec = dict(name=name, sptype=sptype, nights=len(t), span_d=round(span), instruments={labels[k]: int((inst == k).sum()) for k in np.unique(inst)}) if not planets_late_type(sptype) or len(t) < 15 or span < 100: return None tt = (t - t.mean()) / 365.25 # offsets only; a trend is tested after the Keplerians cols = [np.ones_like(t)] for k in np.unique(inst)[1:]: cols.append((inst == k).astype(float)) # the indicators are tested against the velocities less a quadratic trend base = np.column_stack(cols + [tt] + ([tt ** 2] if span >= 300 else [])) r0 = v - base @ np.linalg.lstsq(base / e[:, None], v / e, rcond=None)[0] # each indicator standardised within its series for j in range(len(planets_INDICATORS)): for k in np.unique(inst): m = inst == k x = s[m, 4 + j] sd = np.nanstd(x) if np.isfinite(x).sum() >= 3 else 0.0 s[m, 4 + j] = (x - np.nanmedian(x)) / sd if sd > 0 else np.nan used = [] for j, label in enumerate(planets_INDICATORS): x = s[:, 4 + j] ok = np.isfinite(x) if ok.sum() < 0.5 * len(t) or ok.sum() < 12 or np.std(x[ok]) == 0: continue if pearsonr(r0[ok], x[ok])[1] < 0.01: cols.append(np.where(ok, x, 0.0)) used.append(label) X = np.column_stack(cols) host = host_of(name, star.get("SimbadName"), planets_num(star.get("RAJ2000")), planets_num(star.get("DEJ2000"))) known = [k for k in (planets_of.get(host, []) if host else []) if math.isfinite(k["P"]) and 1.0 < k["P"] < 3.0 * span] most = 8 if blind: rec["catalogue"] = [dict(name=k["name"], P=k["P"], K=k["K"], e=k["e"]) for k in known] most, known = max(4, len(known) + 2), [] m1 = planets_star_mass(star) # a jitter for each series, added to its errors series, ii = np.unique(inst, return_inverse=True) jit = np.ones(len(series)) sig = np.hypot(e, jit[ii]) kep, fr, kinds = [], [], [] for k in known: e0 = k["e"] if math.isfinite(k["e"]) else 0.1 # a catalogued planet starts at its catalogue eccentricity alone starts = planets_starts(t, r0, sig, k["P"], (min(max(e0, 0.02), 0.8),)) for st0 in starts: st0[4] = k["K"] if math.isfinite(k["K"]) else max(np.std(r0), 1.0) best = yield (t, v, sig, X, [kep + [st0] for st0 in starts], fr + [0.01]) nl = X.shape[1] kep = [list(best[0][nl + 5 * i:nl + 5 * i + 5]) for i in range(len(kep) + 1)] fr.append(0.01) kinds.append(("known", k["name"])) resid_of = lambda p: v - (planets_model(p, t, X, len(kep)) if kep else X @ p) p_cur = (yield (t, v, sig, X, [kep], fr))[0] if kep else np.linalg.lstsq(X / sig[:, None], v / sig, rcond=None)[0] # the outlying nights set aside, the furthest first, from the residuals about a quadratic r_ = resid_of(p_cur) Q = np.column_stack([np.ones_like(t), tt, tt ** 2]) r_ = r_ - Q @ np.linalg.lstsq(Q / sig[:, None], r_ / sig, rcond=None)[0] dev = np.abs(r_ - np.median(r_)) out_i = np.argsort(-dev)[:len(t) // 20] out_i = out_i[dev[out_i] > max(6.0 * 1.4826 * np.median(dev), 5.0 * np.median(e))] if len(out_i): keep_i = np.setdiff1d(np.arange(len(t)), out_i) t, v, e, s, X, inst, ii, tt = t[keep_i], v[keep_i], e[keep_i], s[keep_i], X[keep_i], inst[keep_i], ii[keep_i], tt[keep_i] sig = np.hypot(e, jit[ii]) p_cur = (yield (t, v, sig, X, [kep], fr))[0] if kep else np.linalg.lstsq(X / sig[:, None], v / sig, rcond=None)[0] rec["set_aside"] = int(len(out_i)) found = [] freq = np.linspace(1.0 / (2.0 * span), 1.0 / 1.5, 40000) for it in range(most): resid = resid_of(p_cur) for j in range(len(series)): m = ii == j if m.sum() >= 3: jit[j] = max(math.sqrt(max(np.mean(resid[m] ** 2) - np.mean(e[m] ** 2), 0.0)), 0.5) sig = np.hypot(e, jit[ii]) pw = gpu_host(gpu_gls(t, resid, sig, freq)) # the periods within 5 per cent, or a resolution element, of a signal already in the model set aside for k_ in kep: pw[(np.abs(1.0 / freq / k_[0] - 1.0) < 0.05) | (np.abs(freq - 1.0 / k_[0]) < 1.0 / span)] = 0.0 k = int(np.argmax(pw)) fap = float(gpu_baluev(pw[k], freq[-1], t, sig)) if fap > 1e-3: break best = yield (t, v, sig, X, [kep + [st0] for st0 in planets_starts(t, resid, sig, 1.0 / freq[k])], fr + [0.05]) nl = X.shape[1] kep = [list(best[0][nl + 5 * i:nl + 5 * i + 5]) for i in range(len(kep) + 1)] fr.append(0.05) p_cur = best[0] kinds.append(("found", "signal %d" % (it + 1))) found.append(fap) # a linear or quadratic trend joins the model where it lowers the BIC by more than 10 def lnl_of(p, XX): r = v - (planets_model(p, t, XX, len(kep)) if kep else XX @ p) return -0.5 * float(np.sum(r ** 2 / sig ** 2 + np.log(2 * np.pi * sig ** 2))) bic_best, trend = -2.0 * lnl_of(p_cur, X), [] nl0 = X.shape[1] for terms in ([tt], [tt, tt ** 2])[:2 if span >= 300 else 1]: XX = np.column_stack([X] + terms) pp = (yield (t, v, sig, XX, [kep], fr))[0] if kep else np.linalg.lstsq(XX / sig[:, None], v / sig, rcond=None)[0] bic = -2.0 * lnl_of(pp, XX) + len(terms) * math.log(len(t)) if bic < bic_best - 10.0: bic_best, trend, X_t, p_t = bic, [round(float(x), 3) for x in pp[nl0:nl0 + len(terms)]], XX, pp if trend: X, p_cur = X_t, p_t kep = [list(p_cur[X.shape[1] + 5 * i:X.shape[1] + 5 * i + 5]) for i in range(len(kep))] rms = float(np.std(resid_of(p_cur))) # the jitter that flags a star is its largest series' jitter = float(jit[0]) rec.update(host=host, activity_regressors=used, jitter=round(jitter, 2), jitters={labels[u]: round(float(jit[j]), 2) for j, u in enumerate(series)}, rms_resid=round(rms, 2), n_known=len(known), n_found=len(found), trend=trend, t_mean=round(float(t.mean()), 2)) out, fi = [], 0 ind_pw = {} for j, lab in enumerate(planets_INDICATORS): x = s[:, 4 + j] ok = np.isfinite(x) if ok.sum() >= 12 and np.std(x[ok]) > 0: ind_pw[j] = (gpu_host(gpu_gls(t[ok], x[ok], None, freq)), t[ok]) for i, (kind, label) in enumerate(kinds): P, tp, c, sn, K = kep[i] ecc = min(c * c + sn * sn, 0.9) msini = planets_msini(P, abs(K), ecc, m1) row = dict(name=name, sptype=sptype, vmag=star.get("Vmag", ""), host=host or "", kind=kind, label=label, nights=len(t), span_d=round(span), P=round(P, 4), K=round(abs(K), 2), e=round(ecc, 3), msini_mjup=round(msini, 4), msini_mearth=round(msini * 317.83, 1), rms_resid=round(rms, 2), jitter=round(jitter, 2), regressors=";".join(used), fap="", flags="") if kind == "found": row["fap"] = found[fi] fi += 1 flags = [] near = np.abs(1.0 / freq / P - 1.0) < 0.05 for j, (pa, tj) in ind_pw.items(): if near.any(): kk = int(np.argmax(np.where(near, pa, -1))) if float(gpu_baluev(pa[kk], freq[-1], tj)) < 0.01: flags.append("%s at P" % planets_INDICATORS[j]) flags += ["near %s" % kn["name"] for kn in known if abs(P / kn["P"] - 1.0) < 0.05] for j2 in range(i): f2 = 1.0 / kep[j2][0] for base_f in (1.0 / 1.0027, 1.0 / 365.25): for sgn in (1, -1): if f2 + sgn * base_f > 0 and abs(1.0 / P - (f2 + sgn * base_f)) < 0.05 / P: flags.append("alias of %.2f d" % kep[j2][0]) if P > span: flags.append("longer than the span") if jitter > 10.0: flags.append("jitter %.0f m/s" % jitter) row["flags"] = "; ".join(flags) out.append(row) if state is not None: state.update(t=t, resid=resid_of(p_cur), sig=sig, groups=ii, periods=[float(k_[0]) for k_ in kep]) return rec, out planets_SIGNAL_KEYS = ["name", "sptype", "vmag", "host", "kind", "label", "nights", "span_d", "P", "K", "e", "msini_mjup", "msini_mearth", "rms_resid", "jitter", "regressors", "fap", "flags"] def planets_share(part=None, hosts=False): """The census's stars, of the share K/N where PART is given: the eligible stars ranked by their count of velocities, every Nth from the Kth, and with HOSTS only those the archive lists planets for. A star with no bank velocities, as in a root that planets_targets set up, is eligible where its DACE velocities cover 15 nights or more over 100 days or more. Returns the names, the star records, and the archive's planets by host with the host finder.""" stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} planets_of, host_of = planets_known(planets_path("known.csv")) # each star's count of velocities, read without keeping the velocities times, sizes, dace_times = {}, {}, {} for r in csv.DictReader(open(planets_path("bank_velocities.csv"), encoding="utf-8")): if math.isfinite(planets_num(r["DRVmlcnzp"])) and math.isfinite(planets_num(r["e_DRVmlcnzp"])): times.setdefault(r["Name"], []).append([float(r["BJD"]) - 2400000.5]) for r in csv.DictReader(open(planets_path("dace.csv"), encoding="utf-8")): sizes[r["name"]] = sizes.get(r["name"], 0) + 1 if r["name"] not in times and math.isfinite(planets_num(r["rv"])): dace_times.setdefault(r["name"], []).append([float(r["mjd"])]) names = planets_eligible(stars, dict(dace_times, **times)) sizes = {n: len(times.get(n, [])) + sizes.get(n, 0) for n in names} del times, dace_times if hosts: names = [n for n in names if host_of(n, stars[n].get("SimbadName"), planets_num(stars[n].get("RAJ2000")), planets_num(stars[n].get("DEJ2000")))] rank = {n: i for i, n in enumerate(sorted(names, key=lambda n: (-sizes[n], n)))} if part: k, n_parts = (int(x) for x in part.split("/")) names = [n for n in names if rank[n] % n_parts == k] return names, stars, planets_of, host_of def planets_kepler_power(t, r, sig, groups, pmin=1.5, eccs=(0.3, 0.5, 0.65, 0.8, 0.9), phases=16, oversample=5, shuffle=None): """The Keplerian periodogram of velocities R at times T with errors SIG and an offset for each of GROUPS: at every frequency from 1/(2 x span) to 1/PMIN, spaced at 1/(OVERSAMPLE x span), the circular orbit and every eccentricity of ECCS at PHASES times of periastron, each orbit's two linear terms solved exactly with the offsets profiled out, and the improvement in chi-square over the offsets alone, in single precision. SHUFFLE, a numpy Generator, permutes the velocities and their errors within each group first, for a null. Returns the frequencies, the best improvement at each and the circular orbit's, the offsets-only chi-square, and the best orbit: period, eccentricity, time of periastron, K, omega and improvement.""" dev = gpu_DEVICE t, r, sig = (np.asarray(x, float) for x in (t, r, sig)) g = np.asarray(groups, int) if shuffle is not None: r, sig = r.copy(), sig.copy() for k in np.unique(g): idx = np.where(g == k)[0] perm = shuffle.permutation(idx) r[idx], sig[idx] = r[perm], sig[perm] _, g = np.unique(g, return_inverse=True) span = float(t.max() - t.min()) freqs = np.arange(1.0 / (2.0 * span), 1.0 / pmin, 1.0 / (oversample * span)) w = 1.0 / sig ** 2 onehot = np.zeros((len(t), int(g.max()) + 1)) onehot[np.arange(len(t)), g] = 1.0 wsum = onehot.T @ w rt = r - ((onehot.T @ (w * r)) / wsum)[g] chi0 = float(np.sum(w * rt ** 2)) combos = [(0.0, 0.0)] + [(e, k / phases) for e in eccs for k in range(phases)] f32 = dict(dtype=torch.float32, device=dev) E = torch.tensor([c[0] for c in combos], **f32)[None, :, None] PH = torch.tensor([c[1] for c in combos], dtype=torch.float64, device=dev)[None, :, None] T = torch.tensor(t - t.min(), dtype=torch.float64, device=dev)[None, None, :] W, R, OH, WS = (torch.tensor(x, **f32) for x in (w, rt, onehot, wsum)) G = torch.tensor(g, dtype=torch.long, device=dev) sp, sm = torch.sqrt(1 + E), torch.sqrt(1 - E) chunk = max(8, int(2.0e7 / (len(combos) * len(t)))) best, circ = np.empty(len(freqs)), np.empty(len(freqs)) top = (-1.0, None) with torch.no_grad(): for i0 in range(0, len(freqs), chunk): F = torch.tensor(freqs[i0:i0 + chunk], dtype=torch.float64, device=dev)[:, None, None] M = 2 * math.pi * torch.remainder(F * T - PH, 1.0).to(torch.float32) Ea = gpu_kepler_E(M, E, 10) nu = 2 * torch.atan2(sp * torch.sin(Ea / 2), sm * torch.cos(Ea / 2)) c, s = torch.cos(nu), torch.sin(nu) # the offsets profiled out: each basis vector less its weighted mean in each group c = c - ((c * W) @ OH / WS)[..., G] s = s - ((s * W) @ OH / WS)[..., G] cw, sw = c * W, s * W Scc, Sss, Scs, Src, Srs = (cw * c).sum(-1), (sw * s).sum(-1), (cw * s).sum(-1), (cw * R).sum(-1), (sw * R).sum(-1) det = Scc * Sss - Scs ** 2 det = torch.where(det > 1e-9 * Scc * Sss, det, torch.full_like(det, float("inf"))) A = (Src * Sss - Srs * Scs) / det B = (Srs * Scc - Src * Scs) / det d = A * Src + B * Srs dmax, cidx = d.max(dim=1) best[i0:i0 + F.shape[0]] = dmax.double().cpu().numpy() circ[i0:i0 + F.shape[0]] = d[:, 0].double().cpu().numpy() j = int(torch.argmax(dmax)) if float(dmax[j]) > top[0]: ci = int(cidx[j]) top = (float(dmax[j]), (i0 + j, ci, float(A[j, ci]), float(B[j, ci]))) fi, ci, A_, B_ = top[1] P_, e_ = 1.0 / freqs[fi], combos[ci][0] return dict(freqs=freqs, best=best, circ=circ, chi0=chi0, P=P_, e=e_, tp=float(t.min() + combos[ci][1] * P_), K=math.hypot(A_, B_), omega=math.atan2(-B_, A_), dchi2=top[0], dchi2_circular=float(circ[fi])) def planets_eccentric(part=None, perms=50, min_dchi2=25.0, hosts=False): """The census's residuals searched for one more Keplerian, eccentric orbits included, to RESULTS/eccentric/stars[.partKofN].jsonl. Each star of the share is modelled as the census models it (planets_search), and the residuals of its final model, with its jitters, are searched by planets_kepler_power. Where the best orbit improves chi-square by MIN_DCHI2 or more, sets of the residuals permuted within each series give the null's highest improvements, eight at first and PERMS where the best orbit stands above all eight, and a Gumbel distribution fitted to them gives the false-alarm level. Each star's best orbit is kept with its period, eccentricity, K, minimum mass, its improvement over the circular orbit at the same period, and its nearness to the census's periods and their 1-day and 1-year aliases. A star any share has recorded is passed over, and the search ends between stars with exit status 3 where a long search would (planets_search_ends). Run on every star, without PART, the search ends by keeping its candidates (planets_eccentric_merge).""" names, stars, planets_of, host_of = planets_share(part, hosts) bank = planets_bank_series(set(names)) dace = planets_dace_series(set(names)) mark = (".part%sof%s" % tuple(part.split("/"))) if part else "" folder = os.path.join(planets_RESULTS, "eccentric") os.makedirs(folder, exist_ok=True) rng = np.random.default_rng(5) held = {r["name"] for r in planets_eccentric_records()} jobs = [] for name in names: if name in held: continue rows, labels = planets_series(name, dace, bank, stars.get(name, {}).get("SpType")) if rows: jobs.append((name, rows, labels, stars.get(name, {}), planets_of, host_of, False, {})) models = planets_search_many(jobs) with open(os.path.join(folder, "stars%s.jsonl" % mark), "a", encoding="utf-8") as out: for count, (job, got) in enumerate(zip(jobs, models)): if planets_search_ends(): sys.exit(3) name, star, keep = job[0], job[3], job[7] if got is None or not keep: continue t, r, sig, g = keep["t"], keep["resid"], keep["sig"], keep["groups"] kp = planets_kepler_power(t, r, sig, g) span = float(t.max() - t.min()) near = [] for Q in keep["periods"]: if abs(kp["P"] / Q - 1.0) < 0.05: near.append("near %.2f d" % Q) elif any(abs(1.0 / kp["P"] - abs(1.0 / Q + sg * b)) < 0.02 / kp["P"] for b in (1.0 / 1.0027, 1.0 / 365.25) for sg in (1, -1)): near.append("alias of %.2f d" % Q) if kp["P"] > span: near.append("longer than the span") rec = dict(name=name, sptype=star.get("SpType", ""), nights=len(t), span_d=round(span), census_periods=[round(Q, 4) for Q in keep["periods"]], P=round(kp["P"], 4), e=kp["e"], K=round(kp["K"], 2), omega=round(kp["omega"], 3), tp=round(kp["tp"], 3), dchi2=round(kp["dchi2"], 2), dchi2_circular=round(kp["dchi2_circular"], 2), chi2_0=round(kp["chi0"], 2), msini_mearth=round(planets_msini(kp["P"], kp["K"], kp["e"], planets_mass(star.get("SpType"))) * 317.83, 1), flags="; ".join(near)) if kp["dchi2"] >= min_dchi2 and perms: null = [planets_kepler_power(t, r, sig, g, shuffle=rng)["dchi2"] for _ in range(min(perms, 8))] if kp["dchi2"] > max(null): null += [planets_kepler_power(t, r, sig, g, shuffle=rng)["dchi2"] for _ in range(perms - len(null))] null = np.array(null) beta = max(float(np.std(null, ddof=1)) * math.sqrt(6.0) / math.pi, 1e-9) mu = float(np.mean(null)) - 0.5772 * beta rec.update(null_draws=len(null), null_mean=round(float(np.mean(null)), 2), null_sd=round(float(np.std(null, ddof=1)), 2), null_max=round(float(null.max()), 2), fap=float(-math.expm1(-math.exp(-(kp["dchi2"] - mu) / beta)))) out.write(json.dumps(rec) + "\n") out.flush() print("%4d %-12s n %4d | P %9.3f e %.2f K %6.2f | dchi2 %7.1f (circular %7.1f)%s %s" % ( count, name, len(t), rec["P"], rec["e"], rec["K"], rec["dchi2"], rec["dchi2_circular"], " FAP %.1e" % rec["fap"] if "fap" in rec else "", rec["flags"]), flush=True) print("done: %d stars" % len(names), flush=True) if not part: planets_eccentric_merge() def planets_eccentric_records(): """Every star's best orbit the eccentric search's shares hold under RESULTS/eccentric, one a star, a line a write cut short left out.""" recs = {} for f in sorted(glob.glob(os.path.join(planets_RESULTS, "eccentric", "stars*.jsonl"))): for x in open(f, encoding="utf-8"): try: r = json.loads(x) except ValueError: continue recs[r["name"]] = r return list(recs.values()) def planets_eccentric_merge(): """The eccentric search's shares joined into RESULTS/eccentric/candidates.csv: every star's best orbit with a false-alarm level below 0.01, the orbits without a flag first, each in order of false-alarm level. Beside the search's own flags, an orbit is flagged whose periastron would lie within two stellar radii (the radius taken as the spectral type's mass to the power 0.8) and whose period lies within 5 per cent of a year or half a year.""" recs = planets_eccentric_records() for r in recs: m1 = planets_mass(r["sptype"]) flags = [r["flags"]] if r["flags"] else [] if (m1 * (r["P"] / 365.25) ** 2) ** (1.0 / 3.0) * (1.0 - r["e"]) < 2.0 * 0.00465 * m1 ** 0.8: flags.append("periastron within 2 stellar radii") if any(abs(r["P"] / y - 1.0) < 0.05 for y in (365.25, 182.63)): flags.append("near a year or half") r["flags"] = "; ".join(flags) cand = sorted((r for r in recs if r.get("fap", 1.0) < 0.01), key=lambda r: (bool(r["flags"]), r["fap"])) keys = ["name", "sptype", "nights", "span_d", "P", "e", "K", "msini_mearth", "dchi2", "dchi2_circular", "fap", "null_mean", "null_sd", "flags", "census_periods"] planets_write(os.path.join(planets_RESULTS, "eccentric", "candidates.csv"), [{k: r.get(k, "") for k in keys} for r in cand], keys) print("%d stars searched, %d with an orbit below a false-alarm level of 0.01" % (len(recs), len(cand)), flush=True) for r in cand: print("%-12s %-8s n %4d | P %9.3f e %.2f K %6.2f msini %7.1f ME | dchi2 %7.1f circular %7.1f | FAP %.1e | %s" % ( r["name"], r["sptype"][:8], r["nights"], r["P"], r["e"], r["K"], r["msini_mearth"], r["dchi2"], r["dchi2_circular"], r["fap"], r["flags"]), flush=True) # stars whose answers are known: planets with periods (d) and published semi-amplitudes (m/s), refuted signals and disputed ones planets_BENCHMARK = { "GJ551": dict(label="Proxima Cen", planets=[("Proxima Cen b", 11.1868, 1.24), ("Proxima Cen d", 5.1224, 0.39)], disputed=[("Proxima Cen c", 1928.0, 1.2)], false=[]), # alpha Cen B from its 2023 ESPRESSO series alone; its HARPS series scatter by 36 m/s about the binary orbit's quadratic "GJ559B": dict(label="alpha Cen B", planets=[], disputed=[], false=[("alpha Cen Bb", 3.2357, 0.51)], series="ESPRESSO19"), "GJ559A": dict(label="alpha Cen A", planets=[], disputed=[], false=[]), } def planets_match(found, P): """The found signal at a period P: 'recovered' within 2 per cent, 'alias' within 2 per cent of one of its 1-day or 1-year aliases, else None; with the signal.""" for f in found: if abs(float(f["P"]) / P - 1.0) < 0.02: return "recovered", f for f in found: if any(fa > 0 and abs(1.0 / float(f["P"]) / fa - 1.0) < 0.02 for fa in (abs(1.0 / P + s * b) for b in (1.0 / 1.0027, 1.0 / 365.25) for s in (1, -1))): return "alias", f return None, None def planets_benchmark_job(t, y, e, g, S, HA, progs): """The census's search of the Sun's velocities Y (times T, errors E, series G, S, H alpha and the series' labels PROGS) as a planets_search_many job.""" nan = np.full(len(t), np.nan) return ("Sun", np.column_stack([t, y, e, g, S, HA, nan, nan, nan, nan]).tolist(), progs, dict(SpType="G2V", RAJ2000="", DEJ2000=""), {}, lambda *a: None, False, None) def planets_benchmark_found(got): """A search's found signals: their periods, amplitudes, false-alarm levels and flags.""" return [dict(P=float(r["P"]), K=float(r["K"]), fap=float(r["fap"]), flags=r["flags"]) for r in got[1] if r["kind"] == "found"] if got else [] def planets_benchmark(sun=None, periods=(2.0, 3.5, 6.0, 10.0, 17.0, 30.0, 50.0, 85.0, 150.0, 250.0, 450.0, 800.0), amplitudes=(0.5, 1.0, 1.5, 2.0, 3.0, 5.0, 8.0), phases=4, seed=13): """The census run on stars whose answers are known, to RESULTS/benchmark.json. Proxima and alpha Cen A and B, read as the census reads them with the archive's planets left out (alpha Cen B from its ESPRESSO series alone), each found signal set against their planets, the false planet once claimed for alpha Cen B and the disputed Proxima c, and every other found signal kept with its flags as a false alarm. Then the Sun, from its daily velocities from HARPS (SUN, by default the solar mode's velocities.csv, made by its plan, days and lbl steps where it is missing): its own velocities as observed, where DE440's planets project onto the line from the Sun to the Earth at Jupiter's and Saturn's synodic periods (398.9 and 378.1 d); the same less DE440's, the Sun's activity alone, where every found signal is a false alarm; and that activity with circular planets laid into it at PERIODS and AMPLITUDES, PHASES each, each recovered where a found signal lies within 2 per cent of its period, which gives the census's completeness against a real star's noise.""" stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} planets_of, host_of = planets_known(planets_path("known.csv")) names = [n for n in planets_BENCHMARK if n in stars] bank, dace = planets_bank_series(set(names)), planets_dace_series(set(names)) out = dict(stars={}) for name in names: truth = planets_BENCHMARK[name] rows, labels = planets_series(name, dace, bank, stars[name].get("SpType")) if truth.get("series"): kept = [k for k, lab in enumerate(labels) if truth["series"] in lab] rows = [r[:3] + [float(kept.index(int(r[3])))] + r[4:] for r in rows if int(r[3]) in kept] labels = [labels[k] for k in kept] got = planets_search(name, rows, labels, stars[name], planets_of, host_of, blind=True) if rows else None if got is None: continue found = [r for r in got[1] if r["kind"] == "found"] used = set() res = dict(label=truth["label"], nights=got[0]["nights"], span_d=got[0]["span_d"], jitter=got[0]["jitter"], planets=[], false=[], disputed=[], others=[]) for kind in ("planets", "false", "disputed"): for pl_name, P, K in truth[kind]: status, f = planets_match(found, P) if f is not None: used.add(id(f)) res[kind].append(dict(name=pl_name, P=P, K=K, status=status or "not found", found_P=float(f["P"]) if f else None, found_K=float(f["K"]) if f else None, flags=f["flags"] if f else None)) res["others"] = [dict(P=float(f["P"]), K=float(f["K"]), fap=float(f["fap"]), flags=f["flags"]) for f in found if id(f) not in used] out["stars"][name] = res print("%-12s %4d nights: planets %s; false %s; disputed %s; other signals %s" % ( truth["label"], res["nights"], [(x["name"], x["status"]) for x in res["planets"]], [(x["name"], x["status"]) for x in res["false"]], [(x["name"], x["status"]) for x in res["disputed"]], ["%.2f d%s" % (x["P"], " (%s)" % x["flags"] if x["flags"] else "") for x in res["others"]]), flush=True) sun = sun or os.path.join(solar_RESULTS, "HARPS_Sun", "velocities.csv") if not os.path.exists(sun): solar_plan("Sun", "HARPS"), solar_days("Sun", "HARPS"), solar_lbl("Sun", "HARPS") if os.path.exists(sun): rows_ = list(csv.DictReader(open(sun, encoding="utf-8"))) t = np.array([float(r["mjd"]) for r in rows_]) v = np.array([float(r["rv"]) for r in rows_]) e = np.array([float(r["rv_err"]) for r in rows_]) de = np.array([float(r["de440"]) for r in rows_]) S = np.array([float(r["S"]) for r in rows_]) HA = np.array([float(r["Halpha"]) for r in rows_]) progs = sorted({r["programme"] for r in rows_}) g = np.array([float(progs.index(r["programme"])) for r in rows_]) # the days the solar mode's fit sets aside, beyond 5 robust standard deviations of the velocities less DE440's within each programme r_ = v - de for k in np.unique(g): m = g == k r_[m] -= np.median(r_[m]) ok = np.abs(r_) < 5.0 * 1.4826 * np.median(np.abs(r_)) t, v, e, de, S, HA, g = t[ok], v[ok], e[ok], de[ok], S[ok], HA[ok], g[ok] sun_res = {} for label, got in zip(("observed", "activity"), planets_search_many([planets_benchmark_job(t, y, e, g, S, HA, progs) for y in (v, v - de)])): sun_res[label] = planets_benchmark_found(got) print("Sun, %s: %s" % (label, ["%.1f d %.2f m/s%s" % (f["P"], f["K"], " (%s)" % f["flags"] if f["flags"] else "") for f in sun_res[label]]), flush=True) sun_res["observed_synodic"] = {name_: planets_match([dict(P=f["P"]) for f in sun_res["observed"]], P)[0] or "not found" for name_, P in (("Jupiter", 398.88), ("Saturn", 378.09))} rng = np.random.default_rng(seed) draws = [(i, j, P, v - de + K * np.sin(2 * np.pi * t / P + rng.uniform(0, 2 * np.pi))) for i, P in enumerate(periods) for j, K in enumerate(amplitudes) for _ in range(phases)] grid = np.zeros((len(periods), len(amplitudes))) for (i, j, P, _), got in zip(draws, planets_search_many([planets_benchmark_job(t, y, e, g, S, HA, progs) for _, _, _, y in draws])): grid[i, j] += (planets_match(planets_benchmark_found(got), P)[0] == "recovered") / phases for i, P in enumerate(periods): print(" Sun with a planet laid in at %6.1f d: recovered %s at %s m/s" % (P, list(np.round(grid[i], 2)), list(amplitudes)), flush=True) sun_res.update(days=len(t), first=round(float(t.min()), 1), last=round(float(t.max()), 1), periods=list(periods), amplitudes=list(amplitudes), recovered=grid.tolist()) out["sun"] = sun_res json.dump(out, open(os.path.join(planets_RESULTS, "benchmark.json"), "w"), separators=(",", ":")) def planets_census(part=None, blind=False, hosts=False): """A share of the census: the stars whose rank by number of velocities is K modulo N for --part K/N, every star otherwise; each star's record to RESULTS/census/stars[.partKofN].jsonl and its signals to RESULTS/census/signals[.partKofN].csv. BLIND searches without the archive's planets (into RESULTS/census_blind/), and HOSTS keeps to the stars the archive lists planets for. A star with no bank velocities, as in a root that planets_targets set up, is searched where its DACE velocities cover 15 nights or more over 100 days or more. Run on every star, without PART or BLIND, the census ends by joining its results (planets_merge).""" names, stars, planets_of, host_of = planets_share(part, hosts) bank = planets_bank_series(set(names)) dace = planets_dace_series(set(names)) mark = (".part%sof%s" % tuple(part.split("/"))) if part else "" folder = os.path.join(planets_RESULTS, "census_blind" if blind else "census") os.makedirs(folder, exist_ok=True) jobs = [] for name in names: rows, labels = planets_series(name, dace, bank, stars.get(name, {}).get("SpType")) if rows: jobs.append((name, rows, labels, stars.get(name, {}), planets_of, host_of, blind, None)) # a whole census takes the place of any shares before it if not part: for f in glob.glob(os.path.join(folder, "*.part*of*")): os.remove(f) n_sig = n_new = done = 0 t0 = time.time() with open(os.path.join(folder, "stars%s.jsonl" % mark), "w", encoding="utf-8") as out_stars, \ open(os.path.join(folder, "signals%s.csv" % mark), "w", newline="", encoding="utf-8") as out_sig: w = csv.DictWriter(out_sig, fieldnames=planets_SIGNAL_KEYS, extrasaction="ignore") w.writeheader() # each star written and printed as its search ends for i, got in planets_search_stream(jobs): done += 1 if got is None: continue out_stars.write(json.dumps(got[0]) + "\n") w.writerows(got[1]) out_stars.flush() out_sig.flush() new = [r for r in got[1] if r["kind"] == "found"] n_sig, n_new = n_sig + len(got[1]), n_new + len(new) print("%5d/%d %6.0f s %-14s %4d nights %s" % (done, len(jobs), time.time() - t0, got[0]["name"], got[0]["nights"], "; ".join( "%s %.4g d %.2f m/s%s" % ("new" if r["kind"] == "found" else "known", r["P"], r["K"], " [%s]" % r["flags"] if r["flags"] else "") for r in got[1]) or "nothing"), flush=True) print("done: %d stars, %d signals, %d of them new" % (len(names), n_sig, n_new), flush=True) if not part and not blind: planets_merge() def planets_s_test(times, svals, P): """A period's power in a star's S index: the series given, each less its median and averaged per night, searched by a Lomb-Scargle periodogram from 1.5 d to twice their span; the highest peak with its false-alarm level, and the highest power within 10 per cent of P, P/2 or 2P with its level.""" t, s = [], [] for tk, sk in zip(times, svals): tk, sk = np.asarray(tk), np.asarray(sk) _, inv = np.unique(np.floor(tk + 0.3), return_inverse=True) tn, sn = np.bincount(inv, tk) / np.bincount(inv), np.bincount(inv, sk) / np.bincount(inv) t += list(tn) s += list(sn - np.median(sn)) if len(t) < 12: return dict(s_nights=len(t)) t, s = np.array(t), np.array(s) f = np.linspace(1.0 / (2.0 * (t.max() - t.min())), 1.0 / 1.5, 40000) p = gpu_host(gpu_gls(t, s, None, f)) fap = lambda x: float(gpu_baluev(x, f[-1], t)) k = int(np.argmax(p)) best = None for mult in (1.0, 0.5, 2.0): near = np.abs(1.0 / f / (P * mult) - 1.0) < 0.1 if near.any(): kk = int(np.argmax(np.where(near, p, -1))) if best is None or p[kk] > best[1]: best = (1.0 / f[kk], p[kk], mult) out = dict(s_nights=len(t), s_peak_d=round(1.0 / f[k], 2), s_peak_fap="%.1e" % fap(p[k])) if best: out.update(s_near_d=round(best[0], 2), s_near_mult=best[2], s_near_power=round(float(best[1]), 3), s_near_fap="%.1e" % fap(best[1])) return out def planets_write_stars(path, stars): """The census's star records written to PATH as CSV, one row per star, its lists and dicts as compact JSON.""" keys = list(dict.fromkeys(k for s in stars for k in s)) planets_write(path, [{k: json.dumps(v, separators=(",", ":")) if isinstance(v, (dict, list)) else v for k, v in s.items()} for s in stars], keys) def planets_merge(): """The census's shares joined into RESULTS/signals.csv and RESULTS/stars.csv, one row per star with its lists and dicts as compact JSON, each found signal without flags given its period's power in the star's S index from every series DACE gives one for (planets_s_test); a decided table it replaces kept as RESULTS/signals_decided.csv, which the publication reads until this one is decided.""" table = os.path.join(planets_RESULTS, "signals.csv") if os.path.exists(table) and "reason" in open(table, encoding="utf-8").readline().strip().split(","): shutil.copyfile(table, os.path.join(planets_RESULTS, "signals_decided.csv")) sig, stars = [], [] for f in sorted(glob.glob(os.path.join(planets_RESULTS, "census", "signals*.csv"))): sig += planets_read(f) for f in sorted(glob.glob(os.path.join(planets_RESULTS, "census", "stars*.jsonl"))): stars += [json.loads(x) for x in open(f, encoding="utf-8")] planets_write_stars(os.path.join(planets_RESULTS, "stars.csv"), stars) S = {} for r in csv.DictReader(open(planets_path("dace.csv"), encoding="utf-8")): if r["smw"] not in ("", "nan") and 0 < planets_num(r["smw"]) < 5: S.setdefault(r["name"], {}).setdefault(r["inst"] + " " + r["drs"] + " " + r["mode"], []).append((float(r["mjd"]), float(r["smw"]))) for r in sig: if r["kind"] == "found" and not r["flags"]: series = [v for v in S.get(r["name"], {}).values() if len(v) >= 5] r.update(planets_s_test([[x[0] for x in v] for v in series], [[x[1] for x in v] for v in series], float(r["P"]))) planets_write(os.path.join(planets_RESULTS, "signals.csv"), sig, planets_SIGNAL_KEYS + planets_S_KEYS) print("%d stars modelled, %d signals, %d found, %d without flags" % (len(stars), len(sig), sum(1 for r in sig if r["kind"] == "found"), sum(1 for r in sig if r["kind"] == "found" and not r["flags"])), flush=True) planets_S_KEYS = ["s_nights", "s_peak_d", "s_peak_fap", "s_near_d", "s_near_mult", "s_near_power", "s_near_fap"] def planets_write_calibration(res, rows, extra, folder=None): """The calibration's summary RES written to FOLDER/calibration.json (FOLDER by default RESULTS), its catalogued planets ROWS to calibration_planets.csv, and its found signals that match no catalogued planet or alias, EXTRA, to calibration_unmatched.csv.""" folder = folder or planets_RESULTS json.dump(res, open(os.path.join(folder, "calibration.json"), "w"), separators=(",", ":")) planets_write(os.path.join(folder, "calibration_planets.csv"), rows, ["star", "planet", "P", "K", "nights", "rms", "snr_expected", "status", "found_P", "found_K"]) planets_write(os.path.join(folder, "calibration_unmatched.csv"), extra, ["star", "P", "K", "msini_mearth", "fap", "flags"]) def planets_calibrate(): """The blind census scored on the archive's planets, to RESULTS/calibration.json with its planets and unmatched signals as CSV (planets_write_calibration). A catalogued planet of a blind star with a semi-amplitude in the archive is recovered where a found signal lies within 2 per cent of its period, found at an alias where one lies within 2 per cent of the frequency of one of its 1-day or 1-year aliases, and missed otherwise; its expected signal-to-noise is its catalogue K over the star's residual scatter times sqrt(2/N) for N nights. The recovered share is given in bins of expected signal-to-noise and of period, and every found signal that matches no catalogued planet nor an alias of one is listed. The blind census of the archive's hosts is run first where it has not been.""" if not glob.glob(os.path.join(planets_RESULTS, "census_blind", "stars*.jsonl")): planets_census(blind=True, hosts=True) stars, sig = [], [] for f in sorted(glob.glob(os.path.join(planets_RESULTS, "census_blind", "stars*.jsonl"))): stars += [json.loads(x) for x in open(f, encoding="utf-8")] for f in sorted(glob.glob(os.path.join(planets_RESULTS, "census_blind", "signals*.csv"))): sig += planets_read(f) found = {} for r in sig: if r["kind"] == "found": found.setdefault(r["name"], []).append(r) aliases = lambda P: [abs(1.0 / P + s * b) for b in (1.0 / 1.0027, 1.0 / 365.25) for s in (1, -1)] rows, extra = [], [] for s in stars: fs = found.get(s["name"], []) matched = set() for c in s.get("catalogue", []): P, K = float(c["P"]), planets_num(c["K"]) status, hit = "missed", None for i, f in enumerate(fs): if abs(float(f["P"]) / P - 1.0) < 0.02: status, hit = "recovered", i break if hit is None: for i, f in enumerate(fs): if any(fa > 0 and abs(1.0 / float(f["P"]) / fa - 1.0) < 0.02 for fa in aliases(P)): status, hit = "alias", i break if hit is not None: matched.add(hit) snr = K / (s["rms_resid"] * math.sqrt(2.0 / s["nights"])) if math.isfinite(K) and s["rms_resid"] > 0 else float("nan") rows.append(dict(star=s["name"], planet=c["name"], P=round(P, 4), K=K, nights=s["nights"], rms=s["rms_resid"], snr_expected=round(snr, 1), status=status, found_P=float(fs[hit]["P"]) if hit is not None else None, found_K=float(fs[hit]["K"]) if hit is not None else None)) extra += [dict(star=s["name"], P=float(f["P"]), K=float(f["K"]), msini_mearth=float(f["msini_mearth"]), fap=float(f["fap"]), flags=f["flags"]) for i, f in enumerate(fs) if i not in matched] def share(sel): n = len(sel) return dict(n=n, recovered=sum(r["status"] == "recovered" for r in sel), alias=sum(r["status"] == "alias" for r in sel), fraction=round(sum(r["status"] == "recovered" for r in sel) / n, 3) if n else None) scored = [r for r in rows if math.isfinite(r["snr_expected"])] by_snr = {"%g-%g" % (lo, hi): share([r for r in scored if lo <= r["snr_expected"] < hi]) for lo, hi in ((0, 3), (3, 5), (5, 10), (10, 20), (20, 1e9))} by_period = {"%g-%g d" % (lo, hi): share([r for r in scored if lo <= r["P"] < hi and r["snr_expected"] >= 5]) for lo, hi in ((1, 10), (10, 100), (100, 1000), (1000, 1e9))} res = dict(stars=len(stars), planets=len(rows), scored=len(scored), by_expected_snr=by_snr, by_period_above_snr5=by_period, extra_signals=len(extra), extra_unflagged=sum(1 for x in extra if not x["flags"])) planets_write_calibration(res, rows, extra) print("%d host stars, %d catalogued planets, %d with a catalogue K" % (len(stars), len(rows), len(scored)), flush=True) for label, d in by_snr.items(): print(" expected S/N %-8s %4d planets: %4d recovered (%s), %3d at an alias" % (label, d["n"], d["recovered"], d["fraction"], d["alias"]), flush=True) for label, d in by_period.items(): print(" S/N above 5, P %-12s %4d planets: %4d recovered (%s), %3d at an alias" % (label, d["n"], d["recovered"], d["fraction"], d["alias"]), flush=True) 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_own_spectra(name, least_snr): """The rows of a star's own spectra in a root that lists them (bank.json's spectra, ROOT/spectra.csv), above the signal-to-noise ratio LEAST_SNR, as an archive's listing gives them; None in any other root.""" if not planets_BANK_INFO.get("spectra"): return None return [dict(src=planets_BANK_INFO["spectra"], id=r["seq"], t_min=float(r["mjd"]), snr=planets_num(r["snr"])) for r in planets_read(planets_path("spectra.csv")) if r["name"] == name and planets_num(r["snr"]) > least_snr] def planets_zero_of(t): """The zero point at the times T of a root that keeps a curve of it (ROOT/zero_points.csv, planets_zero_curve), that its bank has had taken out; zeros in any other root.""" path = planets_path("zero_points.csv") if not (planets_BANK_INFO.get("spectra") and os.path.exists(path)): return np.zeros(len(t)) rows = planets_read(path) return np.interp(t, [float(r["mjd"]) for r in rows], [float(r["zero"]) for r in rows]) 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 try: m = re.search(r"(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)", str(fits.getheader(path).get("HIERARCH ESO DRS CAL TH FILE", ""))) cal = datetime.datetime.strptime(m.group(1), "%Y-%m-%dT%H:%M:%S") return mjd - (cal - datetime.datetime(1858, 11, 17)).total_seconds() / 86400.0 except Exception: return float("nan") def planets_lbl(name, per_night=1, streams=12, keep=False, most=0, ra=None, dec=None, least=10, listing=None, inst="HARPS", ccf=False): """A star's line-by-line velocities and activity from its public HARPS spectra (or INST's), to ROOT/lbl/.lbl.npz; with CCF, its cross-correlation velocities from the same spectra beside them, to ROOT/ccf/.npz (binaries_velocities: against the M-dwarf template, then against the star's own lines at those velocities), with each spectrum's line-by-line error. The star's HARPS Phase 3 spectra above a signal-to-noise ratio of 20, the PER_NIGHT of highest signal to noise from each night, are fetched over STREAMS connections and read as air wavelengths in the barycentric frame, moved by the star's systemic velocity alone and put on a grid uniform in log wavelength at 0.4 km/s from 3800 to 6880 A, each divided by its running median over 1001 samples. The median of all of them is the template; its lines are the minima at least 4 per cent deep, each taken over the samples within 1.2 times its half-depth width, away from the telluric bands, the sodium sky lines and any sample a spectrum lacks. Each spectrum's velocity in each line is Bouchy's derivative estimate, the residual against the template projected on the template's derivative with the line's own linear continuum solved beside it, with its photon error. A spectrum's velocity is the weighted mean of its lines after lines more than 5 sigma from their median are set aside, and an error-weighted iteration gives each line a jitter (lbl_velocities). The Ca II H and K index and the H alpha index (lbl_indices) are measured in each spectrum before the telluric bands are set aside. Each line's velocities are correlated with the S index across the spectra; the lines whose correlation passes p < 0.01 are the activity-sensitive set, and a second velocity is made from the others. Each spectrum's calibration age, the days since the ThAr exposure that gave its wavelengths, is kept beside its velocity: the archive's one-dimensional spectra carry the spectrograph's drift since that exposure uncorrected. The spectra are deleted unless KEEP. RA and DEC place a star the bank lacks; fewer than LEAST spectra stop it. LISTING, the star's HARPS spectra above a signal-to-noise ratio of 20 where they are already listed (archive_eso_listings), replaces the archive query.""" if ra is None: star = next(r for r in planets_read(planets_path("bank_stars.csv")) if r["Name"] == name) ra, dec = float(star["RAJ2000"]), float(star["DEJ2000"]) tag = archive_tag(name) folder = planets_path("spectra", tag) own = planets_own_spectra(name, 20.0) if listing is None and inst == "HARPS" else None rows = listing if listing is not None else own if own is not None else archive_eso_listing(ra, dec, inst, min_snr=20.0) nights = {} for r in rows: nights.setdefault(math.floor(float(r["t_min"]) + 0.3), []).append(r) rows = sorted((r for rs in nights.values() for r in sorted(rs, key=lambda r: -(archive_num(r["snr"]) or 0))[:per_night]), key=lambda r: float(r["t_min"])) if most and len(rows) > most: rows = [rows[int(i)] for i in np.unique(np.linspace(0, len(rows) - 1, most).round())] spec = [] paths = archive_eso_fetch(rows, folder, streams=2 if own is not None else streams) for p, s in zip(paths, spectra_load_many(paths)): if s is not None: s[3]["cal_age"] = planets_cal_age(p, s[3]["mjd"]) spec.append(s) if len(spec) < least: raise SystemExit("%s: %d spectra" % (name, len(spec))) rvs = [s[3]["rv"] for s in spec if s[3].get("rv") is not None] vsys = float(np.median(rvs)) if rvs else 0.0 grid = lbl_grid() F, E, _ = spectra_onto([(w / (1.0 + vsys / spectra_C), f, e) for w, f, e, meta in spec], grid, 1001, clean_errors=True, dtype=np.float32) for i, (w, f, e, meta) in enumerate(spec): for sky in spectra_SKY: F[i, np.abs(grid - sky * (1.0 + meta.get("berv", 0.0) / spectra_C) / (1.0 + vsys / spectra_C)) < 0.15] = np.nan # the indices first, H alpha lying inside a telluric band S, HA = lbl_indices(F, grid) for lo, hi in spectra_BANDS["optical"]["telluric"]: F[:, (grid > lo) & (grid < hi)] = np.nan lines, V, SV, s2 = lbl_velocities(F, E) rv = np.nansum(V / s2, 1) / np.nansum(1.0 / s2, 1) rv_err = 1.0 / np.sqrt(np.nansum(1.0 / s2, 1)) corr, pval = lbl_corr(V - rv[:, None], S, 10) quiet = ~(pval < 0.01) rv_q = np.nansum(V[:, quiet] / s2[:, quiet], 1) / np.nansum(1.0 / s2[:, quiet], 1) rv_q_err = 1.0 / np.sqrt(np.nansum(1.0 / s2[:, quiet], 1)) t = np.array([s[3]["mjd"] for s in spec]) o = np.argsort(t) os.makedirs(planets_path("lbl"), exist_ok=True) # a root's own spectra keep its zero point out of them as its bank does if own is not None: rv, rv_q = rv - planets_zero_of(t), rv_q - planets_zero_of(t) np.savez_compressed(planets_path("lbl", tag + ".lbl.npz"), mjd=t[o], rv=rv[o], rv_err=rv_err[o], rv_quiet=rv_q[o], rv_quiet_err=rv_q_err[o], S=S[o], upgrade=planets_UPGRADE if own is not None else planets_HARPS_UPGRADE, Halpha=HA[o], snr=np.array([s[3].get("snr", np.nan) for s in spec], float)[o], cal_age=np.array([s[3].get("cal_age", np.nan) for s in spec], float)[o], V=V[o].astype(np.float32), SV=SV[o].astype(np.float32), line_lambda=grid[lines[:, 2]], line_corr=corr, line_p=pval, vsys=vsys) if ccf: # the search spans 400 km/s either side, as halo and cluster stars move at up to a few hundred v, height = binaries_velocities(spec, binaries_line_depths(spec, binaries_velocities(spec, np.load(binaries_template_path()), vmax=400)[0]), vmax=400) os.makedirs(planets_path("ccf"), exist_ok=True) np.savez_compressed(planets_path("ccf", tag + ".npz"), mjd=t[o], v=1000.0 * v[o], height=height[o], rv_err=rv_err[o], snr=np.array([s[3].get("snr", np.nan) for s in spec], float)[o]) print("%s: %d spectra, %d lines (%d activity-sensitive); rms %.2f m/s (median error %.2f), quiet lines %.2f m/s (%.2f)" % ( name, len(spec), len(lines), int((~quiet).sum()), float(np.std(rv - np.median(rv))), float(np.median(rv_err)), float(np.std(rv_q - np.median(rv_q))), float(np.median(rv_q_err))), flush=True) if not keep: shutil.rmtree(folder, ignore_errors=True) def planets_by_night(t, v, e): """Velocities averaged per night, weighted by inverse variance: times, velocities and errors.""" _, inv = np.unique(np.floor(np.asarray(t) + 0.3), return_inverse=True) w = 1.0 / np.asarray(e) ** 2 W = np.bincount(inv, w) return np.bincount(inv, w * t) / W, np.bincount(inv, w * v) / W, 1.0 / np.sqrt(W) def planets_sinusoids(t, v, e, groups, periods): """Offsets for each group and a sinusoid at each period fitted by least squares: coefficients, residuals, covariance.""" cols = [(groups == g).astype(float) for g in np.unique(groups)] for P in periods: cols += [np.cos(2 * np.pi * t / P), np.sin(2 * np.pi * t / P)] A = np.column_stack(cols) / e[:, None] c = np.linalg.lstsq(A, v / e, rcond=None)[0] return c, v - (A * e[:, None]) @ c, np.linalg.pinv(A.T @ A) def planets_amplitude(c, cov): """The last sinusoid's semi-amplitude and phase (deg) with their errors.""" a, b = c[-2], c[-1] K = math.hypot(a, b) eK = math.sqrt(max(a * a * cov[-2, -2] + b * b * cov[-1, -1] + 2 * a * b * cov[-2, -1], 0.0)) / max(K, 1e-12) eph = math.degrees(math.sqrt(max(b * b * cov[-2, -2] + a * a * cov[-1, -1] - 2 * a * b * cov[-2, -1], 0.0)) / max(K * K, 1e-12)) return K, eK, math.degrees(math.atan2(b, a)) % 360.0, eph def planets_reduction(t, v, e, groups, cands): """One velocity set tested: sinusoids taken out one at a time at the highest peak of a generalised Lomb-Scargle periodogram from 1.2 d to twice the span while its Baluev false-alarm level stays below 1e-3, up to six, each fit joint with those before; then each candidate period's power and level in the residuals of all the others, the power of its two 1-day aliases beside it, and its sinusoid fitted to the first and the second half of the nights.""" span = t.max() - t.min() freq = np.linspace(1.0 / (2.0 * span), 1.0 / 1.2, 60000) jit, found = 0.0, [] for _ in range(6): _, r, _ = planets_sinusoids(t, v, np.hypot(e, jit), groups, found) jit = math.sqrt(max(np.mean(r ** 2) - np.mean(e ** 2), 0.0)) p = gpu_host(gpu_gls(t, r, np.hypot(e, jit), freq)) k = int(np.argmax(p)) if float(gpu_baluev(p[k], freq[-1], t, np.hypot(e, jit))) > 1e-3: break found.append(1.0 / freq[k]) sig = np.hypot(e, jit) out = dict(n=len(t), span=round(span), jitter=round(jit, 2), found=[round(P, 3) for P in found], candidates={}) for P in cands: # the others are the found periods away from P and from its 1-day aliases others = [x for x in found if abs(x / P - 1.0) > 0.03 and all(abs(1.0 / x - abs(1.0 / P + s / 1.0027)) > 0.02 / P for s in (1, -1))] _, r, _ = planets_sinusoids(t, v, sig, groups, others) p = gpu_host(gpu_gls(t, r, sig, freq)) kk = int(np.argmax(np.where(np.abs(freq * P - 1.0) < 0.02, p, -1))) Pb = 1.0 / freq[kk] aliases = {} for sgn in (1, -1): fa = abs(1.0 / P + sgn / 1.0027) na = np.abs(freq / fa - 1.0) < 0.02 / max(1.0, 1.0 / (fa * P)) if freq[0] < fa < freq[-1] and na.any(): aliases["%.3f" % (1.0 / fa)] = round(float(p[np.argmax(np.where(na, p, -1))]), 3) halves = [] for sel in (t <= np.median(t), t > np.median(t)): if sel.sum() >= 8: c, _, cov = planets_sinusoids(t[sel], r[sel], sig[sel], groups[sel], [Pb]) K, eK, ph, eph = planets_amplitude(c, cov) halves.append(dict(n=int(sel.sum()), K=round(K, 2), eK=round(eK, 2), phase=round(ph, 1), ephase=round(eph, 1))) out["candidates"]["%g" % P] = dict(P_peak=round(Pb, 3), power=round(float(p[kk]), 3), aliases=aliases, halves=halves, fap="%.1e" % float(gpu_baluev(p[kk], freq[-1], t, sig))) return out def planets_indicator(t, x, cands): """An indicator's periodogram from 1.2 d to twice its span: its highest peak, and its power and false-alarm level within 5 per cent of each period.""" ok = np.isfinite(x) if ok.sum() < 12 or np.std(x[ok]) == 0: return None t, x = t[ok], x[ok] freq = np.linspace(1.0 / (2.0 * (t.max() - t.min())), 1.0 / 1.2, 60000) p = gpu_host(gpu_gls(t, x, None, freq)) fap = lambda y: "%.1e" % float(gpu_baluev(y, freq[-1], t)) k = int(np.argmax(p)) out = dict(top_d=round(1.0 / freq[k], 2), top_fap=fap(p[k])) for P in cands: kk = int(np.argmax(np.where(np.abs(freq * P - 1.0) < 0.05, p, -1))) out["%g" % P] = dict(power=round(float(p[kk]), 3), fap=fap(p[kk])) return out def planets_vet(jobs, show=True): """Signals tested, each star's to RESULTS/vet/.json; JOBS are pairs of a star and its periods. Three velocity sets of the same HARPS spectra, each averaged per night: the bank's SERVAL velocities (an offset across the fibre upgrade), DACE's HARPS pipeline velocities (an offset between HARPS03 and HARPS15, each cleaned as the census cleans), and, where the star's line-by-line file is present, its velocities from all lines and from the lines that do not follow the S index, the spectra wavelength-calibrated more than 30 days before they were taken left out; each is tested by planets_reduction. The bank's indicators, DACE's S index from every series and the line-by-line S and H alpha are searched by planets_indicator. Each instrument family outside HARPS with 8 nights or more is fitted at each period with its own offsets, freely and with the phase of the bank's sinusoid held, so that another telescope's velocities test the orbit independently. Gaia DR3's RUWE and non-single-star solutions close it. Returns the records by star; with SHOW prints each signal's tests on one line, and a single star's in full.""" names = sorted({name for name, _ in jobs}) stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} bank, raw, dace = planets_bank_series(set(names)), planets_bank_raw(set(names)), planets_dace_series(set(names)) gaia = dict(zip(names, archive_pmap(lambda n: archive_gaia_star(float(stars[n]["RAJ2000"]), float(stars[n]["DEJ2000"]), archive_num(stars[n].get("Vmag")), physical=False), names))) sols = archive_gaia_solutions([g["source_id"] for g in gaia.values() if g]) os.makedirs(os.path.join(planets_RESULTS, "vet"), exist_ok=True) out = {} for name, periods in jobs: res = planets_vet_star(name, periods, bank.get(name, []), raw.get(name, []), dace.get(name, {})) g = gaia[name] if g: sol = sols[str(g["source_id"])] res["gaia"] = dict(source_id=g["source_id"], ruwe=g.get("ruwe"), non_single_star=g.get("non_single_star"), solutions=[r.get("nss_solution_type") for kind in ("orbit", "acceleration", "trend") for r in sol[kind]]) json.dump(res, open(os.path.join(planets_RESULTS, "vet", archive_tag(name) + ".json"), "w"), separators=(",", ":")) out[name] = res if show and len(jobs) == 1: planets_vet_print(res) for P in periods if show else (): print(planets_vet_line(res, P), flush=True) return out def planets_vet_star(name, periods, rows, raw_bank, dace, mover=None): """One star's vet record at PERIODS from its bank velocities, bank rows and DACE series, without Gaia, each time taken through MOVER where given (planets_night_mover).""" res = dict(name=name, periods=periods, sets={}, indicators={}, other_instruments={}) phases = {} mv = mover or (lambda t: np.asarray(t, float)) if rows: x = np.array(rows) sets_t, sets_v, sets_e, sets_g = [], [], [], [] for g, sel in enumerate((x[:, 0] < planets_UPGRADE, x[:, 0] >= planets_UPGRADE)): if sel.sum() < 3: continue tn, vn, en = planets_by_night(mv(x[sel, 0]), x[sel, 1], x[sel, 2]) sets_t.append(tn), sets_v.append(vn), sets_e.append(en), sets_g.append(np.full(len(tn), g)) t, v, e, g = (np.concatenate(z) for z in (sets_t, sets_v, sets_e, sets_g)) o = np.argsort(t) t, v, e, g = t[o], v[o], e[o], g[o] label = planets_bank_label() res["sets"][label] = planets_reduction(t, v, e, g, periods) for P in periods: c, _, cov = planets_sinusoids(t, v, np.hypot(e, res["sets"][label]["jitter"]), g, [P]) phases[P] = math.radians(planets_amplitude(c, cov)[2]) bt = mv(np.array([float(r["BJD"]) - 2400000.5 for r in raw_bank])) for key, col in (("CRX", "CRX"), ("dLW", "dLW"), ("Halpha", "Halpha"), ("NaD1", "NaD1"), ("FWHM", "FWHMDRS"), ("BIS", "BIS")): xs = np.array([planets_num(r[col]) for r in raw_bank]) ok = np.isfinite(xs) if ok.sum() >= 12: _, inv = np.unique(np.floor(bt[ok] + 0.3), return_inverse=True) res["indicators"]["bank " + key] = planets_indicator(np.bincount(inv, bt[ok]) / np.bincount(inv), np.bincount(inv, xs[ok]) / np.bincount(inv), periods) # the same spectra's other reduction: DACE's HARPS pipeline, or the second reduction a root planets_tables set up holds harps = [(k, x) for k, x in dace.items() if (planets_family(k[0]) == planets_BANK_FAMILY if planets_BANK_INFO else k[0] in ("HARPS03", "HARPS15") and "CCF" in k[1])] if sum(len(x) for _, x in harps) >= 12: tt, vv, ee, gg = [], [], [], [] for gi, (k, x) in enumerate(harps): x = np.array(planets_clean(x)) tn, vn, en = planets_by_night(mv(x[:, 0]), x[:, 1], x[:, 2]) tt.append(tn), vv.append(vn), ee.append(en), gg.append(np.full(len(tn), gi)) t, v, e, g = (np.concatenate(z) for z in (tt, vv, ee, gg)) o = np.argsort(t) res["sets"][planets_BANK_INFO.get("second_label", "DACE HARPS pipeline")] = planets_reduction(t[o], v[o], e[o], g[o], periods) S = [(x[0], x[3], k) for k, xs in dace.items() for x in xs if math.isfinite(x[3])] if S: t = mv(np.array([s[0] for s in S])) sv = np.array([s[1] for s in S]) lab = np.array([" ".join(s[2]) for s in S]) for u in np.unique(lab): sv[lab == u] -= np.median(sv[lab == u]) _, inv = np.unique(np.floor(t + 0.3), return_inverse=True) res["indicators"]["DACE S"] = planets_indicator(np.bincount(inv, t) / np.bincount(inv), np.bincount(inv, sv) / np.bincount(inv), periods) lp = planets_path("lbl", archive_tag(name) + ".lbl.npz") if os.path.exists(lp): d = np.load(lp) t, g = mv(d["mjd"]), (d["mjd"] >= float(d["upgrade"]) if "upgrade" in d.files else d["mjd"] >= planets_HARPS_UPGRADE).astype(int) stale = d["cal_age"] > 30.0 if "cal_age" in d.files else np.zeros(len(t), bool) res["line_by_line_stale_calibrations"] = int(stale.sum()) for key, ek, label in (("rv", "rv_err", "line-by-line, all lines"), ("rv_quiet", "rv_quiet_err", "line-by-line, quiet lines")): m = np.isfinite(d[key]) & np.isfinite(d[ek]) & ~stale res["sets"][label] = planets_reduction(t[m], d[key][m], d[ek][m], g[m], periods) res["indicators"]["line-by-line S"] = planets_indicator(t, d["S"], periods) res["indicators"]["line-by-line H alpha"] = planets_indicator(t, d["Halpha"], periods) fams = {} for k, xs in dace.items(): fam = planets_family(k[0]) if fam != planets_BANK_FAMILY and ("CCF" in k[1] or k[1][:1].isdigit()): fams.setdefault(fam, {}).setdefault(k[1], []).append((k, xs)) for fam, pubs in fams.items(): # one pipeline or publication per family, the one with the most velocities, its eras as groups k_best = max(pubs, key=lambda b: sum(len(xs) for _, xs in pubs[b])) tt, vv, ee, gg = [], [], [], [] for gi, (k, xs) in enumerate(pubs[k_best]): x = np.array(planets_clean(xs)) if len(x) < 3 or np.median(x[:, 2]) > 20.0: continue tn, vn, en = planets_by_night(mv(x[:, 0]), x[:, 1], x[:, 2]) tt.append(tn), vv.append(vn), ee.append(en), gg.append(np.full(len(tn), gi)) if not tt or sum(len(z) for z in tt) < 8: continue t, v, e, g = (np.concatenate(z) for z in (tt, vv, ee, gg)) out = dict(source=k_best, nights=len(t), first=round(float(t.min())), last=round(float(t.max())), periods={}) for P in periods: per = {} for jit in (0.0, 2.0): c, _, cov = planets_sinusoids(t, v, np.hypot(e, jit), g, [P]) K, eK, ph, eph = planets_amplitude(c, cov) per["free, jitter %g" % jit] = dict(K=round(K, 2), eK=round(eK, 2), phase=round(ph, 1), ephase=round(eph, 1)) if P in phases: se = np.hypot(e, jit) cols = [(g == gi).astype(float) for gi in np.unique(g)] + [np.cos(2 * np.pi * t / P - phases[P])] A = np.column_stack(cols) / se[:, None] cc = np.linalg.lstsq(A, v / se, rcond=None)[0] per["bank phase held, jitter %g" % jit] = dict(K=round(float(cc[-1]), 2), eK=round(float(math.sqrt(np.linalg.pinv(A.T @ A)[-1, -1])), 2)) if P in phases: per["bank phase"] = round(math.degrees(phases[P]) % 360.0, 1) out["periods"]["%g" % P] = per res["other_instruments"][fam] = out # another spectrograph's velocities are a reduction of other spectra if len(t) >= 12: o = np.argsort(t) res["sets"][fam + " velocities"] = planets_reduction(t[o], v[o], e[o], g[o], periods) return res planets_VET_SHORT = {"bank SERVAL": "SERVAL", "ESO HARPS pipeline": "DRS", "DACE HARPS pipeline": "DRS", "orbitlight cross-correlation": "CCF", "line-by-line, all lines": "LBL", "line-by-line, quiet lines": "LBL quiet", "HIRES, first reduction": "HIRES", "HIRES, second reduction": "HIRES2", "CARMENES, first reduction": "CARMENES", "CARMENES, second reduction": "CARMENES2", "SOPHIE, pipeline": "SOPHIE", "HARPS-N, newer pipeline": "HARPS-N", "HARPS-N, second reduction": "HARPS-N2", "NEID, pipeline": "NEID", "ELODIE, pipeline": "ELODIE"} def planets_vet_line(res, P): """A signal's tests on one line.""" key = "%g" % P sets = "; ".join("%s %s K %s" % (planets_VET_SHORT.get(label, label), c["fap"], "/".join("%.1f" % h["K"] for h in c["halves"])) for label, s in res["sets"].items() for c in [s["candidates"].get(key)] if c) ind = ", ".join(k for k, r in res["indicators"].items() if r and float(r.get(key, {}).get("fap", "1")) < 0.01) other = "; ".join("%s K %.2f+-%.2f" % (fam, d["periods"][key]["free, jitter 0"]["K"], d["periods"][key]["free, jitter 0"]["eK"]) for fam, d in res["other_instruments"].items() if key in d["periods"]) g = res.get("gaia") or {} gaia = "RUWE %.2f%s" % (float(g["ruwe"]), "".join(", " + s for s in g["solutions"])) if g.get("ruwe") not in (None, "") else "none" return "%-12s %10.3f d | %s | indicators at P: %s | other telescopes: %s | Gaia %s" % (res["name"], P, sets or "none", ind or "none", other or "none", gaia) def planets_vet_print(res): """A vet record printed in full.""" print("== %s at %s" % (res["name"], ", ".join("%g d" % P for P in res["periods"])), flush=True) if res.get("line_by_line_stale_calibrations"): print(" line-by-line: %d spectra wavelength-calibrated more than 30 days before they were taken left out" % res["line_by_line_stale_calibrations"], flush=True) for label, r in res["sets"].items(): print(" %-26s n %4d span %5d jitter %5.2f | found %s" % (label, r["n"], r["span"], r["jitter"], ", ".join("%g" % x for x in r["found"])), flush=True) for P, c in r["candidates"].items(): print(" %-8s peak %9.3f power %.3f fap %7s | aliases %s | halves %s" % (P, c["P_peak"], c["power"], c["fap"], c["aliases"], "; ".join( "K %.2f+-%.2f phase %.0f" % (h["K"], h["eK"], h["phase"]) for h in c["halves"])), flush=True) for label, r in res["indicators"].items(): if r: print(" %-26s top %9.2f d (%s) | %s" % (label, r["top_d"], r["top_fap"], " ".join("%s: %.3f (%s)" % (k, v["power"], v["fap"]) for k, v in r.items() if isinstance(v, dict))), flush=True) for fam, r in res["other_instruments"].items(): print(" %-26s %d nights %d-%d (%s): %s" % (fam, r["nights"], r["first"], r["last"], r["source"], "; ".join( "%s d: %s" % (P, ", ".join("%s K %.2f+-%.2f" % (k, v["K"], v["eK"]) for k, v in d.items() if isinstance(v, dict))) for P, d in r["periods"].items())), flush=True) if "gaia" in res: print(" Gaia DR3 %s: RUWE %s, non-single-star %s, solutions %s" % (res["gaia"]["source_id"], res["gaia"]["ruwe"], res["gaia"]["non_single_star"], res["gaia"]["solutions"] or "none"), flush=True) def planets_triage(rows, stars): """The candidates ROWS split into those kept and those set aside with why: e of 0.85 or more, fewer than two cycles, within 5 per cent of a year or half a year, or a planet the archive lists for the star in any published solution within 5 per cent of the period (planets_catalogued).""" match = planets_catalogued() kept, aside = [], [] for r in rows: P, e, span = float(r["P"]), float(r["e"]), float(r["span_d"]) why = [] if e >= 0.85: why.append("degenerate fit") if P > 0.5 * span: why.append("under two cycles") if any(abs(P / y - 1.0) < 0.05 for y in (365.25, 182.63)): why.append("year alias") s = stars.get(r["name"], {}) if match(planets_num(s.get("RAJ2000")), planets_num(s.get("DEJ2000")), names=(r["name"], s.get("SimbadName")), P=P): why.append("archive planet") (aside if why else kept).append((r, why)) return [r for r, _ in kept], aside # how near a signal's period an activity indicator's own highest peak marks it as the indicator's, which 2 of 104 of the archive's planets of the bank's stars are planets_INDICATOR_TOP = 0.02 def planets_verdict(res, P): """A vetted signal at P: the reductions where it holds (false-alarm level below 1e-3, halves agreeing in K and phase within 3 sigma), those where it fails with why, the indicators with power at P or their own highest peak within planets_INDICATOR_TOP of it, and the three as a sentence.""" key = "%g" % P held, failed = [], [] for label, s in res["sets"].items(): c = s["candidates"].get(key) if c is None: continue why = [] if float(c["fap"]) < 1e-3 else ["fap %s" % c["fap"]] if len(c["halves"]) == 2: a, b = c["halves"] if abs(a["K"] - b["K"]) > 3.0 * math.hypot(a["eK"], b["eK"]): why.append("halves' K %.1f and %.1f" % (a["K"], b["K"])) if abs((a["phase"] - b["phase"] + 180.0) % 360.0 - 180.0) > 3.0 * math.hypot(a["ephase"], b["ephase"]): why.append("halves' phases %.0f and %.0f" % (a["phase"], b["phase"])) short = planets_VET_SHORT.get(label, label) (failed if why else held).append(short + (" (%s)" % ", ".join(why) if why else "")) ind = [k for k, r in res["indicators"].items() if r and (float(r.get(key, {}).get("fap", "1")) < 0.01 or abs(r["top_d"] / P - 1.0) < planets_INDICATOR_TOP)] text = ("holds in " + ", ".join(held) if held else "holds in no reduction") + ("; fails " + ", ".join(failed) if failed else "") + ( "; indicators at P: " + ", ".join(ind) if ind else "") return held, failed, ind, text def planets_families(held): """How many independent reductions HELD covers, the line-by-line sets counting as one.""" return len({h.split()[0] for h in held}) def planets_rotation(bv, s): """A dwarf's rotation period (d) from B-V and the S index (Noyes et al. 1984, Mamajek and Hillenbrand 2008), None outside their calibrations.""" if not (0.44 < bv < 1.2 and s > 0): return None ccf = 10 ** (1.13 * bv ** 3 - 3.91 * bv ** 2 + 2.84 * bv - 0.47) r = 1.34e-4 * ccf * s - 10 ** (-4.898 + 1.918 * bv ** 2 - 2.893 * bv ** 3) if r <= 0 or not -5.1 < math.log10(r) < -4.0: return None x = 1.0 - bv tau = 10 ** (1.362 - 0.166 * x + 0.025 * x ** 2 - 5.323 * x ** 3 if x > 0 else 1.362 - 0.14 * x) return (0.808 - 2.966 * (math.log10(r) + 4.52)) * tau def planets_decide(res, P, system, tess, prot=None, modelled=False): """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, or with one where MODELLED says the star's activity, modelled, leaves it standing (planets_activity_test), 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, in PDCSAP flux, QLP's detrended flux having had a star's slow variation taken out), lie more than 10 per cent from each of the star's rotation periods PROT and half of it, and leave its system stable on circular orbits.""" held, _, ind, _ = planets_verdict(res, P) if ind and not modelled: return False, "activity indicator" if planets_families(held) < 2: return False, "one reduction" req = (system or {}).get("required", {}).get("%g" % P) if req is None: return False, "no joint model" if req["dbic"] <= 10.0: return False, "not needed" for a in system.get("aliases", {}).get("%g" % P, []): 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(): if label.split()[0] == "%g" % P and power >= 0.1 and float(c.get("near_fap", {}).get(label, "1")) < 0.01: return False, "starspots" if any(abs(P / q - 1.0) < 0.1 for x in prot or () for q in (x, x / 2.0)): return False, "rotation" stab = system.get("stability") if isinstance(stab, dict) and stab.get("circular", {}).get("status") != "stable": return False, "unstable" return True, "" # the false-alarm level a velocity signal must reach once its star's activity is modelled, the level its indicator must stay above at the signal's period, the draws of the null, and how far a signal must lie from the rotation period and its harmonics planets_ACTIVITY_FAP, planets_ACTIVITY_IND_FAP, planets_ACTIVITY_DRAWS, planets_ACTIVITY_ROTATION = 1e-3, 0.01, 200, 0.1 planets_ACTIVITY_CACHE = {} def planets_qp_kernel(t, h, lam, w, prot): """The quasi-periodic covariance of a rotating star's activity (Haywood et al. 2014) between the times T (d): amplitude H, evolution timescale LAM, harmonic complexity W and rotation period PROT.""" tau = t[:, None] - t[None, :] return h * h * np.exp(-0.5 * (tau / lam) ** 2 - 0.5 * (np.sin(np.pi * tau / prot) / w) ** 2) def planets_gp_profile(p, t, y, e, X, gi): """The quasi-periodic process of the log parameters P (amplitude, evolution timescale, harmonic complexity, rotation period, then a jitter for each series numbered by GI) on the values Y at the times T with errors E, the linear model X solved by generalized least squares: its negative log likelihood, the covariance's Cholesky factor and the data whitened by it.""" from scipy.linalg import cholesky, solve_triangular h, lam, w, prot = np.exp(p[:4]) C = planets_qp_kernel(t, h, lam, w, prot) + np.diag(e ** 2 + np.exp(2.0 * np.asarray(p[4:]))[gi]) try: L = cholesky(C, lower=True, check_finite=False) except np.linalg.LinAlgError: return np.inf, None, None yw, Xw = solve_triangular(L, y, lower=True, check_finite=False), solve_triangular(L, X, lower=True, check_finite=False) r = yw - Xw @ np.linalg.lstsq(Xw, yw, rcond=None)[0] return 0.5 * float(r @ r) + float(np.log(np.diag(L)).sum()), L, yw def planets_gp_fit(t, y, e, X, gi, p0, free, lo, hi): """The parameters of planets_gp_profile that FREE marks fitted by L-BFGS-B within LO and HI from P0, the others held: the parameters and the negative log likelihood.""" from scipy.optimize import minimize p0, free = np.asarray(p0, float), np.asarray(free, bool) def nll(q): p = p0.copy() p[free] = q got = planets_gp_profile(p, t, y, e, X, gi)[0] return got if math.isfinite(got) else 1e30 got = minimize(nll, p0[free], method="L-BFGS-B", bounds=list(zip(np.asarray(lo, float)[free], np.asarray(hi, float)[free]))) p = p0.copy() p[free] = got.x return p, float(got.fun) def planets_gp_periodogram(t, L, yw, X, freqs, draws=0, seed=7, chunk=2000): """The chi-square a sinusoid at each of FREQS takes out of the whitened data YW beyond the linear model X, the covariance's Cholesky factor L whitening every column; with DRAWS, the highest of the same over FREQS in that many draws of the null, which whitened is white noise. Returns the powers, the null's highest, and the sinusoid's semi-amplitude and its error at each frequency.""" from scipy.linalg import solve_triangular Q = np.linalg.qr(solve_triangular(L, X, lower=True, check_finite=False))[0] r = yw - Q @ (Q.T @ yw) R = None if draws: R = np.random.default_rng(seed).standard_normal((len(t), draws)) R = R - Q @ (Q.T @ R) power, K, eK, null = np.empty(len(freqs)), np.empty(len(freqs)), np.empty(len(freqs)), np.full(draws, -np.inf) for i in range(0, len(freqs), chunk): ph = 2.0 * np.pi * np.outer(t, freqs[i:i + chunk]) Cw, Sw = (solve_triangular(L, f(ph), lower=True, check_finite=False) for f in (np.cos, np.sin)) Cw, Sw = Cw - Q @ (Q.T @ Cw), Sw - Q @ (Q.T @ Sw) cc, ss, cs = (Cw * Cw).sum(0), (Sw * Sw).sum(0), (Cw * Sw).sum(0) det = np.maximum(cc * ss - cs * cs, 1e-300) a, b = Cw.T @ r, Sw.T @ r power[i:i + chunk] = (ss * a * a - 2.0 * cs * a * b + cc * b * b) / det A, B = (ss * a - cs * b) / det, (cc * b - cs * a) / det K[i:i + chunk] = np.hypot(A, B) eK[i:i + chunk] = np.sqrt(np.maximum((A * A * ss + B * B * cc - 2.0 * A * B * cs) / det, 0.0)) / np.maximum(np.hypot(A, B), 1e-300) if draws: a, b = Cw.T @ R, Sw.T @ R null = np.maximum(null, ((ss[:, None] * a * a - 2.0 * cs[:, None] * a * b + cc[:, None] * b * b) / det[:, None]).max(0)) return power, null, K, eK def planets_gumbel_fap(z, null): """The false-alarm level of the power Z against NULL, the highest powers of draws of the null, by the Gumbel distribution of their mean and spread.""" beta = max(float(np.std(null, ddof=1)) * math.sqrt(6.0) / math.pi, 1e-12) x = -(z - (float(np.mean(null)) - 0.5772156649 * beta)) / beta return 1.0 if x > 700.0 else float(-math.expm1(-math.exp(x))) def planets_activity_test(t, v, e, g, indicators, P, others=(), prot=(), draws=planets_ACTIVITY_DRAWS): """Whether a velocity signal at P outlasts its star's activity (Haywood et al. 2014; Rajpaul et al. 2015). For each activity indicator of INDICATORS, pairs of its name and nightly values at the times T (nan where unmeasured), a quasi-periodic Gaussian process is fitted to the indicator, its rotation period started from each of the indicator's three highest peaks and each period of PROT; the velocities V with errors E are then given the same process with its timescales held, an amplitude and a jitter for each series G fitted, offsets and sinusoids at OTHERS taken out, and searched for a sinusoid in a periodogram whitened by it. The signal holds where that periodogram's power within a resolution element of P has a false-alarm level below planets_ACTIVITY_FAP against DRAWS draws of the process alone, the indicator's own whitened periodogram shows nothing there at planets_ACTIVITY_IND_FAP, and P lies further than planets_ACTIVITY_ROTATION from the fitted and listed rotation periods, their halves and their thirds, under every indicator. Returns the verdict, why, the highest false-alarm level and each indicator's reading.""" span = float(t.max() - t.min()) freqs = np.arange(1.0 / span, 1.0 / 1.5, 1.0 / (5.0 * span)) near = np.abs(freqs - 1.0 / P) <= 1.0 / span if not near.any() or not indicators: return dict(P=P, verdict="failed", why="no indicator to model" if not indicators else "outside the periodogram", fap=1.0, readings=[]) gi = np.searchsorted(np.unique(g), g) X = np.column_stack([(gi == k).astype(float) for k in range(int(gi.max()) + 1)] + [f(2.0 * np.pi * t / Q) for Q in others for f in (np.cos, np.sin)]) readings, why = [], [] for name, y in indicators: m = np.isfinite(y) if m.sum() < 20: readings.append(dict(indicator=name, note="too few nights")) why.append("%s too sparse to model" % name) continue ti, gj = t[m], np.searchsorted(np.unique(g[m]), g[m]) yi = y[m] - np.median(y[m]) yi = yi / (1.4826 * float(np.median(np.abs(yi))) or float(np.std(yi)) or 1.0) Xi = np.column_stack([(gj == k).astype(float) for k in range(int(gj.max()) + 1)]) pw = gpu_host(gpu_gls(ti, yi, np.ones(len(yi)), freqs)) per = 1.0 / freqs loc = np.flatnonzero((pw[1:-1] >= pw[:-2]) & (pw[1:-1] >= pw[2:])) + 1 loc = loc[(per[loc] >= 1.5) & (per[loc] <= span / 3.0)] starts = [] for k in loc[np.argsort(-pw[loc])]: if all(abs(per[k] / q - 1.0) > 0.1 for q in starts): starts.append(float(per[k])) if len(starts) == 3: break starts += [q for q in prot if 1.5 <= q <= span / 2.0 and all(abs(q / s - 1.0) > 0.1 for s in starts)] best = None for q in starts or [span / 10.0]: G = int(gj.max()) + 1 p0 = [0.0, math.log(2.0 * q), math.log(0.7), math.log(q)] + [math.log(0.5)] * G lo = [math.log(1e-3), math.log(0.4 * q), math.log(0.2), math.log(0.8 * q)] + [math.log(1e-3)] * G hi = [math.log(10.0), math.log(5.0 * span), math.log(5.0), math.log(1.2 * q)] + [math.log(3.0)] * G p, nll = planets_gp_fit(ti, yi, np.zeros(len(yi)), Xi, gj, p0, [True] * (4 + G), lo, hi) if best is None or nll < best[1]: best = (p, nll) p_ind = best[0] _, Li, ywi = planets_gp_profile(p_ind, ti, yi, np.zeros(len(yi)), Xi, gj) if Li is None: readings.append(dict(indicator=name, note="no process fits")) why.append("%s not modelled" % name) continue pwi, nulli, _, _ = planets_gp_periodogram(ti, Li, ywi, Xi, freqs, draws) fap_ind = planets_gumbel_fap(float(pwi[near].max()), nulli) sd = float(np.std(v)) or 1.0 G = int(gi.max()) + 1 p0 = np.concatenate([[math.log(sd)], p_ind[1:4], np.full(G, math.log(1.0))]) lo = np.concatenate([[math.log(1e-2)], p_ind[1:4], np.full(G, math.log(1e-2))]) hi = np.concatenate([[math.log(10.0 * sd)], p_ind[1:4], np.full(G, math.log(3.0 * sd))]) pv, _ = planets_gp_fit(t, v, e, X, gi, p0, [True, False, False, False] + [True] * G, lo, hi) _, Lv, ywv = planets_gp_profile(pv, t, v, e, X, gi) if Lv is None: readings.append(dict(indicator=name, note="no process fits the velocities")) why.append("velocities not modelled under %s" % name) continue pwv, nullv, K, eK = planets_gp_periodogram(t, Lv, ywv, X, freqs, draws) k = int(np.flatnonzero(near)[np.argmax(pwv[near])]) fap = planets_gumbel_fap(float(pwv[k]), nullv) rot = float(math.exp(p_ind[3])) at_rot = any(abs(P / (x / n) - 1.0) < planets_ACTIVITY_ROTATION for x in [rot] + list(prot) for n in (1.0, 2.0, 3.0)) held = fap < planets_ACTIVITY_FAP and fap_ind >= planets_ACTIVITY_IND_FAP and not at_rot readings.append(dict(indicator=name, prot_d=round(rot, 2), lam_d=round(float(math.exp(p_ind[1])), 1), w=round(float(math.exp(p_ind[2])), 2), activity_ms=round(float(math.exp(pv[0])), 2), P_peak=round(float(1.0 / freqs[k]), 4), K=round(float(K[k]), 3), eK=round(float(eK[k]), 3), fap=fap, fap_indicator=fap_ind, held=bool(held))) if not held: why.append("%s: %s" % (name, "at the rotation" if at_rot else "the indicator holds the period too (%.1e)" % fap_ind if fap_ind < planets_ACTIVITY_IND_FAP else "not significant once modelled (%.1e)" % fap)) ok = bool(readings) and all(x.get("held") for x in readings) return dict(P=P, verdict="held" if ok else "failed", why="; ".join(why), fap=max([x.get("fap", 1.0) for x in readings] or [1.0]), readings=readings) def planets_indicator_column(label): """The column of planets_INDICATORS that a vet record's indicator LABEL, its source and its name ("bank CRX", "DACE S", "line-by-line H alpha"), is read from in a star's nightly rows, or None.""" head, _, rest = label.partition(" ") name = (rest if head in ("bank", "DACE") else label.replace("line-by-line ", "")).replace("H alpha", "Halpha") return planets_INDICATORS.index(name) if name in planets_INDICATORS else None def planets_activity_result(name, P): """The activity test's record of the star NAME's signal at P (planets_activity), or None.""" if name not in planets_ACTIVITY_CACHE: planets_ACTIVITY_CACHE[name] = planets_load_json(os.path.join(planets_RESULTS, "activity", archive_tag(name) + ".json")) or {} return planets_ACTIVITY_CACHE[name].get("signals", {}).get("%g" % P) def planets_activity_ready(name, P): """Whether the activity test holds the star NAME's signal at P and its system analysis has weighed it, so that the decision follows it.""" got = planets_activity_result(name, P) if not got or got.get("verdict") != "held": return False system = planets_load_json(os.path.join(planets_RESULTS, "system", archive_tag(name), "analysis.json")) or {} return any(abs(P / q - 1.0) < 1e-9 for q in system.get("periods", [])) def planets_activity_text(got): """An activity test's record as the activity_model column gives it.""" return "%s, false-alarm level %.1e%s" % (got["verdict"], got.get("fap", 1.0), "; " + got["why"] if got.get("why") else "") def planets_activity(part=None): """The velocity signals that hold in two independent reductions and are set aside only because an activity indicator shows power at their period, each given the test of planets_activity_test with the indicators that do, to RESULTS/activity/.json, made again when the star's nightly velocities or the test's code change. A signal that holds has its star followed again with it (planets_followup_star), so that the decision weighs it as it weighs any followed signal, a likely planet until another spectrograph's spectra hold it (planets_second_decide). PART takes the share K/N; the pass ends between stars where a long search would, with exit status 3.""" path = os.path.join(planets_RESULTS, "signals.csv") if not os.path.exists(path): return sig = planets_read(path) want = {} for r in sig: if r["kind"] in ("found", "eccentric") and (r["reason"] == "activity indicator" or r.get("activity_model")): want.setdefault(r["name"], set()).add(float(r["P"])) names = sorted(want) if part: k, n = (int(x) for x in part.split("/")) names = names[k::n] digest = planets_rules_hash(("planets_activity", "planets_activity_test", "planets_indicator_column", "planets_qp_kernel", "planets_gp_profile", "planets_gp_fit", "planets_gp_periodogram", "planets_gumbel_fap"), (planets_ACTIVITY_FAP, planets_ACTIVITY_IND_FAP, planets_ACTIVITY_DRAWS, planets_ACTIVITY_ROTATION)) stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} bank, dace = planets_bank_series(set(names)), planets_dace_series(set(names)) folder = os.path.join(planets_RESULTS, "activity") os.makedirs(folder, exist_ok=True) for name in names: if planets_search_ends(): sys.exit(3) res = planets_load_json(os.path.join(planets_RESULTS, "vet", archive_tag(name) + ".json")) rows, _ = planets_series(name, dace, bank, stars.get(name, {}).get("SpType")) if not res or not rows: continue x = planets_nightly(rows) t, v, e, g = x[:, 0], x[:, 1], x[:, 2], x[:, 3].astype(int) kept = os.path.join(folder, archive_tag(name) + ".json") rec, mark = planets_load_json(kept) or {}, "%d:%.4f" % (len(t), float(t.sum())) if rec.get("digest") != digest or rec.get("data") != mark: rec = dict(digest=digest, data=mark, signals={}) s = stars.get(name, {}) prot = [q for q in (archive_num(s.get("Prot")),) if q] + planets_rotation_read(planets_num(s.get("RAJ2000")), planets_num(s.get("DEJ2000"))) known = [float(r["P"]) for r in sig if r["name"] == name and r["kind"] == "known"] holding = [] for P in sorted(want[name]): key = "%g" % P if key not in rec["signals"]: held, _, ind, _ = planets_verdict(res, P) if "%g" % P in next(iter(res["sets"].values()), {}).get("candidates", {}) else ([], [], [], "") if planets_families(held) < 2 or not ind: rec["signals"][key] = dict(P=P, verdict="not tested", why="holds in fewer than two reductions" if planets_families(held) < 2 else "no indicator at the period") continue others = [float(r["P"]) for r in sig if r["name"] == name and r["kind"] in ("found", "eccentric", "known") and r["status"] in ("new", "known", "likely") and abs(float(r["P"]) / P - 1.0) > 0.02] cols = [] for k in ind: c = planets_indicator_column(k) if c is not None and c not in cols: cols.append(c) inds = [(planets_INDICATORS[c], x[:, 4 + c]) for c in cols] try: rec["signals"][key] = planets_activity_test(t, v, e, g, inds, P, others, prot) except Exception as exc: rec["signals"][key] = dict(P=P, verdict="failed", why="%s: %s" % (type(exc).__name__, str(exc)[:120]), fap=1.0) print("%-16s P %10.4f %s" % (name[:16], P, planets_activity_text(rec["signals"][key])), flush=True) if rec["signals"][key]["verdict"] == "held": holding.append(P) archive_save(kept, json.dumps(rec, separators=(",", ":")).encode()) system = planets_load_json(os.path.join(planets_RESULTS, "system", archive_tag(name), "analysis.json")) or {} had = system.get("periods", []) missing = [P for P in holding if not any(abs(P / q - 1.0) < 1e-9 for q in had)] if missing: planets_followup_star(name, sorted({q for q in had if not any(abs(q / k - 1.0) < 1e-9 for k in known)} | set(missing)), known) def planets_followup_star(name, periods, known, lbl_streams=4): """One followed star's work: line-by-line velocities where it has none and a fresh vet, its orbits sampled free and circular, the circular orbits placing its transit windows in TESS's light curves, and the system analysis, at PERIODS and the archive's KNOWN periods; each step's failure to ROOT/followup/.json.""" errors, system = {}, sorted(set(known) | set(periods)) if not os.path.exists(planets_path("lbl", archive_tag(name) + ".lbl.npz")): try: planets_lbl(name, streams=lbl_streams) except (SystemExit, Exception) as exc: errors["lbl"] = str(exc)[:200] planets_vet([(name, periods)]) for step, call in (("orbits", lambda: planets_orbits(name, system)), ("orbits circular", lambda: planets_orbits(name, system, circular=True)), ("tess", lambda: planets_tess(name, periods)), ("system", lambda: planets_system(name, system))): try: call() except Exception as exc: errors[step] = "%s: %s" % (type(exc).__name__, str(exc)[:200]) os.makedirs(planets_path("followup"), exist_ok=True) json.dump(errors, open(planets_path("followup", archive_tag(name) + ".json"), "w"), separators=(",", ":")) def planets_followup_row(r, res, catalogued=(), unexplained=(), prot=None): """A followed signal's decision and follow-up columns for RESULTS/signals.csv, known where the star has a catalogued companion without a period.""" P, tag = float(r["P"]), archive_tag(r["name"]) load = lambda p: json.load(open(p)) if os.path.exists(p) else None system, tess = load(os.path.join(planets_RESULTS, "system", tag, "analysis.json")), load(os.path.join(planets_RESULTS, "tess", tag + ".json")) orbits = load(os.path.join(planets_RESULTS, "orbits", tag + ".json")) modelled = bool(planets_verdict(res, P)[2]) and planets_activity_ready(r["name"], P) planet, reason = planets_decide(res, P, system, tess, prot, modelled) act = planets_activity_result(r["name"], P) row = dict(status=("known" if unexplained else "likely" if modelled else "new") if planet else "rejected", reason=("catalogued" if unexplained else "activity modelled" if modelled else "") if planet else reason, activity_model=planets_activity_text(act) if act and act.get("verdict") in ("held", "failed") else "", catalogued="; ".join(catalogued), ruwe=archive_num((res.get("gaia") or {}).get("ruwe")), rotation_d=round(min(prot, key=lambda q: abs(math.log(P / q))), 1) if prot else "") for label, s in res["sets"].items(): c = s["candidates"].get("%g" % P) if c: row["fap_" + planets_VET_SHORT.get(label, label).lower().replace(" ", "_")] = float(c["fap"]) # Match the signal to the sampled planet with the nearest period; planets_orbits keeps each period within 20% of its starting value. pl = min(orbits["planets"], key=lambda x: abs(x["P"][0] / P - 1.0)) if orbits else None if pl and abs(pl["P"][0] / P - 1.0) < 0.2: for key, col in (("P", "orbit_P"), ("msini_mearth", "orbit_msini_mearth"), ("e", "orbit_e"), ("K", "orbit_K")): row.update({col: pl[key][0], col + "_lo": pl[key][1], col + "_hi": pl[key][2]}) if system: row["dbic"] = system.get("required", {}).get("%g" % P, {}).get("dbic") row["aliases_excluded"] = all(a["observed_ratio"] >= 1.0 and next(v["reaching_observed"] for k, v in a["truth"].items() if k != "%.4f d" % P) < 0.01 for a in system["aliases"].get("%g" % P, [])) if tess: row["tess_power"] = tess["combined"]["near"].get("%g P" % P) near = min(tess["windows"], key=lambda k: abs(float(k) / P - 1.0), default=None) w = tess["windows"][near] if near is not None and abs(float(near) / P - 1.0) < 0.2 else None limits = [x["central"]["radius_limit_rearth"] for x in (w or {}).get("windows", []) if x.get("central", {}).get("probability_covered", 0) >= 0.5] row["tess_radius_limit_rearth"] = min(limits) if limits else None return row # the SIMBAD types of a binary star planets_BINARY_TYPES = ("SB*", "EB*", "El*", "RS*", "WU*", "bL*", "Al*") def planets_object(mjup): """The kind of body of a mass in Jupiter masses: a planet below 13, a brown dwarf below 80, a star above.""" return "" if not math.isfinite(mjup) else "planet" if mjup < 13.0 else "brown dwarf" if mjup < 80.0 else "star" def planets_varying(bank, stars, skip): """The bank's late-type stars outside SKIP that vary like binaries (4+ nights, reduced chi-square > 25, scatter > 30 m/s and 5 median errors): name to nights.""" out = {} for n, rows in bank.items(): if n in skip or not planets_late_type(stars.get(n, {}).get("SpType")): continue x = np.array(rows) V, E = [], [] for sel in (x[:, 0] < planets_UPGRADE, x[:, 0] >= planets_UPGRADE): if sel.any(): _, vn, en = planets_by_night(x[sel, 0], x[sel, 1], x[sel, 2]) V.append(vn - np.sum(vn / en ** 2) / np.sum(1.0 / en ** 2)), E.append(en) v, e = np.concatenate(V), np.concatenate(E) if len(v) < 4: continue chi2r = float(np.sum((v / e) ** 2) / max(len(v) - len(V), 1)) scatter = float(1.4826 * np.median(np.abs(v - np.median(v)))) if chi2r > 25.0 and scatter > 30.0 and scatter > 5.0 * float(np.median(e)): out[n] = len(v) return out def planets_gaia(names, stars): """Each star's Gaia DR3 source and non-single-star solutions, cached in ROOT/gaia.json: name to (source, solutions) or None.""" path = planets_path("gaia.json") cache = json.load(open(path)) if os.path.exists(path) else {} todo = [n for n in names if n not in cache] if todo: found = dict(zip(todo, archive_pmap(lambda n: archive_gaia_star(float(stars[n]["RAJ2000"]), float(stars[n]["DEJ2000"]), archive_num(stars[n].get("Vmag")), physical=False), todo))) sols = archive_gaia_solutions([g["source_id"] for g in found.values() if g]) for n, g in found.items(): cache[n] = [g, sols[str(g["source_id"])]] if g else None json.dump(cache, open(path, "w"), separators=(",", ":")) return {n: cache.get(n) for n in names} # the days Gaia DR3's epochs span, over half of which its orbits' periods are bound loosely planets_GAIA_WINDOW = 1034.0 def planets_catalogue(names, stars, periods=None): """Each star's catalogue entries: SIMBAD binary type, SIMBAD planets and brown dwarfs, Gaia orbits and archive planets, matched to PERIODS if given, a Gaia orbit past half its window matching any period past the window.""" simbad = {n: (stars.get(n, {}).get("SimbadName") or n).strip() for n in names} basic = archive_simbad_basic(sorted(set(simbad.values()))) kids = archive_simbad_companions(sorted(set(simbad.values()))) # papers on a few hundred objects at most whose titles name a binary, a companion or an orbit papers = archive_simbad_papers(sorted(set(simbad.values())), words=("binar", "companion", "orbit"), most=500) gaia = planets_gaia(names, stars) known = planets_read(planets_path("known.csv")) kra, kdec, kper = (np.array([planets_num(k[c]) for k in known]) for c in ("ra", "dec", "pl_orbper")) kpm = np.array([[np.nan_to_num(planets_num(k["sy_pmra"])), np.nan_to_num(planets_num(k["sy_pmdec"]))] for k in known]) out = {} for n in names: P = (periods or {}).get(n) near = lambda Q, tol: P is None or (math.isfinite(Q) and abs(P / Q - 1.0) < tol) hits = [] otype = (basic.get(simbad[n]) or {}).get("otype") or "" if otype in planets_BINARY_TYPES: hits.append("SIMBAD " + otype) hits += ["SIMBAD %s %s" % (k[1], " ".join(k[0].split())) for k in kids.get(simbad[n], [])] hits += ["paper %s" % p[0] for p in papers.get(simbad[n], [])[:3]] g = gaia.get(n) for o in (g[1]["orbit"] if g else []): if near(planets_num(o.get("period")), 0.2) or (P is not None and P > planets_GAIA_WINDOW and planets_num(o.get("period")) > 0.5 * planets_GAIA_WINDOW): hits.append("Gaia %s %.1f d" % (o.get("nss_solution_type"), planets_num(o.get("period")))) ra, dec = planets_num(stars[n]["RAJ2000"]), planets_num(stars[n]["DEJ2000"]) cosd = math.cos(math.radians(dec)) sep = lambda a, d: np.hypot(((a - ra + 180.0) % 360.0 - 180.0) * cosd, d - dec) * 3600.0 close = np.minimum(sep(kra, kdec), sep(kra - 16.0 * kpm[:, 0] / 3.6e6 / cosd, kdec - 16.0 * kpm[:, 1] / 3.6e6)) < 60.0 hits += ["archive %s" % known[i]["pl_name"] for i in np.where(close)[0] if near(kper[i], 0.05)] out[n] = hits return out def planets_companion(name, perms=50, most=40, seed=17): """One star's companion analysis to RESULTS/companion/.json: Keplerian periodogram and permutation null, sampled and weighed orbit, and a second reduction from its archive spectra by cross-correlation.""" star = next(r for r in planets_read(planets_path("bank_stars.csv")) if r["Name"] == name) t, v, e, g = planets_nights(name) span = float(t.max() - t.min()) kp = planets_kepler_power(t, v, e, g) rng = np.random.default_rng(seed) null = np.array([planets_kepler_power(t, v, e, g, shuffle=rng)["dchi2"] for _ in range(perms)]) beta = max(float(np.std(null, ddof=1)) * math.sqrt(6.0) / math.pi, 1e-9) mu = float(np.mean(null)) - 0.5772 * beta P0 = kp["P"] away = np.abs(1.0 / kp["freqs"] / P0 - 1.0) > 0.05 s2 = max((kp["chi0"] - kp["dchi2"]) / max(len(t) - (int(g.max()) + 1) - 5, 1), 1.0) z = -(kp["dchi2"] - mu) / beta rec = dict(name=name, nights=len(t), span_d=round(span), P=round(P0, 4), e=kp["e"], K=round(kp["K"], 2), dchi2=round(kp["dchi2"], 1), fap=1.0 if z > 700.0 else float(-math.expm1(-math.exp(z))), null_mean=round(float(np.mean(null)), 1), null_sd=round(float(np.std(null, ddof=1)), 1), null_max=round(float(null.max()), 1), cycles=round(span / P0, 2), margin=round(float((kp["dchi2"] - kp["best"][away].max()) / s2), 1) if away.any() else None) if span >= 2.0 * P0: try: planets_orbits(name, [P0], steps=20000, label="companion") o = json.load(open(os.path.join(planets_RESULTS, "orbits", archive_tag(name) + ".companion.json")))["planets"][0] rec["orbit"] = {k: o[k] for k in ("P", "K", "e", "msini_mearth")} except Exception as exc: rec["orbit_error"] = "%s: %s" % (type(exc).__name__, str(exc)[:200]) if P0 > 100.0: try: 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", "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) if gs: rec["ruwe"] = archive_num(gs.get("ruwe")) hip = archive_hipparcos_of(gs["source_id"]) or planets_hip_near(gs) k = planets_anomaly(gs, hip) rec["pma_snr"] = round(k["snrPMaH2EG3b"], 1) if k else None # The second reduction: the archive's spectra on the bank's nights measured by cross-correlation, or in a root planets_measure measured, where the # bank is already that, the same spectra's line-by-line velocities, or in a root planets_tables set up its second reduction of the same spectra. night = np.floor(t + 0.3) stored = planets_path("lbl", archive_tag(name) + ".lbl.npz") rows = sorted((x for k, xs in planets_dace_series({name}).get(name, {}).items() if planets_family(k[0]) == planets_BANK_FAMILY for x in xs), key=lambda x: x[0]) if planets_BANK_INFO else [] own = None if rows else planets_own_spectra(name, 10.0) if rows or planets_BANK_INFO and own is None: tv = np.array([x[0] for x in rows]) v1 = np.array([x[1] for x in rows]) keep_ = np.isin(np.floor(tv + 0.3), night) tv, v1 = tv[keep_], v1[keep_] elif os.path.exists(planets_path("measure.json")) and os.path.exists(stored): d = np.load(stored) tv, v1 = d["mjd"], d["rv"] keep_ = np.isin(np.floor(tv + 0.3), night) & np.isfinite(v1) tv, v1 = tv[keep_], v1[keep_] else: best = {} for r in own if own is not None else archive_eso_listing(float(star["RAJ2000"]), float(star["DEJ2000"]), "HARPS", 10.0): k = math.floor(float(r["t_min"]) + 0.3) if k in night and (k not in best or (archive_num(r["snr"]) or 0) > (archive_num(best[k]["snr"]) or 0)): best[k] = r pick = [best[k] for k in sorted(best)] pick = [pick[int(i)] for i in np.unique(np.linspace(0, len(pick) - 1, most).round())] if len(pick) > most else pick folder = planets_path("spectra", archive_tag(name) + ".ccf") spectra = spectra_read(archive_eso_fetch(pick, folder, streams=2 if own is not None else 4)) shutil.rmtree(folder, ignore_errors=True) tv = np.array([s[3]["mjd"] for s in spectra]) v1 = binaries_velocities(spectra, binaries_line_depths(spectra, binaries_velocities(spectra, np.load(binaries_template_path()))[0]))[0] * 1000.0 if len(spectra) >= 6 else [] if len(tv) >= 6: at = {k: i for i, k in enumerate(night)} j = np.array([at[math.floor(x + 0.3)] for x in tv]) a, b = v1.copy(), v[j].copy() for gi in np.unique(g[j]): m = g[j] == gi a[m], b[m] = a[m] - a[m].mean(), b[m] - b[m].mean() rec["ccf"] = dict(nights=int(len(j)), corr=round(float(np.corrcoef(a, b)[0, 1]), 3), rms=round(float(np.std(a - b)), 1)) os.makedirs(os.path.join(planets_RESULTS, "companion"), exist_ok=True) json.dump(rec, open(os.path.join(planets_RESULTS, "companion", archive_tag(name) + ".json"), "w"), separators=(",", ":")) 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 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: # an orbit longer than half the span stands on the astrometry: an anomaly of 5 sigma or a Gaia solution, and a period the prior does not set w = rec.get("weigh") if not w: 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 if b > 2.0 * a or b > 0.9 * hi or a < 1.1 * lo: return False, "period unbounded" elif rec["fap"] >= 1e-3: return False, "not significant" elif rec.get("margin") is not None and rec["margin"] < 10.0: return False, "period ambiguous" c = rec.get("ccf") or {} if c.get("nights", 0) < 6 or c.get("corr", 0.0) < 0.9: return False, "one reduction" return True, "" def planets_companion_row(name, star, rec, cat): """A companion's signals.csv row from its analysis REC and catalogue entries CAT.""" m1 = planets_star_mass(star) row = dict(name=name, sptype=star.get("SpType", ""), vmag=star.get("Vmag", ""), kind="companion", label="orbit", nights=rec["nights"], span_d=rec["span_d"], fap=rec["fap"], catalogued="; ".join(cat), ruwe=rec.get("ruwe"), pma_snr=rec.get("pma_snr")) o, w = rec.get("orbit"), rec.get("weigh") if o: P, K, e = o["P"][0], o["K"][0], o["e"][0] for key, col in (("P", "orbit_P"), ("msini_mearth", "orbit_msini_mearth"), ("e", "orbit_e"), ("K", "orbit_K")): row.update({col: o[key][0], col + "_lo": o[key][1], col + "_hi": o[key][2]}) elif w: P, K, e = w["P_d"][0], w["K1_ms"][0], w["e"][0] for key, col in (("P_d", "orbit_P"), ("K1_ms", "orbit_K"), ("e", "orbit_e")): row.update({col: round(w[key][0], 4), col + "_lo": round(w[key][1], 4), col + "_hi": round(w[key][2], 4)}) else: 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)) # 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, object=planets_object(row.get("mass_mjup") or msini)) return row def planets_decide_toi(r): """A weighed TESS candidate's verdict and reason: ephemeris within 0.1 period, K > 0 at 5 sigma, free phase within 3 sigma of the transit's.""" if planets_num(r["phase_err"]) > 0.1: return False, "ephemeris lost" K, snr = planets_num(r["K"]), planets_num(r["snr"]) if not (K > 0 and snr >= 5.0): return False, "not significant" eph = planets_num(r.get("ephase_deg")) if not math.isfinite(eph): eph = math.degrees(planets_num(r["eK_free"]) / max(planets_num(r["K_free"]), 1e-9)) if abs(planets_num(r["phase_offset_deg"])) > 3.0 * math.hypot(eph, 360.0 * planets_num(r["phase_err"])): return False, "phase" return True, "" def planets_toi_rows(): """The weighed TESS candidates of ROOT/tois.csv, then of tois_eso.csv, tois_rvcat.csv and tois_bank.csv for those not weighed before, as decided signals.csv rows.""" tois = planets_read(planets_path("tois.csv")) if os.path.exists(planets_path("tois.csv")) else [] for table in ("tois_eso.csv", "tois_rvcat.csv", "tois_bank.csv"): have = {r["toi"] for r in tois} if os.path.exists(planets_path(table)): tois += [r for r in planets_read(planets_path(table)) if r["toi"] not in have] if not tois: return [] if not all(r.get("ra") for r in tois): exo = planets_path("toi.csv") if not os.path.exists(exo): open(exo, "wb").write(archive_get(planets_EXOFOP["toi"], timeout=300)) from astropy.coordinates import Angle pos = {x["TOI"]: (Angle(x["RA"], unit="hourangle").deg, Angle(x["Dec"], unit="deg").deg) for x in planets_read(exo)} for r in tois: r["ra"], r["dec"] = pos.get(r["toi"], ("", "")) match = planets_catalogued() basic = archive_simbad_basic(sorted({r["dace_name"] for r in tois})) out = [] for r in tois: P, ra, dec = planets_num(r["period"]), planets_num(r["ra"]), planets_num(r["dec"]) msini = planets_msini(P, abs(planets_num(r["K"])), 0.0, planets_num(r["mstar"]) or 1.0) cat = ["archive %s" % n for n in match(ra, dec, r.get("tic"), (r["dace_name"],), P)] + (["archive host %s" % r["archive_host"]] if r.get("archive_host") else []) otype = (basic.get(r["dace_name"]) or {}).get("otype") or "" if otype in planets_BINARY_TYPES and msini >= 80.0: cat.append("SIMBAD " + otype) held, why = planets_decide_toi(r) snr = planets_num(r["snr"]) out.append(dict(name=r["dace_name"], kind="toi", label="TOI-" + r["toi"], nights=r["nights"], span_d=r["span_d"], P=round(P, 6), K=r["K"], e=0.0, msini_mjup=round(msini, 4), msini_mearth=round(msini * 317.83, 1), jitter=r["jitter"], fap="%.1e" % (0.5 * math.erfc(snr / math.sqrt(2.0))) if math.isfinite(snr) else "", catalogued="; ".join(cat), status=("known" if cat else "new") if held else "rejected", reason=("catalogued" if cat else "") if held else why, object=planets_object(msini))) return out # MAST's tables of SPOC's threshold-crossing events with their data-validation statistics, one for each search of one sector or of several planets_TCE = "https://archive.stsci.edu/missions/tess/catalogs/tce/" planets_TCE_KEYS = ("tce_period", "tce_num_transits", "tce_bin_oedp_stat", "tce_ws_maxmes", "tce_dicco_msky", "tce_dicco_msky_err", "tce_cap_stat", "tce_hap_stat") def planets_tce(tics): """SPOC's threshold-crossing events of the TIC stars TICS with their data-validation statistics (planets_TCE_KEYS), read from every table MAST lists, the listing kept a day in ROOT/tce/listing.json and each table fetched into ROOT/tce once, their rows kept as arrays in ROOT/tce/events.npz until another table arrives: TIC to its events.""" if not tics: return {} folder = planets_path("tce") os.makedirs(folder, exist_ok=True) listed = os.path.join(folder, "listing.json") if os.path.exists(listed) and time.time() - os.path.getmtime(listed) < 86400: names = json.load(open(listed)) else: listing = archive_get(planets_TCE, timeout=120, soft=True) names = sorted(set(re.findall(r'href="([^"]+_dvr-tcestats\.csv)"', listing.decode("utf-8", "replace")))) if listing else [] if names: archive_save(listed, json.dumps(names).encode()) def fetch(name): path = os.path.join(folder, name) if not os.path.exists(path): b = archive_get(planets_TCE + name, timeout=600, soft=True) if b: archive_save(path, b) archive_pmap(fetch, names, 4) tables = [os.path.basename(p) for p in sorted(glob.glob(os.path.join(folder, "*_dvr-tcestats.csv")))] cache, d = os.path.join(folder, "events.npz"), None if os.path.exists(cache): with np.load(cache) as z: if z["tables"].tolist() == tables: d = dict(ticid=z["ticid"], values=z["values"]) if d is None: ticid, values = [], [] for name in tables: with open(os.path.join(folder, name), encoding="utf-8", errors="replace") as fh: rows = csv.reader(line for line in fh if not line.startswith("#")) head = next(rows, []) if "ticid" not in head: continue at = {k: head.index(k) for k in ("ticid",) + planets_TCE_KEYS if k in head} for row in rows: if len(row) > max(at.values()) and row[at["ticid"]].strip().isdigit(): ticid.append(int(row[at["ticid"]])) values.append([planets_num(row[at[k]]) if k in at else float("nan") for k in planets_TCE_KEYS]) d = dict(ticid=np.array(ticid, np.int64), values=np.array(values, float).reshape(-1, len(planets_TCE_KEYS))) tmp = archive_tmp(cache) with open(tmp, "wb") as fh: np.savez(fh, tables=np.array(tables), **d) archive_place(tmp, cache) out = {} hit = np.isin(d["ticid"], np.array(sorted({int(t) for t in tics}), np.int64)) for t, v in zip(d["ticid"][hit].tolist(), d["values"][hit].tolist()): out.setdefault(str(t), []).append(dict(zip(planets_TCE_KEYS, v))) return out def planets_dv(e): """A SPOC event's data validation as decided signals.csv columns, with the reason it fails, empty where it passes: a secondary eclipse found at a MES of 7.1 or more, the difference image's centroid off the out-of-transit image's at 3 sigma or more, or the halo aperture's statistic above the core aperture's, as a ghost's is. Its odd-even statistic is kept beside them; the odd-even test is orbitlight's own (planets_validate_one).""" sigma = e["tce_dicco_msky"] / e["tce_dicco_msky_err"] if e["tce_dicco_msky_err"] > 0 else float("nan") cols = {k: round(x, 3) if math.isfinite(x) else "" for k, x in (("dv_odd_even", e["tce_bin_oedp_stat"]), ("dv_secondary_mes", e["tce_ws_maxmes"]), ("dv_centroid_sigma", sigma), ("dv_core", e["tce_cap_stat"]), ("dv_halo", e["tce_hap_stat"]))} why = "secondary eclipse" if e["tce_ws_maxmes"] >= 7.1 else "centroid offset" if sigma >= 3.0 else "halo" if e["tce_hap_stat"] > e["tce_cap_stat"] else "" return cols, why def planets_occultation_max(x, depth_ppm, P): """The deepest occultation (ppm) a planet transiting DEPTH_PPM deep every P days could give behind its star, ExoFOP's row X giving the star's mass, radius and temperature: the planet's geometric albedo one and its dayside at the equilibrium temperature without redistribution, a blackbody at 800 nm against the star's; zero where ExoFOP lacks them.""" M, R, T = (planets_num(x.get(k)) for k in ("Stellar Mass (M_Sun)", "Stellar Radius (R_Sun)", "Stellar Eff Temp (K)")) if not (M > 0 and R > 0 and T > 0 and P > 0): return 0.0 aR = 215.032 * (M * (P / 365.25) ** 2) ** (1.0 / 3.0) / R planck = lambda t: 1.0 / math.expm1(1.4388e-2 / (8.0e-7 * t)) return depth_ppm * (1.0 / aR ** 2 + planck(T * math.sqrt(1.0 / aR) * (2.0 / 3.0) ** 0.25) / planck(T)) def planets_odd_even_z(t, f, P, t0, dur): """How far apart a dip's odd and even transits lie against the scatter of the transits themselves, the flux F at the times T already flattened: each transit's depth the mean within a quarter of the duration DUR of its centre against the mean between 0.75 and 2 durations of it, the two sets' means set against their pooled scatter, as a normal deviate through Student's t, so that a few transits count for little and neither red noise nor changes from transit to transit pass for a difference; None where the transits give no scatter.""" from scipy import stats dt = ((t - t0) / P + 0.5) % 1.0 * P - 0.5 * P ep = np.round((t - t0) / P).astype(int) depths, epochs = [], [] for k in np.unique(ep[np.abs(dt) < 2.0 * dur]): m = ep == k inn, ring = m & (np.abs(dt) < 0.25 * dur), m & (np.abs(dt) > 0.75 * dur) & (np.abs(dt) < 2.0 * dur) if inn.sum() >= 2 and ring.sum() >= 4: depths.append(float(np.mean(f[ring]) - np.mean(f[inn]))) epochs.append(int(k)) depths, epochs = np.array(depths), np.array(epochs) odd, even = depths[epochs % 2 == 1], depths[epochs % 2 == 0] dof = len(odd) + len(even) - 2 if not len(odd) or not len(even) or dof < 1: return None pooled = (float(np.sum((odd - odd.mean()) ** 2)) + float(np.sum((even - even.mean()) ** 2))) / dof se = math.sqrt(pooled * (1.0 / len(odd) + 1.0 / len(even))) if se <= 0: return None return round(float(stats.norm.isf(stats.t.sf(abs(float(odd.mean() - even.mean())) / se, dof))), 2) def planets_odd_even(v): """Whether a validation record V's odd and even transits differ: 3 sigma against the light curve's noise and, once read (planets_odd_even_z), 3 sigma against the transits' own scatter, or depths half their mean apart at 5 sigma against that noise, as a binary's seen in few transits are.""" sigma = v.get("odd_even_sigma") or 0.0 if sigma < 3.0: return False if "odd_even_z" not in v: return True a, b = v.get("depth_odd_ppm"), v.get("depth_even_ppm") apart = a is not None and b is not None and (a + b <= 0.0 or abs(a - b) >= 0.25 * (a + b)) return (v["odd_even_z"] or 0.0) >= 3.0 or (apart and sigma >= 5.0) # how strongly a candidate's own flattened fold must show its dip to stand, a TOI's as a TOI's selection asks and any other's further, since TRICERATOPS weighs a dip without asking whether it is there and the weakest candidates of a blind search are the least reliable (Thompson et al. 2018) planets_DIP_TOI, planets_MISSION_DIP = 7.1, 10.0 # and Kepler's, whose false positives and false alarms near the spacecraft's year reach further, as its settled candidates show planets_DIP_KEPLER = 15.0 def planets_fold_fault(v, label): """What a validation record V, of the candidate LABEL, holds against its dip being there: a TOI's flattened fold under planets_DIP_TOI, once read, or any other candidate's under planets_MISSION_DIP, a Kepler candidate's under planets_DIP_KEPLER, or a community TOI's signal-to-noise under planets_TRANSIT_NEW times the highest of the same search upside down (planets_noise_ratio), as a signal of orbitlight's own search must, until they are read; the unflattened fold's box stands in where the flattened has not been read.""" d = v.get("dip_sigma") if d is None and v.get("shape_box_chi2") is not None: d = math.sqrt(max(v["shape_box_chi2"], 0.0)) if label.startswith("TOI-"): return "no dip in its fold" if d is not None and d < planets_DIP_TOI else "" if (v.get("dip_sigma") or 0.0) < (planets_DIP_KEPLER if label.startswith("KOI-") else planets_MISSION_DIP): return "no dip in its fold" return "near the noise" if label.startswith("CTOI-") and (v.get("noise_ratio") or 0.0) < planets_TRANSIT_NEW else "" # the limits of a validation (Giacalone et al. 2021), and those within which a candidate that passes every other test is a likely planet, listed apart planets_FPP_VALID, planets_NFPP_VALID, planets_FPP_LIKELY, planets_NFPP_LIKELY = 0.015, 0.001, 0.1, 0.003 # the scenarios in which a dip is a planet's, on the target or on an unresolved star with it: a fainter companion's planet is no false positive, only larger than the target's light gives it (Morton et al. 2016) planets_PLANET_SCENARIOS = ("TP", "PTP", "DTP", "STP", "BTP") def planets_not_planet(v): """The probability that a validation record V's dip is no planet's: its false-positive probability, which counts a planet on the target alone, less the shares of a planet on an unresolved companion (STP) and on an unresolved star behind the target (BTP).""" scen = v.get("scenarios") or {} return max(v["fpp"] - scen.get("STP", 0.0) - scen.get("BTP", 0.0), 0.0) def planets_planet_cols(v): """A validation record V's columns of its planet: the probability that its dip is no planet's, and the share of the planet's probability that lies on the target, its radius larger than given on the rest.""" if "fpp" not in v or not v.get("scenarios"): return {} scen = v["scenarios"] planet = sum(scen.get(k, 0.0) for k in planets_PLANET_SCENARIOS) return dict(not_planet=round(planets_not_planet(v), 6), on_target=round(sum(scen.get(k, 0.0) for k in ("TP", "PTP", "DTP")) / planet, 4) if planet > 0 else "") # how many times rarer a false positive is on a star that holds another live candidate or planet (planets_multi_measure), a false-positive probability under that many times its limit passing there, and the radius (Earth's) from which a giant, on which the settled TOIs bear out little of it, takes none planets_MULTI_BOOST, planets_MULTI_RADIUS = 10.0, 8.0 planets_SIBLINGS = {} def planets_has_sibling(tic, P, ra=float("nan"), dec=float("nan")): """Whether a star holds another live candidate or planet than one of period P: a TOI or community TOI ExoFOP gives for its TIC number TIC, the TFOPWG not having found it false, or a planet the archive lists for the star, at a period that is not P, its half, its double, its third or three times it within 2 per cent.""" if not planets_SIBLINGS: for x in planets_exofop(): if x.get("TFOPWG Disposition", "").strip() not in ("FP", "FA") and planets_num(x.get("Period (days)")) > 0: planets_SIBLINGS.setdefault(str(x["TIC ID"]).strip(), []).append(planets_num(x["Period (days)"])) match = planets_catalogued() periods = planets_SIBLINGS.get(str(tic).strip(), []) + [match.period[n] for n in match(ra, dec, tic, (), None, 10.0) if match.period[n] > 0] return any(all(abs(P / (q * m) - 1.0) >= 0.02 for m in (1.0, 0.5, 2.0, 1.0 / 3.0, 3.0)) for q in periods) def planets_multi_measure(): """What another live candidate or planet on a star is worth among the TOIs the TFOPWG has settled, to RESULTS/multi_boost.json: those of a signal-to-noise of 7.1 or more with one (planets_has_sibling) and without, below planets_MULTI_RADIUS and from it, how many of each it found false, and the ratio of the two odds of being false, half a count added to each, the boost planets_MULTI_BOOST stands within. Returns it.""" out = {} rows = [r for r in planets_candidates("toi") if r["TFOPWG Disposition"].strip() in ("CP", "KP", "FP", "FA") and planets_num(r["Planet SNR"]) >= 7.1 and planets_num(r["Period (days)"]) > 0] for label, sel in (("below", lambda r: planets_num(r["Planet Radius (R_Earth)"]) < planets_MULTI_RADIUS), ("from", lambda r: planets_num(r["Planet Radius (R_Earth)"]) >= planets_MULTI_RADIUS)): tally = dict(sibling=[0, 0], alone=[0, 0]) for r in rows: if sel(r): t = tally["sibling" if planets_has_sibling(r["TIC ID"], planets_num(r["Period (days)"]), *planets_radec(r)) else "alone"] t[0] += 1 t[1] += r["TFOPWG Disposition"].strip() in ("FP", "FA") odds = lambda t: (t[1] + 0.5) / (t[0] - t[1] + 0.5) out[label] = dict(with_sibling=tally["sibling"][0], false_with_sibling=tally["sibling"][1], alone=tally["alone"][0], false_alone=tally["alone"][1], boost=round(odds(tally["alone"]) / odds(tally["sibling"]), 1)) archive_save(os.path.join(planets_RESULTS, "multi_boost.json"), json.dumps(dict(out, radius=planets_MULTI_RADIUS, used=planets_MULTI_BOOST), separators=(",", ":")).encode()) return out # a difference image's reading of a dip's source: the chi-square its place must take out of the images, the error (arcsec) a sector's place holds beside its noise from its file's WCS and a Gaussian's fit of the true shape of a star, and the least a neighbour's share is multiplied by, the chance an image misplaces a source (planets_clear_measure) planets_IMAGE_CHI2, planets_IMAGE_FLOOR, planets_IMAGE_TAIL = 25.0, 2.0, 1e-3 # and how far past the star's chi-square, over the factor that gives the place its error, the image's best place may lie before it clears no neighbour: 4 sigma planets_IMAGE_OFF = 16.0 def planets_image_sector(raw, P, t0, D, nulls=12): """One sector's target pixel file, the open file RAW, as a difference image of the transits of period P days from T0 (BTJD) lasting D days: for each transit the mean image between 0.8 and 2.5 durations on either side, each side weighing alike so that a pixel's slow drift goes, less the mean within 0.4 of a duration, the transits averaged by their points. Each pixel's error is the scatter of the same image at the same windows moved to NULLS other times of the sector, clear of every transit by 2.5 durations, which holds its correlated noise; with fewer than six such times, the scatter of its frames over the root of the points. Returns the image, the errors, the star's width (pixels) from a round Gaussian fitted within 3.5 pixels of it in the mean image, the file's WCS, the star's place at the sector's date, its J2000 place carried by its proper motion, what that motion has carried it (arcsec, east and north), and the transits held; None where the file holds no transit with light on either side.""" from astropy.io import fits from astropy.wcs import WCS from scipy.optimize import least_squares with fits.open(raw) as h: d, ap, H0 = h[1].data, h[2].header, h[0].header t, cube, q = np.asarray(d["TIME"], float), np.asarray(d["FLUX"], float), np.asarray(d["QUALITY"]) w = WCS(ap) ra, dec, pmra, pmdec = float(H0["RA_OBJ"]), float(H0["DEC_OBJ"]), archive_num(H0.get("PMRA"), 0.0), archive_num(H0.get("PMDEC"), 0.0) keep = np.isfinite(t) & (q == 0) & (np.isfinite(cube).sum((1, 2)) > 0) t, cube = t[keep], cube[keep] if len(t) < 50: return None good = np.isfinite(cube) S = np.concatenate([np.zeros((1,) + cube.shape[1:]), np.cumsum(np.where(good, cube, 0.0), axis=0)]) N = np.concatenate([np.zeros((1,) + cube.shape[1:]), np.cumsum(good, axis=0)]) def mean(a, b): i, j = int(np.searchsorted(t, a)), int(np.searchsorted(t, b)) if j <= i: return None, 0 with np.errstate(divide="ignore", invalid="ignore"): return (S[j] - S[i]) / (N[j] - N[i]), j - i def image(mids): total, weight, count = None, 0.0, 0 for c in mids: inn, n_in = mean(c - 0.4 * D, c + 0.4 * D) before, n_b = mean(c - 2.5 * D, c - 0.8 * D) after, n_a = mean(c + 0.8 * D, c + 2.5 * D) if n_in < 1 or n_b < 1 or n_a < 1: continue x = 0.5 * (before + after) - inn total = n_in * x if total is None else total + n_in * x weight, count = weight + n_in, count + 1 return (total / weight, weight, count) if count else (None, 0.0, 0) mids = t0 + P * np.arange(math.ceil((t.min() - D - t0) / P), math.floor((t.max() + D - t0) / P) + 1) if not len(mids): return None img, weight, count = image(mids) if img is None: return None span = float(t.max() - t.min()) null = [] for shift in np.linspace(-0.5 * span, 0.5 * span, 4 * nulls): c = mids + shift if np.min(np.abs(c[:, None] - mids[None, :])) > 2.5 * D: got, _, n_ = image(c) if got is not None and n_ >= max(1, count // 2): null.append(got) err = np.nanstd(np.array(null), axis=0) if len(null) >= 6 else np.nanstd(cube, axis=0) * math.sqrt(1.5 / max(weight, 1.0)) err = np.where(np.isfinite(err) & (err > 0), err, np.nanmedian(err)) years = (float(np.median(t)) + 2457000.0 - 2451545.0) / 365.25 east, north = pmra * years / 1000.0, pmdec * years / 1000.0 ra_now, dec_now = ra + east / 3600.0 / math.cos(math.radians(dec)), dec + north / 3600.0 sx, sy = (float(x) for x in w.all_world2pix([[ra_now, dec_now]], 0)[0]) frame = np.nanmean(cube, 0) y, x = np.mgrid[0:frame.shape[0], 0:frame.shape[1]] near = np.isfinite(frame) & (np.hypot(x - sx, y - sy) <= 3.5) width = 0.85 if near.sum() >= 8: med = float(np.nanmedian(frame[near])) noise = np.sqrt(np.maximum(np.abs(frame), 1.0)) def resid(p): return ((p[0] * np.exp(-0.5 * ((x - p[1]) ** 2 + (y - p[2]) ** 2) / p[3] ** 2) + p[4] - frame) / noise)[near] try: width = float(least_squares(resid, [float(np.nanmax(frame[near])) - med, sx, sy, 0.85, med], bounds=([0.0, -1.0, -1.0, 0.5, -np.inf], [np.inf, frame.shape[1], frame.shape[0], 1.6, np.inf]), max_nfev=50).x[3]) except ValueError: pass return dict(img=img, err=err, width=width, w=w, ra=ra_now, dec=dec_now, moved=(east, north), transits=count) def planets_image_surface(images, east, north): """The chi-square a Gaussian takes out of each of IMAGES (planets_image_sector), of the sector's width, with an amplitude and a flat background free in each, at the places EAST and NORTH (arcsec from each image's star, arrays of one length): (sectors, places), a place of negative amplitude taking out nothing.""" out = np.zeros((len(images), len(east))) for k, m in enumerate(images): px = m["w"].all_world2pix(np.column_stack([m["ra"] + east / (3600.0 * math.cos(math.radians(m["dec"]))), m["dec"] + north / 3600.0]), 0) ok = np.isfinite(m["img"]) y, x = np.mgrid[0:m["img"].shape[0], 0:m["img"].shape[1]] wt, data = 1.0 / m["err"][ok] ** 2, m["img"][ok] G = np.exp(-0.5 * ((x[ok][None, :] - px[:, 0, None]) ** 2 + (y[ok][None, :] - px[:, 1, None]) ** 2) / m["width"] ** 2) W = wt.sum() Gm = (G * wt).sum(1) / W top = (G * (wt * (data - float((wt * data).sum()) / W))).sum(1) bottom = (G * G * wt).sum(1) - W * Gm * Gm out[k] = np.where((top > 0) & (bottom > 0), top * top / np.maximum(bottom, 1e-30), 0.0) return out def planets_image_read(tic, P, t0, D, most=8): """A transit's difference images (planets_image_sector) from MAST's bucket, SPOC's target pixel files where any covers a transit, else TESS-SPOC's, MOST sectors at most, spread evenly, each marked with its kind.""" tics, secs, kinds, sectors = planets_tess_index() a, b = int(np.searchsorted(tics, tic)), int(np.searchsorted(tics, tic, side="right")) t0m, images = t0 + 56999.5, [] for kind in (0, 1): held = sorted(s for s, k in zip(secs[a:b].tolist(), kinds[a:b].tolist()) if k == kind and "t0" in sectors.get(s, {}) and math.ceil((sectors[s]["t0"] - t0m) / P) * P + t0m <= sectors[s]["t1"]) held = [held[int(j)] for j in np.unique(np.linspace(0, len(held) - 1, most).round())] if len(held) > most else held for s in held: raw = archive_get(planets_TESS_BUCKET + planets_tess_key(tic, s, kind, sectors).replace("_lc.fits", "_tp.fits"), timeout=300, soft=True) if raw: got = planets_image_sector(io.BytesIO(raw), P, t0, D) if got: images.append(dict(got, kind=kind)) if images: break return images def planets_image_fit(images): """One place on the sky fitted to all a transit's difference images at once (planets_image_surface), on a grid of 3 arcsec about the star and then of half an arcsec about the best. Returns its offset from the star (arcsec, east and north, offset), its error from that surface's curvature, scaled by the fit's reduced chi-square and joined to planets_IMAGE_FLOOR over the root of the sectors, the chi-square it takes out (chi2), the chi-square the star's own place takes out (star_chi2), by how much a chi-square's differences are to be divided to give that error (factor), what its proper motion has carried the star since J2000 (moved), and the sectors and transits held.""" grid = np.arange(-105.0, 105.1, 3.0) ee, nn = np.meshgrid(grid, grid) f = planets_image_surface(images, ee.ravel(), nn.ravel()).sum(0) i = int(np.argmax(f)) fine = np.arange(-4.0, 4.1, 0.5) fe, fn = np.meshgrid(float(ee.ravel()[i]) + fine, float(nn.ravel()[i]) + fine) g = planets_image_surface(images, fe.ravel(), fn.ravel()).sum(0) j = int(np.argmax(g)) east, north, top = float(fe.ravel()[j]), float(fn.ravel()[j]), float(g[j]) chi, dof = 0.0, 0 for m in images: px = m["w"].all_world2pix([[m["ra"] + east / (3600.0 * math.cos(math.radians(m["dec"]))), m["dec"] + north / 3600.0]], 0)[0] ok = np.isfinite(m["img"]) y, x = np.mgrid[0:m["img"].shape[0], 0:m["img"].shape[1]] A = np.column_stack([np.exp(-0.5 * ((x[ok] - px[0]) ** 2 + (y[ok] - px[1]) ** 2) / m["width"] ** 2), np.ones(int(ok.sum()))]) / m["err"][ok][:, None] chi += float(np.sum((m["img"][ok] / m["err"][ok] - A @ np.linalg.lstsq(A, m["img"][ok] / m["err"][ok], rcond=None)[0]) ** 2)) dof += int(ok.sum()) - 2 scale = max(chi / max(dof, 1), 1.0) h = 2.0 around = planets_image_surface(images, np.array([east - h, east + h, east, east]), np.array([north, north, north - h, north + h])).sum(0) # the surface falls by (x / sigma)^2 from its top, its second difference 2 / sigma^2 var = 0.5 * (2.0 * h ** 2 / max(2.0 * top - around[0] - around[1], 1e-9) + 2.0 * h ** 2 / max(2.0 * top - around[2] - around[3], 1e-9)) err2 = scale * var + planets_IMAGE_FLOOR ** 2 / len(images) return dict(east=round(east, 2), north=round(north, 2), offset=round(math.hypot(east, north), 2), err=round(math.sqrt(err2), 2), chi2=round(top, 1), star_chi2=round(float(planets_image_surface(images, np.array([0.0]), np.array([0.0])).sum()), 1), factor=round(err2 / var, 3), scale=round(scale, 2), moved=[round(float(np.mean([m["moved"][k] for m in images])), 2) for k in (0, 1)], sectors=len(images), transits=sum(m["transits"] for m in images), light_curves="SPOC" if images[0]["kind"] == 0 else "TESS-SPOC") def planets_image_at(images, place, near): """The chi-square a Gaussian at each nearby star's own place takes out of a transit's difference images (planets_image_surface), NEAR its stars with their separations and position angles (planets_validate_one's near_probs) in the TIC's J2000 and PLACE its fit (planets_image_fit), the star carried by its motion: star to chi-square.""" if not near: return {} ids = sorted(near) east = np.array([near[i][0] * math.sin(math.radians(near[i][1])) - place["moved"][0] for i in ids]) north = np.array([near[i][0] * math.cos(math.radians(near[i][1])) - place["moved"][1] for i in ids]) return dict(zip(ids, (round(float(x), 1) for x in planets_image_surface(images, east, north).sum(0)))) def planets_source_cleared(v): """The probability that a validation record V's dip is no planet's (planets_not_planet) and its nearby-false-positive probability with its difference images read into them: each nearby star's share of the probability (near_probs) multiplied by the likelihood of the images at that star against at the star itself, half the difference of the chi-squares a Gaussian at each takes out over the factor that gives the place its error (planets_image_fit, planets_image_at), held within planets_IMAGE_TAIL and its inverse, the chance an image misplaces a source, where it holds an image whose place takes out planets_IMAGE_CHI2 and those shares, an image whose place lies planets_IMAGE_OFF off the star lowering none of them; and without a star eclipsing the target (planets_TARGET_BINARIES) where Gaia's velocities leave it no room (planets_no_room).""" s, near, scen = v.get("source") or {}, v.get("near_probs"), v.get("scenarios") if not scen: return v["fpp"], v["nfpp"] weighed = v["nfpp"] if near is not None and s.get("chi2", 0.0) >= planets_IMAGE_CHI2 and "at" in s: least = 1.0 if (s["chi2"] - s["star_chi2"]) / s["factor"] > planets_IMAGE_OFF else planets_IMAGE_TAIL weighed = sum(p * min(max(math.exp(max(min(0.5 * (s["at"].get(i, 0.0) - s["star_chi2"]) / s["factor"], 500.0), -500.0)), least), 1.0 / planets_IMAGE_TAIL) for i, (_, _, p) in near.items()) total = sum(x for k, x in scen.items() if k not in ("NTP", "NEB", "NEBx2P") and not (k in planets_TARGET_BINARIES and planets_no_room(v))) + weighed return (1.0 - sum(scen.get(k, 0.0) for k in planets_PLANET_SCENARIOS) / total, weighed / total) if total > 0 else (planets_not_planet(v), v["nfpp"]) def planets_validation_decision(v, x, rv, events): """A validation record's decision from its own evidence, before any catalogue: (status, reason, vetting columns), the status None for a pass still waiting for its runs, and likely for a candidate that passes every test at the likely limits and not at a validation's.""" P = v.get("period", planets_num(x.get("Period (days)"))) radius = planets_num(x.get("Planet Radius (R_Earth)")) if "fpp" not in v: note = v.get("note", "") return "rejected", "no light curve" if "light curve" in note else "inside the star" if "inside the star" in note else \ "duration" if note.startswith("duration") else "no stellar parameters" if "stellar" in note else "analysis failed", {} if rv and (rv["object"] in ("star", "brown dwarf") and rv["status"] != "rejected" or rv["reason"] == "phase"): return "rejected", "velocities", {} if math.isfinite(radius) and radius >= 22.4: return "rejected", "radius", {} # the probabilities as its difference image leaves them fpp, nfpp = planets_source_cleared(v) valid = fpp < planets_FPP_VALID and nfpp < planets_NFPP_VALID # on a star with another live candidate or planet the limit is planets_MULTI_BOOST times higher, on the means of ten runs boosted = not valid and fpp < planets_MULTI_BOOST * planets_FPP_VALID and nfpp < planets_NFPP_VALID and v.get("runs", 0) >= 10 and radius < planets_MULTI_RADIUS and planets_has_sibling(v.get("tic") or x.get("TIC ID"), P, *planets_radec(x)) valid = valid or boosted if not valid and not (fpp < planets_FPP_LIKELY and nfpp < planets_NFPP_LIKELY): return "rejected", "not validated", {} # a pass stands on the means of ten runs, the light curves' checks and SPOC's data validation of its event if valid and v.get("runs", 0) < 10: return None, "", {} # a dip half an orbit on is an eclipse where it lies 3 sigma or more beyond the deepest occultation a planet could give 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 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 planets_odd_even(v) 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 "a double star in Gaia" if (v.get("gaia_nss") or 0.0) > 0.0 or planets_rv_moving(v) 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), multiplicity_boost=planets_MULTI_BOOST if boosted else "", **checks) if (v.get("source") or {}).get("offset") is not None: cols.update(source_offset=v["source"]["offset"], source_err=v["source"]["err"], fpp_image=round(fpp, 6), nfpp_image=round(nfpp, 6)) return ("rejected" if own or why else "new" if valid else "likely"), own or why, cols def planets_validated_rows(tois): """The TESS candidates validated statistically (RESULTS/validate/, planets_validate) as decided signals.csv rows. A candidate is new where the probability that its dip is no planet's (planets_not_planet) lies below 0.015 and its nearby-false-positive probability below 0.001 (the limits of Giacalone et al. 2021), each the mean of ten runs, as its difference image leaves them (planets_source_cleared), 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, 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 candidate the archive lists in any published solution (planets_catalogued) or the TFOPWG now gives as a known or confirmed planet is known, an independent validation where it passes; one the TFOPWG now gives as a false positive or false alarm, or whose period ExoFOP has moved by more than 1 per cent from the one it was weighed at, is rejected. ExoFOP's tables are read again once a day old.""" folder = os.path.join(planets_RESULTS, "validate") exo = {x["label"]: x for x in planets_exofop(1.0)} listed_in = planets_catalogued() weighed = {r["label"]: r for r in tois} recs = [json.load(open(path)) for path in sorted(glob.glob(os.path.join(folder, "*.json")))] events = planets_tce({v["tic"] for v in recs if "fpp" in v and planets_source_cleared(v)[0] < planets_FPP_LIKELY and planets_source_cleared(v)[1] < planets_NFPP_LIKELY}) out = [] # Kepler's and K2's candidates enter once the benchmark of their settled ones bears them out (planets_mission_scored) scored = {m for m, source in (("Kepler", "koi"), ("K2", "k2")) if planets_mission_scored(source)} for v in recs: label = v.get("label") or "TOI-" + v["toi"] x, rv = exo.get(label, {}), weighed.get(label) if rv and rv["status"] == "new" or x.get("mission") and x["mission"] not in scored: continue fpp, nfpp = (max(v[k], 0.0) if k in v else "" for k in ("fpp", "nfpp")) row = dict(name="TIC %s" % v["tic"], kind="validated", label=label, nights="", span_d="", P=v.get("period", planets_num(x.get("Period (days)"))), K="", e="", msini_mjup="", msini_mearth="", fap="%.1e" % fpp if "fpp" in v else "", object="planet", catalogued="", fpp=fpp, nfpp=nfpp, radius_rearth=x.get("Planet Radius (R_Earth)", "")) status, reason, cols = planets_validation_decision(v, x, rv, events) if status is None: continue # a likely planet stands on the checks planets_validate_checks reads if status == "likely" and "checks_read" not in v: status, reason = "rejected", "not validated" if status in ("new", "likely") and planets_fold_fault(v, label): status, reason = "rejected", planets_fold_fault(v, label) row.update(cols, status=status, reason=reason, **planets_planet_cols(v)) disp = x.get("TFOPWG Disposition", "") ra, dec = planets_radec(x) if x else (float("nan"), float("nan")) cat = listed_in(ra, dec, v["tic"], (), planets_num(row["P"])) if cat or disp in ("KP", "CP"): row.update(contribution="independent validation" if row["status"] == "new" else "", status="known", reason="catalogued", catalogued="; ".join(["archive %s" % n for n in cat] + (["TFOPWG %s" % disp] if disp in ("KP", "CP") else []))) elif disp in ("FP", "FA"): row.update(status="rejected", reason="TFOPWG %s" % disp) elif "fpp" in v and abs(planets_num(x.get("Period (days)")) / planets_num(row["P"]) - 1.0) > 0.01: row.update(status="rejected", reason="ephemeris revised") elif row["status"] == "new": row["contribution"] = "statistical validation" out.append(row) return out def planets_list(rows, stars): """The new planets and companions of ROWS for RESULTS/planets.csv, named after their hosts and lettered after the archive's planets of the same star, and after them the likely planets for RESULTS/likely_planets.csv, lettered after those, each with its status.""" new = [r for r in rows if r["status"] in ("new", "likely")] simbad = {r["name"]: (stars.get(r["name"], {}).get("SimbadName") or r["name"]).strip() for r in new} main = archive_simbad_basic(sorted(set(simbad.values()) | {r["name"] for r in new}), ("main_id",)) def host_of(name): found = (main.get(simbad[name]) or main.get(name) or {}).get("main_id") if not found and name in stars: found = archive_simbad_near(planets_num(stars[name].get("RAJ2000")), planets_num(stars[name].get("DEJ2000"))) return " ".join((found or name).split()) taken = {} for r in rows: if r["kind"] == "known" and r["label"][-1:].isalpha() and r["label"][-2:-1] == " ": taken[r["name"]] = max(taken.get(r["name"], "a"), r["label"][-1].lower()) # a validated community TOI is named after a TOI validated on its star, else after its star stems = {r["name"]: r["label"].split(".")[0] for r in rows if r["kind"] == "validated" and r["label"].startswith("TOI-")} exo = {x["label"]: x for x in planets_exofop()} kept = planets_path("stellar.json") stellar = json.load(open(kept)) if os.path.exists(kept) else {} def star_of(r): # the star's temperature, radius and mass with the planet's radius: ExoFOP's for a TESS candidate, else Gaia DR3's FLAME for the bank's star, # kept in ROOT/stellar.json x = exo.get(r["label"]) if r["kind"] in ("validated", "toi") and x: return [archive_num(x.get(k)) for k in ("Stellar Eff Temp (K)", "Stellar Radius (R_Sun)", "Stellar Mass (M_Sun)", "Planet Radius (R_Earth)")] s = stars.get(r["name"]) if s and archive_num(s.get("Mass")): stellar[r["name"]] = [archive_num(s.get("Teff")), archive_num(s.get("Rad")), archive_num(s.get("Mass"))] elif s and r["name"] not in stellar: try: g = archive_gaia_star(float(s["RAJ2000"]), float(s["DEJ2000"]), archive_num(s.get("Vmag"))) or {} except Exception: g = {} stellar[r["name"]] = [archive_num(g.get("teff_gspphot")), archive_num(g.get("radius_flame")), archive_num(g.get("mass_flame")) or planets_mass(s.get("SpType"))] # a transit the blind search found gives its radius from its depth, and one of the TESS stage its star from its light curve's header if r["kind"] == "transit" and r.get("star"): return [archive_num(x) for x in r["star"]] + [archive_num(r.get("radius_rearth"))] return stellar.get(r["name"], [None] * 3) + [archive_num(r.get("radius_rearth")) if r["kind"] == "transit" else None] def mags_of(r): # a TESS candidate's star's J and K magnitudes from the TIC (planets_tic_cone), kept in ROOT/stellar.json x = exo.get(r["label"]) if r["kind"] not in ("validated", "toi") or not x: return None, None key = "mags TIC %d" % int(x["TIC ID"]) if key not in stellar: try: row = next(s for s in planets_tic_cone(int(x["TIC ID"])) if str(s["ID"]) == str(int(x["TIC ID"]))) except Exception: return None, None stellar[key] = [archive_num(row["Jmag"]), archive_num(row["Kmag"])] return tuple(stellar[key]) match, discoverer, eu = planets_catalogued(), planets_discoverers(), planets_encyclopaedia() hosts = dict(eu.host, **match.host) def archived(r): # 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["status"] != "new", x["name"], float(x["P"]))): host = host_of(r["name"]) listed = archived(r) if r["object"] != "star" else [] if r["object"] == "star": letter = "B" else: letter = chr(ord(max([taken.get(r["name"], "a"), chr(ord("a") + len(listed))] + [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 = 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"])) sunlight, teq, zone = planets_sunlight(P, teff, rs, ms) # 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"] 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", "transit": "transit search", "astrometry": "astrometry"}[r["kind"]], status=r["status"], contribution=planets_CONTRIBUTION[r["kind"]] if r["status"] == "new" else "likely planet", discovered_by=discoverer(r), candidate=r["label"] if r["kind"] in ("validated", "toi") else "", 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=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", ""), 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", ""), dr4_test=r.get("dr4_test", ""), dr4_ln_bayes=r.get("dr4_ln_bayes", ""), dr4_control=r.get("dr4_control", ""), dr4_snr_least=r.get("dr4_snr_least", ""), dr4_mass_mjup=r.get("dr4_mass_mjup", ""), dr4_mass_lo=r.get("dr4_mass_lo", ""), dr4_mass_hi=r.get("dr4_mass_hi", ""), dr4_incl_deg=r.get("dr4_incl_deg", ""), fpp=r.get("fpp", ""), nfpp=r.get("nfpp", ""), multiplicity_boost=r.get("multiplicity_boost", ""), not_planet=r.get("not_planet", ""), on_target=r.get("on_target", ""), source_offset=r.get("source_offset", ""), source_err=r.get("source_err", ""), fpp_image=r.get("fpp_image", ""), nfpp_image=r.get("nfpp_image", ""), 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=(",", ":")) return out # Kopparapu et al.'s (2014) habitable zone, its recent-Venus and early-Mars edges: each edge's sunlight (Earth's) as S + a T + b T^2 + c T^3 + d T^4, # T the star's temperature less 5780 K, from 2600 to 7200 K planets_HZ = ((1.776, 2.136e-4, 2.533e-8, -1.332e-11, -3.097e-15), (0.320, 5.547e-5, 1.526e-9, -2.874e-12, -5.011e-16)) def planets_sunlight(P, teff, radius, mass): """The sunlight (Earth's) of an orbit of P days about a star of TEFF K and RADIUS and MASS solar, its equilibrium temperature (K, no albedo and the heat spread over the planet) and its place against the habitable zone (planets_HZ, the star's temperature held within 2600 to 7200 K): inside, hotter or colder; Nones where a value is missing.""" if not (P and P > 0 and teff and teff > 0 and radius and radius > 0 and mass and mass > 0): return None, None, None S = radius ** 2 * (teff / 5772.0) ** 4 / (mass * (P / 365.25) ** 2) ** (2.0 / 3.0) T = min(max(teff, 2600.0), 7200.0) - 5780.0 hot, cold = (sum(c * T ** i for i, c in enumerate(edge)) for edge in planets_HZ) return S, 278.6 * S ** 0.25, "hotter" if S > hot else "colder" if S < cold else "inside" # Chen and Kipping's (2017) mean mass-radius relation, R = C M^s in Earth's units, over the masses of each regime: rocky, Neptunian and Jovian planets_MR = ((2.04, 1.0, 0.279), (132.0, 0.80811, 0.589), (26600.0, 17.74, -0.044)) def planets_radius_of(mass): """The radius (Earth's) Chen and Kipping's relation gives a mass (Earth's); None beyond the Jovian regime.""" return next((c * mass ** s for hi, c, s in planets_MR if mass < hi), None) def planets_mass_of(radius): """The mass (Earth's) Chen and Kipping's relation gives a radius (Earth's) in its rocky and Neptunian regimes; None above them, where a giant's radius no longer tells its mass.""" for hi, c, s in planets_MR[:2]: mass = (radius / c) ** (1.0 / s) if mass < hi: return mass return None def planets_character(body, P, teff, rs, ms, radius, mass, basis, jmag, kmag, teq): """A body's inferred character for planets.csv, from its period P (days), its star's temperature TEFF (K), radius RS and mass MS (solar), its radius from a transit and its MASS (Earth's) of BASIS measured or minimum, with the star's J and K magnitudes and the equilibrium temperature TEQ: the orbit's size; the radius from the mass or the mass from the radius where only one is known (planets_radius_of, planets_mass_of); the density, surface gravity and escape speed; a composition by radius (a brown dwarf or star by mass) and a character by equilibrium temperature and size; tidal locking expected where Gladman et al.'s (1996) time for it from a 12-hour spin lies within 1 Gyr (Q 100 and k2 0.3 below 1.6 Earth radii, Q 1e5 and k2 0.5 above, a moment of inertia of 0.3 M R^2); the star's colour and its apparent diameter in the planet's sky; and for a transiting planet the transmission and emission spectroscopy metrics of Kempton et al. (2018).""" out = dict.fromkeys(("a_au", "mass_mearth", "mass_basis", "radius_rearth", "radius_basis", "density_gcc", "gravity_earth", "escape_kms", "composition", "character", "tidally_locked", "star_color", "star_in_sky_deg", "tsm", "esm"), "") a = (ms * (P / 365.25) ** 2) ** (1.0 / 3.0) if ms and P else None if teff: out["star_color"] = "red" if teff < 3700 else "orange" if teff < 5200 else "yellow" if teff < 6000 else "yellow-white" if teff < 7500 else \ "white" if teff < 10000 else "blue-white" if a: out["a_au"] = round(a, 4) if rs: out["star_in_sky_deg"] = round(2.0 * math.degrees(math.asin(min(1.0, rs * 0.0046505 / a))), 2) if body == "star": out["composition"] = "star" return out rbasis = "transit" if radius else "" if not radius and mass: radius, rbasis = planets_radius_of(mass), "predicted" if not mass and radius: mass, basis = planets_mass_of(radius), "predicted" out.update(radius_basis=rbasis, mass_basis=basis if mass else "", radius_rearth=round(radius, 2) if radius else "") if mass: out["mass_mearth"] = round(mass, 2) if body == "brown dwarf": out["composition"] = "brown dwarf" elif radius: out["composition"] = "rocky" if radius < 1.5 else "rocky or water-rich" if radius < 2.0 else \ "sub-Neptune: a rocky core under hydrogen, or a water world" if radius < 4.0 else "Neptune-like" if radius < 6.0 else "sub-Saturn" if radius < 8.0 \ else "gas giant" if radius and mass: out.update(density_gcc=round(5.514 * mass / radius ** 3, 2), gravity_earth=round(mass / radius ** 2, 2), escape_kms=round(11.186 * math.sqrt(mass / radius), 1)) if radius and teq: size = "rocky planet" if radius < 1.5 else "super-Earth" if radius < 2.0 else "sub-Neptune" if radius < 4.0 else "Neptune" if radius < 6.0 else \ "sub-Saturn" if radius < 8.0 else "Jupiter" heat = "temperate" if teq < 350 else "warm" if teq < 800 else "hot" if teq < 2000 else "ultra-hot" out["character"] = "lava world" if radius < 2.0 and teq >= 1200 else ("ultra-short-period " if P < 1.0 else "") + heat + " " + size if a and radius and mass and ms: Q, k2 = (100.0, 0.3) if radius < 1.6 else (1e5, 0.5) lock = (2.0 * math.pi / 43200.0) * (a * 1.496e11) ** 6 * 0.3 * mass * 5.972e24 * Q / (3.0 * 6.674e-11 * (ms * 1.989e30) ** 2 * k2 * (radius * 6.371e6) ** 3) out["tidally_locked"] = "expected" if lock < 3.156e16 else "" if rbasis == "transit" and radius and teq and rs: if mass and jmag is not None: scale = 0.190 if radius < 1.5 else 1.26 if radius < 2.75 else 1.28 if radius < 4.0 else 1.15 out["tsm"] = round(scale * radius ** 3 * teq / (mass * rs ** 2) * 10.0 ** (-jmag / 5.0), 1) if teff and kmag is not None: planck = lambda t: 1.0 / math.expm1(1.4388e-2 / (7.5e-6 * t)) out["esm"] = round(4.29e6 * planck(1.10 * teq) / planck(teff) * (radius * 0.009158 / rs) ** 2 * 10.0 ** (-kmag / 5.0), 1) return out planets_CONTRIBUTION = {"found": "discovery", "eccentric": "discovery", "companion": "discovery", "transit": "discovery", "astrometry": "discovery", "toi": "mass confirmation", "validated": "statistical validation"} planets_DISCOVERER = "CharlesCNorton" def planets_discoverers(): """Who first found a signal: for a TESS candidate, the pipeline that raised its TOI (SPOC or QLP) or the submitter of its community TOI; planets_DISCOVERER otherwise.""" exo = {x["label"]: x for x in planets_exofop()} promoted = {re.sub(r"[^0-9.]", "", x.get("Promoted to TOI") or ""): x for k, x in exo.items() if k.startswith("CTOI-") and (x.get("Promoted to TOI") or "").strip()} community = lambda x: "%s%s, community TOI" % (x.get("User") or "unnamed", " (%s)" % x["Group"] if (x.get("Group") or "").strip() else "") def of(r): if r["kind"] not in ("validated", "toi"): return planets_DISCOVERER x = exo.get(r["label"], {}) if x.get("mission"): return x["mission"] if r["label"].startswith("CTOI-"): return community(x) if r["label"][4:] in promoted: return community(promoted[r["label"][4:]]) source = (x.get("Source") or "").strip() return "TESS SPOC" if source.lower().startswith("spoc") else "TESS QLP" if source.lower().startswith("qlp") else ("TESS " + source).strip() return of planets_DECISION_KEYS = ["status", "reason", "contribution", "discovered_by", "object", "prediction", "orbit_P", "orbit_P_lo", "orbit_P_hi", "orbit_msini_mearth", "orbit_msini_mearth_lo", "orbit_msini_mearth_hi", "orbit_e", "orbit_e_lo", "orbit_e_hi", "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", "fap_hires", "fap_hires2", "fap_carmenes", "fap_carmenes2", "fap_sophie", "fap_harps-n", "fap_harps-n2", "fap_neid", "fap_elodie", "dbic", "aliases_excluded", "tess_power", "tess_radius_limit_rearth", "rotation_d", "activity_model", "ruwe", "pma_snr", "catalogued", "fpp", "nfpp", "multiplicity_boost", "not_planet", "on_target", "source_offset", "source_err", "fpp_image", "nfpp_image", "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", "centroid_arcsec", "centroid_err", "centroid_sigma", "gaia_vbroad", "spin_ratio", "gaia_nss", "gaia_rv_scatter", "gaia_rv_gof", "second_instrument", "second_nights", "second_scale", "second_scale_err", "second_phase_sigma", "second_test", "dr4_test", "dr4_ln_bayes", "dr4_control", "dr4_snr_least", "dr4_mass_mjup", "dr4_mass_lo", "dr4_mass_hi", "dr4_incl_deg"] def planets_followup(workers=6, report=False): """Every signal decided into RESULTS/signals.csv and the new bodies listed in RESULTS/planets.csv; REPORT re-decides from saved results.""" sig = [r for r in planets_read(os.path.join(planets_RESULTS, "signals.csv")) if r["kind"] in ("known", "found")] stars = {r["Name"]: r for r in planets_read(planets_path("bank_stars.csv"))} # Candidates from the eccentric-orbit search (planets eccentric) that carry no flags and lie more than 5% in period from every census signal of the # same star are vetted and decided in the same way as census signals. epath = os.path.join(planets_RESULTS, "eccentric", "candidates.csv") for x in (planets_read(epath) if os.path.exists(epath) else []): if x["flags"] or any(s["name"] == x["name"] and abs(float(s["P"]) / float(x["P"]) - 1.0) < 0.05 for s in sig): continue sig.append(dict(name=x["name"], sptype=x["sptype"], vmag=stars.get(x["name"], {}).get("Vmag", ""), host="", kind="eccentric", label="eccentric orbit", nights=x["nights"], span_d=x["span_d"], P=x["P"], K=x["K"], e=x["e"], msini_mjup=round(float(x["msini_mearth"]) / 317.83, 4), msini_mearth=x["msini_mearth"], fap=x["fap"], flags="")) heavy = lambda r: r["kind"] in ("found", "eccentric") and (float(r["msini_mjup"]) > 13.0 or float(r["K"]) >= 100.0) routed = {r["name"] for r in sig if heavy(r)} for r in sig: r.update(dict.fromkeys(planets_DECISION_KEYS, ""), object=planets_object(float(r["msini_mjup"]))) # a companion's signal is decided in its star's companion row r.update(status="known") if r["kind"] == "known" else r.update(status="rejected", reason="companion") if heavy(r) else \ r.update(status="rejected", reason="flagged") if r["flags"] else None cand = [r for r in sig if not r["status"]] kept, aside = planets_triage(cand, stars) for r, why in aside: r.update(status="known" if "archive planet" in why else "rejected", reason="; ".join(why)) jobs = {} for r in kept: jobs.setdefault(r["name"], []).append(float(r["P"])) # with REPORT each star's saved vet record, and a fresh vet for those without one saved = {n: os.path.join(planets_RESULTS, "vet", archive_tag(n) + ".json") for n in jobs} if report else {} vet = {n: v for n, v in ((n, json.load(open(p))) for n, p in saved.items() if os.path.exists(p)) if all(any(abs(P / q - 1.0) < 1e-9 for q in v["periods"]) for P in jobs[n])} vet.update(planets_vet([(n, ps) for n, ps in jobs.items() if n not in vet], show=False) if len(vet) < len(jobs) else {}) follow, cands = {}, {} for r in kept: P = float(r["P"]) held, failed, ind, text = planets_verdict(vet[r["name"]], P) cands[(r["name"], P)] = r act = planets_activity_result(r["name"], P) if act and act.get("verdict") in ("held", "failed"): r["activity_model"] = planets_activity_text(act) # a signal an indicator marks is followed where the star's activity, modelled, leaves it standing (planets_activity) if planets_families(held) >= 2 and (not ind or planets_activity_ready(r["name"], P)): follow.setdefault(r["name"], []).append(P) else: r.update(status="rejected", reason="activity indicator" if ind else "one reduction") known = {} for s in sig: if s["kind"] == "known": known.setdefault(s["name"], []).append((s["label"], float(s["P"]))) # the followed stars' catalogued companions simbad = {n: (stars.get(n, {}).get("SimbadName") or n).strip() for n in follow} linked = archive_simbad_companions(sorted(set(simbad.values()))) catalogued = {n: ["%s %.4g d" % kp for kp in known.get(n, [])] + ["%s (SIMBAD %s)" % c[:2] for c in linked.get(simbad[n], [])] for n in follow} # SIMBAD's companions without an archive period, the archive's planets matched to SIMBAD's objects archived = archive_simbad_oids(sorted({lb for n in follow for lb, _ in known.get(n, [])})) unexplained = {n: [m for m, _, o in linked.get(simbad[n], []) if o not in {archived.get(lb) for lb, _ in known.get(n, [])} and archive_simbad_key(m) not in {archive_simbad_key(lb) for lb, _ in known.get(n, [])}] for n in follow} # the bank's stars beyond the census that vary as a companion's would, the census's companion stars beside them census = {r["name"] for r in planets_read(os.path.join(planets_RESULTS, "stars.csv"))} varying = planets_varying(planets_bank_series(), stars, census) explained = planets_catalogue(sorted(varying), stars) rows, analyse = [], set(routed) for n, nights in sorted(varying.items()): if explained[n] or nights < 10: s = stars[n] rows.append(dict(name=n, sptype=s.get("SpType", ""), vmag=s.get("Vmag", ""), kind="companion", label="variation", nights=nights, status="known" if explained[n] else "rejected", reason="catalogued" if explained[n] else "few nights", catalogued="; ".join(explained[n]))) else: analyse.add(n) folder = planets_path("followup") os.makedirs(folder, exist_ok=True) def run(name, args, log): """Run one star's follow-up in a separate process, logging to ROOT/followup/LOG and retrying once on failure. With REPORT, saved results are reused, except that a star is rerun when its saved system analysis lacks one of its periods, and a companion analysis is run when none is saved or the saved one failed for want of the primary star's mass.""" saved = os.path.join(planets_RESULTS, "companion", archive_tag(name) + ".json") system = os.path.join(planets_RESULTS, "system", archive_tag(name), "analysis.json") rerun = (args[0] == "--companion" and (not os.path.exists(saved) or "no primary mass" in json.load(open(saved)).get("weigh_error", ""))) or \ (args[0] == "--star" and not (os.path.exists(system) and all(any(abs(float(P) / q - 1.0) < 1e-9 for q in json.load(open(system))["periods"]) for P in args[3].split(",")))) if report and not rerun: return name, 0 cmd = [sys.executable, "-u", os.path.abspath(__file__), "planets", "followup"] + args for _ in range(2): with open(os.path.join(folder, log), "w", encoding="utf-8") as fh: code = subprocess.run(cmd, stdout=fh, stderr=subprocess.STDOUT).returncode if code == 0: break return name, code tasks = [(n, ["--star", n, "--periods", ",".join(repr(P) for P in follow[n]), "--known", ",".join(repr(P) for _, P in known.get(n, []))], archive_tag(n) + ".log") for n in follow] + [(n, ["--companion", n], archive_tag(n) + ".companion.log") for n in sorted(analyse)] failed = set() with cf.ThreadPoolExecutor(workers) as ex: for f in cf.as_completed([ex.submit(run, *task) for task in tasks]): name, code = f.result() failed |= {name} if code else set() # each followed star's rotation period from its S index and colour, as the Sun's activity lies at its rotation and half of it dace = planets_dace_series(set(follow)) s_med = {n: float(np.median([x[3] for xs in dace.get(n, {}).values() for x in xs if 0 < x[3] < 5])) if any(0 < x[3] < 5 for xs in dace.get(n, {}).values() for x in xs) else float("nan") for n in follow} prot = {n: [q for q in (archive_num(stars.get(n, {}).get("Prot")) or planets_rotation(planets_num(stars.get(n, {}).get("Bmag")) - planets_num(stars.get(n, {}).get("Vmag")), s_med[n]),) if q] + planets_rotation_read(planets_num(stars.get(n, {}).get("RAJ2000")), planets_num(stars.get(n, {}).get("DEJ2000"))) for n in follow} for name in follow: vp = os.path.join(planets_RESULTS, "vet", archive_tag(name) + ".json") res = json.load(open(vp)) if os.path.exists(vp) else vet[name] for P in follow[name]: cands[(name, P)].update(planets_followup_row(cands[(name, P)], res, catalogued[name], unexplained[name], prot[name])) if name in failed: cands[(name, P)].update(status="rejected", reason="follow-up failed") recs = {} for name in sorted(analyse): path = os.path.join(planets_RESULTS, "companion", archive_tag(name) + ".json") if os.path.exists(path) and name not in failed: recs[name] = json.load(open(path)) else: s = stars[name] rows.append(dict(name=name, sptype=s.get("SpType", ""), vmag=s.get("Vmag", ""), kind="companion", label="orbit", status="rejected", reason="analysis failed")) period = lambda rec: (rec.get("orbit") or {}).get("P", [None])[0] or (rec.get("weigh") or {}).get("P_d", [None])[0] or rec["P"] 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())] # a root with its own bank weighs TESS's candidates among its stars with it at each decision, as ExoFOP's table now stands if planets_BANK_INFO: planets_tois(fit_only=True, source="bank") tois = planets_toi_rows() # 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 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 sig += planets_epochs_rows(stars, sig) planets_encyclopaedia_decide(sig, stars) planets_false_decide(sig, stars) planets_survey_decide(sig, stars) planets_second_decide(sig) planets_epochs_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", "astrometry": "astrometry"} for x in (planets_read(lpath) if os.path.exists(lpath) else []): for r in sig: if r["status"] == "new" and r["name"] == x["bank_name"] and r["kind"] == kinds[x["found_by"]] and abs(float(r["P"]) / float(x["P_d"]) - 1.0) < 0.2: r["prediction"] = x["prediction"] if x["prediction"] == "failed": r.update(status="rejected", reason="prediction failed") discoverer = planets_discoverers() for r in sig: r["contribution"] = planets_CONTRIBUTION[r["kind"]] if r["status"] == "new" else "likely planet" if r["status"] == "likely" else "" if r["status"] != "known" else \ "independent detection" if r["kind"] in ("found", "eccentric", "companion", "transit", "astrometry") and r["reason"] in ("archive planet", "catalogued") and r.get("label") != "variation" \ else "independent mass measurement" if r["kind"] == "toi" else r.get("contribution", "") if r["kind"] == "validated" else "" r["discovered_by"] = discoverer(r) if r["kind"] in ("validated", "toi") or r["status"] in ("new", "candidate", "likely") else "" planets_write(os.path.join(planets_RESULTS, "signals.csv"), sig, planets_SIGNAL_KEYS + planets_S_KEYS + planets_DECISION_KEYS) listed = planets_list(sig, stars) found, likely = [r for r in listed if r["status"] == "new"], [r for r in listed if r["status"] == "likely"] planets_write(os.path.join(planets_RESULTS, "planets.csv"), found, list(listed[0].keys()) if listed else ["planet"]) planets_write(os.path.join(planets_RESULTS, "likely_planets.csv"), likely, list(listed[0].keys()) if listed else ["planet"]) planets_singles_table() try: planets_epochs_predict(found, stars) except Exception as exc: print("DR4's predictions left as they stand: %s: %s" % (type(exc).__name__, str(exc)[:160]), flush=True) for r in found: mass = "%s Mjup true" % r["mass_mjup"] if r["mass_mjup"] not in ("", None) else "%s Mearth minimum" % r["msini_mearth"] print("%-26s %-11s %12.3f d %s" % (r["planet"], r["kind"], float(r["P_d"]), mass), flush=True) def planets_draws_save(path, rec, **arrays): """Posterior draws written beside the JSON record at PATH, in the file of the same name ending .draws.npz, each of ARRAYS under its name; REC's draws field is set to that file's name.""" npz = path[:-len(".json")] + ".draws.npz" np.savez_compressed(npz, **{k: np.asarray(v, float) for k, v in arrays.items()}) rec["draws"] = os.path.basename(npz) def planets_draws_load(path, rec): """The posterior draws of the JSON record REC at PATH: the arrays of the .npz file its draws field names, by name.""" with np.load(os.path.join(os.path.dirname(path), rec["draws"])) as d: return {k: d[k] for k in d.files} def planets_orbits(name, periods, steps=30000, mstar=None, ebound=0.9, others=True, seed=11, circular=False, label=None, extra=None): """A star's Keplerians sampled, to RESULTS/orbits/.json. The bank's velocities averaged per night, an offset for each side of the fibre upgrade and 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 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 (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 .