Astronomy and Space Exploration ES

Higher Education / Exoplanets and observational astrophysics

Bayesian inference and MCMC

Bayes' theorem, Gaussian likelihood and priors; the Metropolis–Hastings algorithm with a proof of detailed balance; convergence diagnostics (Gelman–Rubin, autocorrelation, effective sample size); emcee; a complete example fitting a radial-velocity curve.

⏱ 180 min conditional probability and Bayes' theoremMarkov chainsdetailed balanceestimators and varianceautocorrelationχ² functioninformation criteria revision

By the end you will be able to:
  • Formulate the inference of orbital parameters as a Bayesian problem with a Gaussian likelihood and explicit priors.
  • Prove that the Metropolis–Hastings chain satisfies detailed balance and has the posterior as its stationary distribution.
  • Diagnose convergence with the Gelman–Rubin statistic R̂, the integrated autocorrelation time and the effective sample size.
  • Fit a radial-velocity curve with MCMC, summarize the posterior and interpret correlations and degeneracies.
  • Compare models with ΔBIC and know the role of the evidence and of emcee in practice.

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

Illustration: 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 KK and with what error? Is ee 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

Illustration: Bayes’ theorem and Gaussian likelihood

For parameters θ\boldsymbol\theta and data DD,

p(θ ∣ D)=p(D ∣ θ) p(θ)p(D),p(D)=∫p(D ∣ θ) p(θ) dθ,p(\boldsymbol\theta\,|\,D) = \frac{p(D\,|\,\boldsymbol\theta)\,p(\boldsymbol\theta)}{p(D)}, \qquad p(D) = \int p(D\,|\,\boldsymbol\theta)\,p(\boldsymbol\theta)\,d\boldsymbol\theta ,

with the likelihood L(θ)=p(D∣θ)\mathcal L(\boldsymbol\theta) = p(D|\boldsymbol\theta), the prior p(θ)p(\boldsymbol\theta) and the evidence p(D)p(D) (a constant for parameter estimation; essential for comparing models). If each datum has an independent Gaussian error of known standard deviation σi\sigma_i and the model predicts mi(θ)m_i(\boldsymbol\theta),

ln⁡L=−12∑i=1N[yi−mi(θ)σi]2−∑iln⁡σi−N2ln⁡2π=−χ2(θ)2+const.\ln\mathcal L = -\frac12\sum_{i=1}^N\left[\frac{y_i - m_i(\boldsymbol\theta)}{\sigma_i}\right]^2 - \sum_i\ln\sigma_i - \frac N2\ln 2\pi = -\frac{\chi^2(\boldsymbol\theta)}{2} + \mathrm{const}.

With a uniform prior, the maximum a posteriori coincides with the minimum of χ2\chi^2: 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 ss is added: σi2→σi2+s2\sigma_i^2 \to \sigma_i^2 + s^2, with ss one more parameter (and then ∑ln⁡σi\sum\ln\sigma_i 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 γ\gamma or tpt_p) the uniform prior is natural; for a positive scale parameter spanning orders of magnitude (PP, KK) the Jeffreys prior p(θ)∝1/θp(\theta) \propto 1/\theta (uniform in ln⁡θ\ln\theta), which favors no decade, is more honest (problem 6). For ee and ω\omega one usually samples in (ecos⁡ω,esin⁡ω)(\sqrt e\cos\omega, \sqrt e\sin\omega), which gives a uniform prior in ee and avoids the singularity of ω\omega at e=0e = 0. If the prior is informative (e.g. M⋆M_\star from an isochrone) it is included as a Gaussian.

3. Metropolis–Hastings

Illustration: Metropolis–Hastings

