1. Motivation: from the best fit to the distribution of the parameters

The periodogram gave us a candidate period; now we want the orbital parameters with their uncertainties and correlations: what is and with what error? Is really different from zero? Is there a second planet? Least squares answers the first question only if the model is nearly linear and the errors Gaussian; Bayesian inference answers all of them and does so with a single object, the posterior distribution of the parameters, which it explores with Markov chains. In exoplanets it is the standard methodology (Gregory 2005; Foreman-Mackey et al. 2013), and it applies equally to transit light curves, to cosmology or to gravitational waves.
2. Bayes’ theorem and Gaussian likelihood

For parameters and data ,
with the likelihood , the prior and the evidence (a constant for parameter estimation; essential for comparing models). If each datum has an independent Gaussian error of known standard deviation and the model predicts ,
With a uniform prior, the maximum a posteriori coincides with the minimum of : least squares is the particular Bayesian case of flat priors and Gaussian errors (problem 1). If we suspect that the errors are underestimated (stellar noise), a jitter term is added: , with one more parameter (and then is no longer constant).
Priors
The prior encodes what we know before seeing the data and must be declared. For a location parameter (such as or ) the uniform prior is natural; for a positive scale parameter spanning orders of magnitude (, ) the Jeffreys prior (uniform in ), which favors no decade, is more honest (problem 6). For and one usually samples in , which gives a uniform prior in and avoids the singularity of at . If the prior is informative (e.g. from an isochrone) it is included as a Gaussian.
3. Metropolis–Hastings

We want samples distributed according to without knowing the normalization constant. The Metropolis–Hastings algorithm (Metropolis et al. 1953; Hastings 1970):
- From the current state , propose with a proposal density .
- Compute .
- With probability accept (); otherwise, repeat the state ().
With a symmetric Gaussian proposal (random walk), and :
one always moves uphill, and moves downhill with probability equal to the ratio. In logarithms: accept if
with . This is what metropolisHastings in src/lib/math/mcmc.ts implements.
Why it works: detailed balance
Theorem. The Metropolis–Hastings chain has as its stationary distribution.
Proof. The transition kernel for is . Suppose (the other case is symmetric). Then and , so that
This equality is detailed balance. Integrating over : , that is, if the current state is distributed according to , so is the next one: is stationary. (Rejections, which leave , satisfy the balance trivially.)
For the chain to converge to from any point one also needs irreducibility and aperiodicity, guaranteed by a Gaussian proposal with support on the whole space. What the theorem does not say is how long it takes: that is what the diagnostics are about.
The scale of the proposal
With very small steps almost everything is accepted but the chain advances as an extremely slow random walk; with very large steps almost everything is rejected. For Gaussian targets of dimension the optimal acceptance rate is (0.44 in ), with scale (Roberts, Gelman & Gilks 1997). In our example (§5), multiplying the scale by 0.2, 1 and 5 gives acceptances of 0.90, 0.56 and 0.045, and autocorrelation times for of 203, 23 and 36 steps: the middle wins.
4. Convergence diagnostics

Gelman–Rubin
One runs chains from dispersed starting points, of length after discarding the burn-in. For each scalar parameter, let be the mean of the within-chain variances and the between-chain variance. The estimator of the posterior variance
overestimates if the chains have not mixed (each explores a different region: large ), whereas
underestimates it; both converge and . Practical criterion: (1.01 in demanding work). An
does not prove convergence (all the chains may be trapped in the same mode), but does prove the
opposite. Implementation: gelmanRubin.
Autocorrelation and effective sample size
Consecutive samples are correlated. For a chain with normalized autocorrelation function , the integrated autocorrelation time is
and the variance of the sample mean is : a chain of steps is worth independent
samples. The sum is truncated with Sokal’s automatic window (stop at the first , ; this is what
emcee does) because the at large lag are pure noise. For an AR(1) process with coefficient ,
(test with : ). Rule of thumb: run at least steps per chain, and
discard a few as burn-in. Implementation: tiempoAutocorrelacion, tamanoEfectivo.
emcee: the ensemble sampler
The random walk requires choosing a scale per parameter, and fails with strong correlations. Goodman & Weare (2010)
proposed evolving an ensemble of walkers where each one moves along the line joining it to another
randomly chosen walker (“stretch move”, with of density on ,
), accepting with probability . The algorithm is affine invariant: its performance is
the same for a highly elongated Gaussian and for a spherical one, with no manual tuning. emcee (Foreman-Mackey et al. 2013) is
the reference implementation in Python, with built-in estimation of ; in this lesson we use
Metropolis–Hastings for transparency, but in professional practice one uses emcee or nested sampling (dynesty,
MultiNest) when the evidence is also wanted.
5. Example: the radial-velocity curve of 51 Peg

