Radial-velocity orbit of an exoplanet¶
A planet on an eccentric orbit pulls its star back and forth along the line of sight, and the star’s radial velocity traces a Keplerian curve. This page fits that curve, with seven parameters, to simulated velocities. It follows the steps of Quickstart: a log-density written as for emcee, a start from an optimizer’s fit, a run, and the reading of its summary and warnings.
The data¶
A star with one planet has the radial velocity
where \(K\) is the semi-amplitude, \(e\) the eccentricity, \(\omega\) the argument of periastron and \(\gamma\) the systemic velocity. The true anomaly \(\nu\) follows from the mean anomaly \(M = 2\pi t/P + M_0\), with period \(P\) and phase \(M_0\), through Kepler’s equation \(M = E - e\sin E\) for the eccentric anomaly \(E\). The function below solves Kepler’s equation by Newton’s method for a batch of parameter vectors at once:
import numpy as np
from scipy import differentiate, optimize
import telescopic
names = ["P", "K", "e", "omega", "M0", "gamma", "s"]
def velocity(theta, t):
# theta has shape (n, 7) or (7,); the result, shape (n, len(t)) or (len(t),).
P, K, e, omega, M0, gamma = (theta[..., i, None] for i in range(6))
M = 2 * np.pi * t / P + M0
E = M + 0.85 * e * np.sign(np.sin(M)) # Danby's start, from which Newton converges
step = np.inf
while np.max(np.abs(step), initial=0) > 1e-12:
step = (E - e * np.sin(E) - M) / (1 - e * np.cos(E))
E -= step
nu = 2 * np.arctan2(np.sqrt(1 + e) * np.sin(E / 2), np.sqrt(1 - e) * np.cos(E / 2))
return gamma + K * (np.cos(nu + omega) + e * np.cos(omega))
Forty velocities over 300 days, each with its own measurement error between 1.5 and 3.5 m/s, and an extra scatter \(s\) of 2 m/s that the errors do not include, as stellar activity adds:
rng = np.random.default_rng(3)
n = 40
t = np.sort(rng.uniform(0, 300, n))
sigma = rng.uniform(1.5, 3.5, n)
truth = np.array([37.5, 11.0, 0.3, 2.2, 3.4, -4.0, 2.0])
v = velocity(truth, t) + np.hypot(sigma, truth[6]) * rng.normal(size=n)
The log-density¶
Each velocity is Gaussian about the curve with variance \(\sigma_i^2 + s^2\). The prior is
uniform on a box that enforces the constraints: \(1 < P < 1000\) days, \(K > 0\),
\(0 \le e < 1\), \(\omega\) and \(M_0\) in \([0, 2\pi)\), and \(s > 0\), with \(\gamma\)
unconstrained. Outside the box the log-density is -inf, which every Metropolis test
rejects (Special values). The function takes a
batch of points of shape (n, 7), so the run passes vectorize=True
(The log-density):
lower = np.array([1.0, 0.0, 0.0, 0.0, 0.0, -np.inf, 0.0])
upper = np.array([1000.0, np.inf, 1.0, 2 * np.pi, 2 * np.pi, np.inf, np.inf])
def log_prob(theta, t, v, sigma):
inside = np.all((theta >= lower) & (theta < upper), axis=1) & (theta[:, 0] > 1)
out = np.full(len(theta), -np.inf)
point = theta[inside]
variance = sigma**2 + point[:, 6, None] ** 2
residual = v - velocity(point, t)
out[inside] = -0.5 * np.sum(residual**2 / variance + np.log(variance), axis=1)
return out
Finding the period¶
An optimizer needs a starting period. A periodogram fits a sinusoid and a constant by weighted least squares at each period of a grid, and the best period has the smallest \(\chi^2\):
import matplotlib.pyplot as plt
periods = np.geomspace(2, 300, 20000)
chi2 = np.empty(len(periods))
for i, period in enumerate(periods):
phase = 2 * np.pi * t / period
design = np.column_stack([np.cos(phase), np.sin(phase), np.ones(n)]) / sigma[:, None]
coefficients = np.linalg.lstsq(design, v / sigma)[0]
chi2[i] = np.sum((v / sigma - design @ coefficients) ** 2)
best_period = periods[np.argmin(chi2)]
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(periods, chi2, linewidth=1)
ax.set(xscale="log", xlabel="period $P$ (days)", ylabel=r"$\chi^2$");
The periodogram: the \(\chi^2\) of a sinusoid fit at each period. The deep minimum is near the true period of 37.5 days; the shallow ones are other local minima.¶
The deepest minimum is at 37.2 days, and every other local minimum has a \(\chi^2\) larger by at least 213. With sparser data, the period’s posterior can have several modes of comparable height, at aliases of the true period. The pairs of chains find only the modes that their initial distribution covers, so the initial distribution must cover every mode of the period that matters (Choose an initial distribution).
A start from an optimizer’s fit¶
Nelder-Mead from the best period, and from a few phases and arguments of periastron,
finds the maximum of the log-density, and the Hessian there gives its error bars.
scipy.differentiate.hessian() evaluates the log-density at a batch of points of
shape (7, ...), which batch reshapes for log_prob:
def negative(theta):
return -log_prob(theta[None], t, v, sigma)[0]
starts = [
[best_period, np.ptp(v) / 2, 0.1, omega, M0, np.mean(v), 1.0]
for omega in (1.0, 3.0, 5.0)
for M0 in (1.0, 3.0, 5.0)
]
fits = [
optimize.minimize(negative, start, method="Nelder-Mead", options={"maxfev": 20000})
for start in starts
]
fit = min(fits, key=lambda result: result.fun)
def batch(x):
points = np.moveaxis(x, 0, -1)
return log_prob(points.reshape(-1, 7), t, v, sigma).reshape(points.shape[:-1])
hessian = differentiate.hessian(batch, fit.x, initial_step=1e-2).ddf
cov = np.linalg.inv(-(hessian + hessian.T) / 2)
dict(zip(names, np.sqrt(np.diag(cov)).round(3).tolist()))
{'P': 0.142,
'K': 0.873,
'e': 0.053,
'omega': 0.2,
'M0': 0.182,
'gamma': 0.463,
's': 0.619}
The initial distribution is a Gaussian centered on the fit and wider than its error bars, cut to the box: a callable that redraws until the point is inside, so that every chain starts where the density is positive (Choosing one). The guide asks for a start a few to ten times wider than the target. The meeting times of 100 pilot pairs with lag 1, capped at 2,000 iterations, compare a start 3 times and 10 times wider than the error bars:
def truncated(width):
def init(rng):
while True:
point = rng.multivariate_normal(fit.x, width**2 * cov)
if np.isfinite(log_prob(point[None], t, v, sigma)[0]):
return point
return init
pilot = {}
for width in (3, 10):
sampler = telescopic.CoupledSampler(
log_prob, truncated(width), args=(t, v, sigma), vectorize=True, rng=4
)
pilot[width] = sampler.meeting_times(100, max_iter=2000)
print(
f"{width:2} times wider: median {np.median(pilot[width]):5.0f}, "
f"unmet at 2,000: {np.sum(np.isinf(pilot[width]))}"
)
3 times wider: median 51, unmet at 2,000: 0
10 times wider: median 230, unmet at 2,000: 6
After 2,000 iterations, from the start 10 times wider, 6 of the 100 pairs had not met, too many for k to be chosen; from the start 3 times wider, 0 of the 100 pairs had not met, and k can be chosen from them. The automatic choice of the burn-in k allows only a few
unmet pairs (The automatic pipeline), and
from a start wider than needed, the pairs that start far out take longest to meet. The
run starts 3 times wider.
The run¶
A run of 500 replicates, each of which stores every tenth state
(thin=10), which keeps the memory of the atoms small; thinning does not
shorten a run (Memory and thinning):
result = telescopic.sample(
log_prob,
truncated(3),
500,
args=(t, v, sigma),
vectorize=True,
thin=10,
names=names,
rng=5,
)
result.summary()
| mean | standard_error | std | q16 | q50 | q84 | |
|---|---|---|---|---|---|---|
| P | 37.3792 | 0.000923515 | 0.175253 | 37.2118 | 37.3902 | 37.547 |
| K | 12.2507 | 0.00541367 | 0.948465 | 11.3293 | 12.2325 | 13.1736 |
| e | 0.298743 | 0.000347813 | 0.0639955 | 0.237265 | 0.301261 | 0.360451 |
| omega | 2.10643 | 0.00139304 | 0.24845 | 1.87069 | 2.11011 | 2.34387 |
| M0 | 3.53255 | 0.00127445 | 0.223276 | 3.32214 | 3.5371 | 3.74006 |
| gamma | -3.88629 | 0.00280423 | 0.524859 | -4.39904 | -3.88608 | -3.37539 |
| s | 1.91607 | 0.00460205 | 0.718767 | 1.22037 | 1.92 | 2.60893 |
- R = 500, k = 225, m = 2250, lag = 225, thin = 10
- kernel: RandomWalk(cov=<7x7>, scale=None, coupling='reflection')
- meeting times: median 270, 90% 332, 99% 432, max 477; censored 0
- tail index of the meeting times: 3.55
- cost per replicate: 2306 kernel applications, 0.024 s; relative cost 1.14
- pairs meeting after k + lag: 0.8% (at most 1.8% at 95%)
- largest share of one replicate in a variance: 14%, for the variance of omega
The next cell sets the table’s means beside the values that drew the data. A posterior mean need not equal the true value: it differs from it by about the error bars that the data leave, here those of the optimizer’s fit:
mean = result.mean()
fit_error = np.sqrt(np.diag(cov))
print(" true estimate std. error fit's error bar")
for name, true, value, error, spread in zip(
names, truth, mean.value, mean.standard_error, fit_error
):
print(f"{name:5} {true:6.2f} {value:8.3f} {error:10.4f} {spread:15.3f}")
true estimate std. error fit's error bar
P 37.50 37.379 0.0009 0.142
K 11.00 12.251 0.0054 0.873
e 0.30 0.299 0.0003 0.053
omega 2.20 2.106 0.0014 0.200
M0 3.40 3.533 0.0013 0.182
gamma -4.00 -3.886 0.0028 0.463
s 2.00 1.916 0.0046 0.619
The orbit and two marginals¶
The posterior mean of the velocity at each time of a grid is an expectation like any
other, estimated from the same run with estimate(), with its
error bars. Below, it is drawn against the data and against the curve that drew them:
grid = np.linspace(0, 300, 300)
curve = result.estimate(lambda theta: velocity(theta, grid))
fig, ax = plt.subplots(figsize=(9, 3.5))
ax.errorbar(t, v, sigma, fmt="o", color="C1", markersize=4, label="data")
ax.fill_between(
grid,
curve.value - 2 * curve.standard_error,
curve.value + 2 * curve.standard_error,
color="C0",
alpha=0.4,
)
ax.plot(grid, curve.value, color="C0", linewidth=1.2, label="posterior mean")
ax.plot(grid, velocity(truth, grid), color="gray", linestyle="--", linewidth=1, label="true")
ax.set(xlabel="time $t$ (days)", ylabel="radial velocity (m/s)")
ax.legend(loc="upper right", ncols=3);
The simulated velocities, with error bars of their measurement errors, the estimated posterior mean of the velocity curve with a band of plus or minus two standard errors, and the curve that drew the data, dashed.¶
plot_marginals() draws the histograms of the
signed measure of the period
and the eccentricity, with boxes of plus or minus two standard errors on each bin
(Plot a result), here with the true values dashed:
axes = result.plot_marginals(dims=[0, 2], bins=30)
for ax, true in zip(axes, truth[[0, 2]]):
ax.axvline(true, color="gray", linestyle="--")
The signed histograms of the period and the eccentricity, with boxes of plus or minus two standard errors on each bin, and the true values dashed.¶
What the warnings say¶
The run emits no warning. The largest share of one replicate in the variance of an estimate is 0.14, for the variance of omega, held by replicate 160, whose pair met at $\tau$ = 265, with 278 of the 500 pairs meeting later or not at all, by $k + L$ = 450, so its estimate carries no bias correction.
A share near 1 means that the error bar of that estimate rests on one replicate and is not reliable. A pair that meets far later than the others, as from a start far out or after an excursion to a region that the other pairs did not visit, gives such a share: an orbit’s posterior can have a tail toward high eccentricity, where a narrow spike of the curve fits a few points. Warnings and errors gives each warning’s threshold, meaning and remedy. For error bars that rest on many replicates, plan a second run with more of them, its number fixed before it runs (How many replicates).