We want samples θ(1),θ(2),…\boldsymbol\theta^{(1)}, \boldsymbol\theta^{(2)}, \ldots distributed according to π(θ)∝L(θ)p(θ)\pi(\boldsymbol\theta) \propto \mathcal L(\boldsymbol\theta)p(\boldsymbol\theta) without knowing the normalization constant. The Metropolis–Hastings algorithm (Metropolis et al. 1953; Hastings 1970):

  1. From the current state x\mathbf x, propose x′\mathbf x' with a proposal density q(x′∣x)q(\mathbf x'|\mathbf x).
  2. Compute α=min⁡ ⁣{1, π(x′) q(x∣x′)π(x) q(x′∣x)}\alpha = \min\!\left\{1,\ \dfrac{\pi(\mathbf x')\,q(\mathbf x|\mathbf x')}{\pi(\mathbf x)\,q(\mathbf x'|\mathbf x)}\right\}.
  3. With probability α\alpha accept (x(k+1)=x′\mathbf x^{(k+1)} = \mathbf x'); otherwise, repeat the state (x(k+1)=x\mathbf x^{(k+1)} = \mathbf x).

With a symmetric Gaussian proposal (random walk), q(x′∣x)=q(x∣x′)q(\mathbf x'|\mathbf x) = q(\mathbf x|\mathbf x') and α=min⁡{1,π(x′)/π(x)}\alpha = \min\{1, \pi(\mathbf x')/\pi(\mathbf x)\}: one always moves uphill, and moves downhill with probability equal to the ratio. In logarithms: accept if ln⁡u<ln⁡π(x′)−ln⁡π(x)\ln u < \ln\pi(\mathbf x') - \ln\pi(\mathbf x) with u∼U(0,1)u \sim U(0,1). This is what metropolisHastings in src/lib/math/mcmc.ts implements.

Why it works: detailed balance

Theorem. The Metropolis–Hastings chain has π\pi as its stationary distribution.

Proof. The transition kernel for x′≠x\mathbf x' \ne \mathbf x is T(x′∣x)=q(x′∣x) α(x′∣x)T(\mathbf x'|\mathbf x) = q(\mathbf x'|\mathbf x)\,\alpha(\mathbf x'|\mathbf x). Suppose π(x′)q(x∣x′)≤π(x)q(x′∣x)\pi(\mathbf x')q(\mathbf x|\mathbf x') \le \pi(\mathbf x)q(\mathbf x'|\mathbf x) (the other case is symmetric). Then α(x′∣x)=π(x′)q(x∣x′)/[π(x)q(x′∣x)]\alpha(\mathbf x'|\mathbf x) = \pi(\mathbf x')q(\mathbf x|\mathbf x')/[\pi(\mathbf x)q(\mathbf x'|\mathbf x)] and α(x∣x′)=1\alpha(\mathbf x|\mathbf x') = 1, so that

π(x) T(x′∣x)=π(x) q(x′∣x) π(x′)q(x∣x′)π(x)q(x′∣x)=π(x′) q(x∣x′)=π(x′) T(x∣x′).\pi(\mathbf x)\,T(\mathbf x'|\mathbf x) = \pi(\mathbf x)\,q(\mathbf x'|\mathbf x)\,\frac{\pi(\mathbf x')q(\mathbf x|\mathbf x')}{\pi(\mathbf x)q(\mathbf x'|\mathbf x)} = \pi(\mathbf x')\,q(\mathbf x|\mathbf x') = \pi(\mathbf x')\,T(\mathbf x|\mathbf x') .

This equality is detailed balance. Integrating over x\mathbf x: ∫π(x)T(x′∣x) dx=π(x′)∫T(x∣x′) dx=π(x′)\int\pi(\mathbf x)T(\mathbf x'|\mathbf x)\,d\mathbf x = \pi(\mathbf x')\int T(\mathbf x|\mathbf x')\,d\mathbf x = \pi(\mathbf x'), that is, if the current state is distributed according to π\pi, so is the next one: π\pi is stationary. (Rejections, which leave x′=x\mathbf x' = \mathbf x, satisfy the balance trivially.) ■\blacksquare

For the chain to converge to π\pi 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 dd the optimal acceptance rate is ≈0.23\approx 0.23 (0.44 in d=1d = 1), with scale ≈2.4 σpost/d\approx 2.4\,\sigma_{\rm post}/\sqrt d (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 KK of 203, 23 and 36 steps: the middle wins.

4. Convergence diagnostics

Illustration: Convergence diagnostics

Gelman–Rubin

One runs mm chains from dispersed starting points, of length nn after discarding the burn-in. For each scalar parameter, let WW be the mean of the within-chain variances and B=n Var(chain means)B = n\,\mathrm{Var}(\text{chain means}) the between-chain variance. The estimator of the posterior variance

V^=n−1nW+1nB,R^=V^/W\hat V = \frac{n-1}{n}W + \frac1n B, \qquad \hat R = \sqrt{\hat V/W}

overestimates Var(θ)\mathrm{Var}(\theta) if the chains have not mixed (each explores a different region: large BB), whereas WW underestimates it; both converge and R^→1\hat R \to 1. Practical criterion: R^<1.1\hat R < 1.1 (1.01 in demanding work). An R^≈1\hat R \approx 1 does not prove convergence (all the chains may be trapped in the same mode), but R^≫1\hat R \gg 1 does prove the opposite. Implementation: gelmanRubin.

Autocorrelation and effective sample size

Consecutive samples are correlated. For a chain xkx_k with normalized autocorrelation function ρ(ℓ)\rho(\ell), the integrated autocorrelation time is

τ=1+2∑ℓ=1∞ρ(ℓ),\tau = 1 + 2\sum_{\ell=1}^{\infty}\rho(\ell) ,

and the variance of the sample mean is Var(xˉ)=τ σ2/n\mathrm{Var}(\bar x) = \tau\,\sigma^2/n: a chain of nn steps is worth neff=n/τn_{\rm eff} = n/\tau independent samples. The sum is truncated with Sokal’s automatic window (stop at the first M≥cτ(M)M \ge c\tau(M), c=5c = 5; this is what emcee does) because the ρ(ℓ)\rho(\ell) at large lag are pure noise. For an AR(1) process with coefficient ϕ\phi, τ=(1+ϕ)/(1−ϕ)\tau = (1+\phi)/(1-\phi) (test with ϕ=0.9\phi = 0.9: τ=19\tau = 19). Rule of thumb: run at least 50τ50\tau steps per chain, and discard a few τ\tau 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 LL walkers where each one moves along the line joining it to another randomly chosen walker (“stretch move”, x′=xj+Z(x−xj)\mathbf x' = \mathbf x_j + Z(\mathbf x - \mathbf x_j) with ZZ of density ∝1/Z\propto 1/\sqrt Z on [1/a,a][1/a, a], a=2a = 2), accepting with probability min⁡{1,Zd−1π(x′)/π(x)}\min\{1, Z^{d-1}\pi(\mathbf x')/\pi(\mathbf x)\}. 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 τ\tau; 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

Illustration: Example: the radial-velocity curve of 51 Peg

Data: the same 40 synthetic measurements of the previous lesson (P=4.2293P = 4.2293 d, K=59K = 59 m s⁻¹, γ=−33 250\gamma = -33\,250 m s⁻¹, σ=13\sigma = 13 m s⁻¹, 61 nights). Circular model with four parameters θ=(P,K,γ,t0)\boldsymbol\theta = (P, K, \gamma, t_0):

mi=γ+Kcos⁡ ⁣[2π(ti−t0)P],ln⁡π(θ)=−12∑i(yi−mi)2σ2+ln⁡p(θ),m_i = \gamma + K\cos\!\left[\frac{2\pi(t_i - t_0)}{P}\right], \qquad \ln\pi(\boldsymbol\theta) = -\frac12\sum_i\frac{(y_i - m_i)^2}{\sigma^2} + \ln p(\boldsymbol\theta),

with uniform priors P∈[4.0,4.5]P \in [4.0, 4.5] d, K∈[0,200]K \in [0, 200], γ∈[−34 000,−32 000]\gamma \in [-34\,000, -32\,000], t0∈[−5,5]t_0 \in [-5, 5] d. Four chains of 40 000 steps from dispersed points, proposal scales (0.002,2,2,0.01)(0.002, 2, 2, 0.01), burn-in 5000. Results (mcmc.ts, fixed seeds):

ParameterTrueMean ± σ[p16, p84]R^\hat Rτ\tau (steps)
PP (d)4.22934.2324±0.00814.2324 \pm 0.0081[4.2244, 4.2405]1.003258
KK (m s⁻¹)5956.2±3.056.2 \pm 3.0[53.2, 59.2]1.00019
γ\gamma (m s⁻¹)−33 250−33 250.2±2.1-33\,250.2 \pm 2.1[−33 252.3, −33 248.1]1.00010
t0t_0 (d)0−0.074±0.074-0.074 \pm 0.074[−0.148, −0.001]1.003268

Acceptance 0.56 in all four chains. Comments:

  • Comparison with the linear theory. For a well-sampled sinusoid, σK=σ2/N=2.91\sigma_K = \sigma\sqrt{2/N} = 2.91 m s⁻¹ and σγ=σ/N=2.06\sigma_\gamma = \sigma/\sqrt N = 2.06: the posterior reproduces both (3.0 and 2.1). KK falls 0.9 σ from the true value: a normal noise realization.
  • PP–t0t_0 degeneracy. Changing PP by δP\delta P shifts the phase at the center of the campaign by 2π(30 d)δP/P22\pi(30\ \mathrm d)\delta P/P^2, which is compensated by t0t_0: the posterior is an elongated “banana” and the random-walk chain traverses it slowly (τ≈260\tau \approx 260 versus 10–20 for the others). With 35 000 useful steps, neff≈135n_{\rm eff} \approx 135 per chain for PP: enough for the mean (Monte Carlo error σP/4×135=0.0003\sigma_P/\sqrt{4\times135} = 0.0003 d) but scarce for the tails. This is the typical case where emcee (affine invariant) or reparametrizing (t0t_0 referred to the center of the campaign) gains a lot.
  • Precision of the period. σP=0.008\sigma_P = 0.008 d is 25 times smaller than the resolution of the periodogram (0.030.03 d): the periodogram locates, the fit refines.

Model comparison

Is there a planet? We compare the constant model (k=1k = 1 parameter, χ2=400.5\chi^2 = 400.5) with the circular one (k=4k = 4, χ2=48.2\chi^2 = 48.2 at the maximum). The Bayesian information criterion BIC=χ2+kln⁡N\mathrm{BIC} = \chi^2 + k\ln N gives ΔBIC=−352.3+3ln⁡40=−341\Delta\mathrm{BIC} = -352.3 + 3\ln 40 = -341: overwhelming evidence (usual threshold ∣ΔBIC∣>10|\Delta\mathrm{BIC}| > 10). The BIC is an approximation to −2ln⁡p(D)-2\ln p(D) valid for large NN 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

Illustration: Error analysis
  • Monte Carlo error. The uncertainty of any average over the chain is σpostτ/n\sigma_{\rm post}\sqrt{\tau/n}; for extreme percentiles (e.g. the 99% limit on ee) one needs neff≳103n_{\rm eff} \gtrsim 10^3–10410^4.
  • Burn-in. If included, it biases the means toward the starting point; it is detected in the trace and with R^\hat R 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 σi\sigma_i.

Problems

1. (Proof) Least squares as a Bayesian case. Show that with independent Gaussian errors and a uniform prior the maximum a posteriori minimizes χ2\chi^2, and that if the model is linear, m=Xθm = \mathbf X\boldsymbol\theta, the posterior is Gaussian with mean (XTC−1X)−1XTC−1y(\mathbf X^T\mathbf C^{-1}\mathbf X)^{-1}\mathbf X^T\mathbf C^{-1}\mathbf y and covariance (XTC−1X)−1(\mathbf X^T\mathbf C^{-1}\mathbf X)^{-1}, with C=diag(σi2)\mathbf C = \mathrm{diag}(\sigma_i^2).

Proof

ln⁡π=−χ2/2+const\ln\pi = -\chi^2/2 + \mathrm{const} with a uniform prior, so maximizing π\pi is minimizing χ2\chi^2. For m=Xθm = \mathbf X\boldsymbol\theta, χ2=(y−Xθ)TC−1(y−Xθ)\chi^2 = (\mathbf y - \mathbf X\boldsymbol\theta)^T\mathbf C^{-1}(\mathbf y - \mathbf X\boldsymbol\theta) is quadratic in θ\boldsymbol\theta: expanding and completing the square, χ2=(θ−θ^)TA(θ−θ^)+const\chi^2 = (\boldsymbol\theta - \hat{\boldsymbol\theta})^T\mathbf A(\boldsymbol\theta - \hat{\boldsymbol\theta}) + \mathrm{const} with A=XTC−1X\mathbf A = \mathbf X^T\mathbf C^{-1}\mathbf X and θ^=A−1XTC−1y\hat{\boldsymbol\theta} = \mathbf A^{-1}\mathbf X^T\mathbf C^{-1}\mathbf y. Then π∝exp⁡[−12(θ−θ^)TA(θ−θ^)]\pi \propto \exp[-\tfrac12(\boldsymbol\theta - \hat{\boldsymbol\theta})^T\mathbf A(\boldsymbol\theta - \hat{\boldsymbol\theta})]: a Gaussian of mean θ^\hat{\boldsymbol\theta} and covariance A−1\mathbf A^{-1}. 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. ■\blacksquare

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 min⁡{1,π(x′)/π(x)}\min\{1, \pi(\mathbf x')/\pi(\mathbf x)\} without the ratio q(x∣x′)/q(x′∣x)q(\mathbf x|\mathbf x')/q(\mathbf x'|\mathbf x), the stationary distribution is not π\pi. Compute what it is for q(x′∣x)=N(x+δ,s2)q(x'|x) = \mathcal N(x + \delta, s^2) with drift δ\delta and a uniform target on a large box.

Proof

With α′=min⁡{1,π(x′)/π(x)}\alpha' = \min\{1, \pi(\mathbf x')/\pi(\mathbf x)\} detailed balance requires π(x)q(x′∣x)α′(x′∣x)=π(x′)q(x∣x′)α′(x∣x′)\pi(\mathbf x)q(\mathbf x'|\mathbf x)\alpha'(\mathbf x'|\mathbf x) = \pi(\mathbf x')q(\mathbf x|\mathbf x')\alpha'(\mathbf x|\mathbf x'); if π(x′)≤π(x)\pi(\mathbf x') \le \pi(\mathbf x), the left-hand side is π(x′)q(x′∣x)\pi(\mathbf x')q(\mathbf x'|\mathbf x) and the right-hand side π(x′)q(x∣x′)\pi(\mathbf x')q(\mathbf x|\mathbf x'), equal only if qq is symmetric. In the example, inside the box π\pi is constant and α′=1\alpha' = 1: the chain is a random walk with drift δ\delta 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, q(x∣x′)/q(x′∣x)=exp⁡[−2δ(x′−x)/s2]q(\mathbf x|\mathbf x')/q(\mathbf x'|\mathbf x) = \exp[-2\delta(\mathbf x' - \mathbf x)/s^2], penalizes the steps in the direction of the drift and restores uniformity. ■\blacksquare

3. Gelman–Rubin by hand. Three chains of n=1000n = 1000 steps for KK have means 55.1, 57.8 and 56.4 and variances 8.9, 9.4 and 9.1. Compute WW, BB, V^\hat V and R^\hat R. Have they converged? What if the means were 50, 57 and 63?

Show solution

W=9.13W = 9.13; mean of means 56.43, sample variance of the means =[(1.33)2+(1.37)2+(0.03)2]/2=1.82= [(1.33)^2 + (1.37)^2 + (0.03)^2]/2 = 1.82, B=1000×1.82=1820B = 1000\times1.82 = 1820; V^=0.999×9.13+1.82=10.94\hat V = 0.999\times9.13 + 1.82 = 10.94; R^=10.94/9.13=1.095\hat R = \sqrt{10.94/9.13} = 1.095: borderline, better to run longer. With means 50, 57, 63: variance =42.3= 42.3, B=42 300B = 42\,300, V^=51.4\hat V = 51.4, R^=2.37\hat R = 2.37: 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, ρ=0.95\rho = 0.95), run Metropolis with scales 0.1σ0.1\sigma, σ\sigma, 2.4σ/d2.4\sigma/\sqrt d and 10σ10\sigma. Tabulate acceptance, τ\tau and neffn_{\rm eff} and verify that the maximum of neffn_{\rm eff} 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 ρ=0.95\rho = 0.95 the optimal isotropic scale is still bad (τ\tau 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, R^\hat R, τ\tau, marginal histograms and the PP–t0t_0 diagram. Reparametrize with t0′=t0−30t_0' = t_0 - 30 d (center of the campaign) and compare τP\tau_P. Then add the jitter parameter ss and check that its posterior is compatible with zero.

Show solution

With t0t_0 referred to the center of the campaign the PP–t0t_0 correlation almost disappears (the phase at the center no longer depends on PP) and τP\tau_P drops from ∼260\sim 260 to a few tens of steps. With jitter, ln⁡π\ln\pi includes −∑ln⁡σ2+s2-\sum\ln\sqrt{\sigma^2 + s^2}; the posterior of ss piles up at 0 (84% limit of a few m s⁻¹), as it should with data that already have the correct σ\sigma. With emcee: 32 walkers, 5000 steps, get_autocorr_time().

6. (Proof) Jeffreys prior. Show that p(θ)∝1/θp(\theta) \propto 1/\theta is the only prior on θ>0\theta > 0 invariant under changes of units θ→cθ\theta \to c\theta, and that it is equivalent to a uniform prior in ln⁡θ\ln\theta. For K∈[0.1,1000]K \in [0.1, 1000] m s⁻¹, what fraction of the prior mass falls below 1 m s⁻¹ with the uniform prior and with the Jeffreys prior?

Proof

Invariance: p(θ)dθ=p(cθ)d(cθ)p(\theta)d\theta = p(c\theta)d(c\theta) for all cc ⇒ p(θ)=c p(cθ)p(\theta) = c\,p(c\theta); with θ=1\theta = 1, p(c)=p(1)/cp(c) = p(1)/c. And p(ln⁡θ)=p(θ) dθ/dln⁡θ=p(θ)θ=constp(\ln\theta) = p(\theta)\,d\theta/d\ln\theta = p(\theta)\theta = \mathrm{const}. Uniform: 0.9/999.9=0.09 %0.9/999.9 = 0.09\,\% below 1 m s⁻¹ (the prior “knows” that KK is large). Jeffreys: ln⁡10/ln⁡104=25 %\ln 10/\ln 10^4 = 25\,\%. ■\blacksquare

7. Occam. For the data of §5, a model with free eccentricity (k=6k = 6) reaches χ2=46.9\chi^2 = 46.9. Compute ΔBIC\Delta\mathrm{BIC} against the circular one and decide. What does Wilks’ theorem say about Δχ2=1.3\Delta\chi^2 = 1.3 with 2 extra degrees of freedom?

Show solution

ΔBIC=(46.9−48.2)+2ln⁡40=−1.3+7.4=+6.1\Delta\mathrm{BIC} = (46.9 - 48.2) + 2\ln 40 = -1.3 + 7.4 = +6.1: the circular model is preferable. Wilks: under the null hypothesis (e=0e = 0) Δχ2∼χ22\Delta\chi^2 \sim \chi^2_2, and Pr⁡(χ22>1.3)=e−0.65=0.52\Pr(\chi^2_2 > 1.3) = e^{-0.65} = 0.52: the improvement is what is expected by chance. (Strictly, e=0e = 0 lies on the boundary of the parameter space, which modifies the distribution; the BIC is more conservative.)

✦ Self-assessment

  1. 1. With independent Gaussian errors and a uniform prior, the maximum of the posterior coincides with
  2. 2. In Metropolis with a symmetric proposal, a proposal with higher posterior probability than the current state
  3. 3. Detailed balance π(x)T(x′|x) = π(x′)T(x|x′) guarantees that
  4. 4. A Gelman–Rubin R̂ of 2.4 indicates
  5. 5. A chain of 40 000 steps with autocorrelation time τ = 260 is equivalent to about
  6. 6. The main advantage of the Goodman–Weare ensemble sampler (emcee) is
Answer all the questions to check.

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 PP–t0t_0 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.
Key terms in this lesson (12)

Glossary terms that appear in the text. Each one links to its full entry.

  • MCMC (Markov chain Monte Carlo) A method for randomly exploring all the possible combinations of the parameters of a model, spending more time on the most probable ones. It is how the "error bars" of exoplanets are obtained.
  • Bayesian inference A way of reasoning with probabilities: you start from what you believe (the prior), look at the data and update your belief (the posterior). It is how astronomers estimate the mass of a planet together with its uncertainty.
  • Linear regression Drawing the line that best passes "through the middle" of a cloud of points. That is how Hubble found that the velocity of galaxies grows with their distance, and the slope of that line is his famous constant.
  • Degeneracy pressure A pressure that appears when matter is so tightly packed that the electrons cannot get any closer together, because of a rule of quantum physics. It holds up white dwarfs even when they are cold.
  • Periodogram A tool for finding hidden rhythms in data taken at irregular times: for each possible period it says how well a wave "fits". That is how the period of a planet is found in radial velocity data.
  • Transit When a planet passes in front of its star and takes away a bit of its brightness, like a moth crossing in front of a lighthouse. Measuring that dip gives the size of the planet.
  • Exoplanet A planet that orbits a star other than the Sun. More than 5000 have been known since 1995; most were discovered by watching them block a tiny bit of their star's light as they pass in front of it.
  • Gravitational wave Ripples in spacetime itself that travel at the speed of light, produced by enormous masses accelerating, such as two black holes colliding. They were first detected in 2015.
  • Apparent magnitude A number that says how bright a star looks from Earth. The smaller it is, the brighter the star: Sirius has −1.5, and the faintest stars you can see with the naked eye, 6.
  • Eccentricity A number between 0 and 1 that says how flattened an orbit is: 0 is a perfect circle, and the closer to 1, the more elongated. Earth's is 0.017, almost a circle; Halley's comet's, 0.97.
  • Light curve A chart of the brightness of a star over time. A transit shows up as a small "dip"; a variable star, as waves that rise and fall.
  • Logarithm The question "to what power must 10 be raised to get this number?". log(1000) = 3. It turns multiplications into additions and compresses huge numbers: that is why stellar magnitudes use logarithms.

See the whole glossary →

References

  • Gregory, P. C. (2005). Bayesian Logical Data Analysis for the Physical Sciences, Cambridge University Press, chs. 3, 11 and 12.
  • Foreman-Mackey, D., Hogg, D. W., Lang, D. & Goodman, J. (2013). emcee: The MCMC Hammer. PASP 125, 306. doi:10.1086/670067. arXiv:1202.3665.
  • Goodman, J. & Weare, J. (2010). Ensemble samplers with affine invariance. Comm. Appl. Math. Comp. Sci. 5, 65. doi:10.2140/camcos.2010.5.65.
  • Gelman, A. & Rubin, D. B. (1992). Inference from iterative simulation using multiple sequences. Statistical Science 7, 457. doi:10.1214/ss/1177011136.
  • Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H. & Teller, E. (1953). Equation of state calculations by fast computing machines. J. Chem. Phys. 21, 1087.
  • Hastings, W. K. (1970). Monte Carlo sampling methods using Markov chains and their applications. Biometrika 57, 97.
  • Hogg, D. W. & Foreman-Mackey, D. (2018). Data analysis recipes: Using Markov chain Monte Carlo. ApJS 236, 11. arXiv:1710.06068.
  • Sokal, A. D. (1997). Monte Carlo methods in statistical mechanics: foundations and new algorithms. In Functional Integration, Plenum.
  • Perryman, M. (2018). The Exoplanet Handbook, 2nd ed., §2.3 and §6.4.