Data: the same 40 synthetic measurements of the previous lesson ( d, m s⁻¹, m s⁻¹, m s⁻¹, 61 nights). Circular model with four parameters :
with uniform priors d, , , d. Four chains of
40 000 steps from dispersed points, proposal scales , burn-in 5000. Results
(mcmc.ts, fixed seeds):
| Parameter | True | Mean ± σ | [p16, p84] | (steps) | |
|---|---|---|---|---|---|
| (d) | 4.2293 | [4.2244, 4.2405] | 1.003 | 258 | |
| (m s⁻¹) | 59 | [53.2, 59.2] | 1.000 | 19 | |
| (m s⁻¹) | −33 250 | [−33 252.3, −33 248.1] | 1.000 | 10 | |
| (d) | 0 | [−0.148, −0.001] | 1.003 | 268 |
Acceptance 0.56 in all four chains. Comments:
- Comparison with the linear theory. For a well-sampled sinusoid, m s⁻¹ and : the posterior reproduces both (3.0 and 2.1). falls 0.9 σ from the true value: a normal noise realization.
- – degeneracy. Changing by shifts the phase at the center of the campaign by , which is compensated by : the posterior is an elongated “banana” and the random-walk chain traverses it slowly ( versus 10–20 for the others). With 35 000 useful steps, per chain for : enough for the mean (Monte Carlo error d) but scarce for the tails. This is the typical case where emcee (affine invariant) or reparametrizing ( referred to the center of the campaign) gains a lot.
- Precision of the period. d is 25 times smaller than the resolution of the periodogram ( d): the periodogram locates, the fit refines.
Model comparison
Is there a planet? We compare the constant model ( parameter, ) with the circular one (, at the maximum). The Bayesian information criterion gives : overwhelming evidence (usual threshold ). The BIC is an approximation to valid for large and Gaussian posteriors; the rigorous comparison uses the evidence, which automatically penalizes complexity (Occam factor) and which nested sampling or thermodynamic integration compute.
6. Error analysis

- Monte Carlo error. The uncertainty of any average over the chain is ; for extreme percentiles (e.g. the 99% limit on ) one needs –.
- Burn-in. If included, it biases the means toward the starting point; it is detected in the trace and with over segments.
- Multimodality. If the periodogram has comparable aliases (previous lesson), the posterior has several modes and the random walk does not jump between them: chains must be launched from each alias or nested sampling used.
- Wrong model. No sampler corrects an incomplete model (second planet, stellar activity): it shows up in the residuals and in a fitted jitter much larger than .
Problems
1. (Proof) Least squares as a Bayesian case. Show that with independent Gaussian errors and a uniform prior the maximum a posteriori minimizes , and that if the model is linear, , the posterior is Gaussian with mean and covariance , with .
Proof
with a uniform prior, so maximizing is minimizing . For ,
is quadratic in : expanding and completing the square,
with and
. Then : a Gaussian of
mean and covariance . The test in mcmc.ts checks this result for a straight line: the mean and the
standard deviation of the chain coincide with the formula.
2. (Proof) Hastings with an asymmetric proposal. Show that if a non-symmetric proposal is used (e.g. lognormal for a positive parameter) but one accepts with without the ratio , the stationary distribution is not . Compute what it is for with drift and a uniform target on a large box.
Proof
With detailed balance requires ; if , the left-hand side is and the right-hand side , equal only if is symmetric. In the example, inside the box is constant and : the chain is a random walk with drift per step, which piles up against the wall of the box: the stationary distribution is concentrated at the edge, not the uniform one. The Hastings correction, , penalizes the steps in the direction of the drift and restores uniformity.
3. Gelman–Rubin by hand. Three chains of steps for have means 55.1, 57.8 and 56.4 and variances 8.9, 9.4 and 9.1. Compute , , and . Have they converged? What if the means were 50, 57 and 63?
Show solution
; mean of means 56.43, sample variance of the means , ; ; : borderline, better to run longer. With means 50, 57, 63: variance , , , : they have not converged (or the posterior is multimodal).
4. (Computational) Scale of the proposal. With the example of §5 (or with a correlated 2D Gaussian, ), run Metropolis with scales , , and . Tabulate acceptance, and and verify that the maximum of falls near acceptance 0.2–0.4.
Outline in Python
import numpy as np
rng = np.random.default_rng(0)
C = np.array([[1, 0.95], [0.95, 1]]); Ci = np.linalg.inv(C)
logp = lambda x: -0.5 * x @ Ci @ x
def tau_int(x, c=5):
x = x - x.mean(); n = len(x); acf = np.correlate(x, x, 'full')[n-1:] / (x @ x)
t = 1.0
for M in range(1, n // 2):
t += 2 * acf[M]
if M >= c * t: return t
return t
for s in (0.1, 1.0, 2.4 / np.sqrt(2), 10.0):
x = np.zeros(2); lp = logp(x); X = []; acc = 0
for _ in range(50000):
xp = x + s * rng.standard_normal(2); lpp = logp(xp)
if np.log(rng.random()) < lpp - lp: x, lp, acc = xp, lpp, acc + 1
X.append(x.copy())
X = np.array(X)[5000:]; t = tau_int(X[:, 0])
print(s, acc / 50000, t, len(X) / t)With the optimal isotropic scale is still bad ( of hundreds) because the posterior is a needle: direct motivation for the affine-invariant samplers.
5. (Computational) Full fit. Reproduce §5 with your own Metropolis (or with emcee): four chains, traces, , , marginal histograms and the – diagram. Reparametrize with d (center of the campaign) and compare . Then add the jitter parameter and check that its posterior is compatible with zero.
Show solution
With referred to the center of the campaign the – correlation almost disappears (the phase at the center no longer depends on ) and
drops from to a few tens of steps. With jitter, includes ; the posterior of piles up at 0
(84% limit of a few m s⁻¹), as it should with data that already have the correct . With emcee: 32 walkers, 5000
steps, get_autocorr_time().
6. (Proof) Jeffreys prior. Show that is the only prior on invariant under changes of units , and that it is equivalent to a uniform prior in . For m s⁻¹, what fraction of the prior mass falls below 1 m s⁻¹ with the uniform prior and with the Jeffreys prior?
Proof
Invariance: for all ⇒ ; with , . And . Uniform: below 1 m s⁻¹ (the prior “knows” that is large). Jeffreys: .
7. Occam. For the data of §5, a model with free eccentricity () reaches . Compute against the circular one and decide. What does Wilks’ theorem say about with 2 extra degrees of freedom?
Show solution
: the circular model is preferable. Wilks: under the null hypothesis () , and : the improvement is what is expected by chance. (Strictly, lies on the boundary of the parameter space, which modifies the distribution; the BIC is more conservative.)
✦ Self-assessment
Further reading
- Gregory, P. C. (2005). Bayesian Logical Data Analysis for the Physical Sciences, ch. 3 (foundations), ch. 11 (nonlinear fitting) and ch. 12 (MCMC, with the radial-velocity example).
- Hogg & Foreman-Mackey (2018). Data analysis recipes: Using MCMC, ApJS 236, 11: a practical, brief and honest guide to what works.
- Foreman-Mackey et al. (2013), PASP 125, 306 (emcee) and Goodman & Weare (2010): the affine-invariant sampler.
- Gelman & Rubin (1992), Stat. Sci. 7, 457; Sokal (1997): convergence diagnostics and autocorrelation.
- Perryman (2018). The Exoplanet Handbook, §2.3 and §6.4: orbit inference from radial velocities and transits.
🍎 Teacher guide
- Time
- 2 classes of 90 min
- Learning outcome
- By the end, the student formulates an orbital fit as Bayesian inference, implements Metropolis–Hastings, diagnoses convergence with R̂ and τ, and interprets the posterior and the model comparison.
- Evidence of learning
- Submission of problem 5 (full fit with traces, R̂, τ, marginals and reparametrization) and of problem 2 (Hastings proof).
Materials
- Python 3 with NumPy; optionally emcee and corner
- src/lib/math/mcmc.ts and velocidadRadial.ts
- Hogg & Foreman-Mackey 2018 (prior reading, 20 pages)
Suggested sequence
Class 1. Bayes, Gaussian likelihood and priors (§2); Metropolis–Hastings with the proof of detailed balance (§3); live experiment with the scale of the proposal.
Class 2. Diagnostics (§4) on the chains of the example; fit of 51 Peg (§5) with discussion of the – degeneracy and of ΔBIC. Lab: problems 4 and 5.
Common mistakes
- Confusing likelihood with posterior and forgetting to declare the priors.
- Taking R̂ ≈ 1 as proof of convergence: only R̂ ≫ 1 is conclusive.
- Using the standard deviation of the chain without accounting for τ when estimating Monte Carlo errors.
- Choosing the proposal scale without looking at the acceptance or τ; or using an asymmetric proposal without the Hastings correction.
- Comparing models by χ² without penalizing parameters.