Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Metropolis-Hastings for Classical Distributions

Hello! Welcome to your next lesson on numerical methods for quantum systems.

In our last lesson, you mastered Exact Diagonalization (ED), a powerful "brute-force" method for finding the exact energy spectrum and eigenstates of small quantum many-body systems. We also confronted its primary weakness: the curse of dimensionality, where the computational cost grows exponentially, making it intractable for all but the smallest systems.

To tackle larger, more realistic problems—a key part of your goal to study many-body physics—we must turn to methods that don't require storing the entire Hamiltonian. This brings us to the world of Monte Carlo methods.

Today, we will learn the engine that drives many of these powerful techniques. Your learning outcome for this lesson is to:

  • Implement the Metropolis-Hastings algorithm for sampling a classical probability distribution.

This might seem like a step away from quantum mechanics, but it's a crucial one. The Metropolis-Hastings algorithm is a general and powerful tool for statistical sampling in high-dimensional spaces. We'll master its mechanics in a classical context today, and in our next lesson, we will apply it directly to solve quantum problems using Variational Monte Carlo.

1. The Challenge of High-Dimensional Integrals

At the heart of many problems in physics, especially statistical mechanics and quantum mechanics, lies the need to compute high-dimensional integrals. For instance, the expectation value of an observable in statistical mechanics is given by an integral over the entire phase space of a system:

For particles in 3D, this is an integral over dimensions! Standard numerical integration methods like the trapezoidal or Simpson's rule, which rely on evaluating the function on a grid, fail catastrophically here. If you use just 10 grid points per dimension, you'd need points—an impossible number. This is another manifestation of the "curse of dimensionality."

Monte Carlo methods solve this by replacing a deterministic evaluation on a grid with a statistical sampling of the space.

MetropolisHastings_Tutorial

This article, 'Metropolis-Hastings MCMC Tutorial', provides an excellent motivation for why we need sampling methods. It clearly explains the failure of grid-based integration in high dimensions and introduces the idea of solving integrals by sampling.

Please read the introduction and the section 'Solving integrals'. Focus on understanding why the error of standard numerical integration scales poorly with dimension d (ϵ ∝ 1/N^(2/d)), while the error of Monte Carlo sampling is independent of dimension (ϵ ∝ 1/√N).

The simplest Monte Carlo approach is to sample points uniformly and average them. However, this is inefficient if the function you're integrating is peaked in a small region of the space. A much better strategy is importance sampling, where you preferentially draw samples from regions where the function's value is high.

To do this, you need to be able to draw random numbers from a distribution that mimics your function. But what if that distribution is complex and non-standard? This is where the Metropolis-Hastings algorithm comes in. It's a method to generate samples from any probability distribution , even if we only know up to a normalization constant.

2. The Metropolis-Hastings Algorithm: A "Smart" Random Walk

The core idea of the Metropolis-Hastings algorithm is to construct a "smart" random walk in the space of possible states (or configurations) . This walk, known as a Markov chain, is designed so that the points it visits, after an initial "burn-in" period, are distributed according to the target probability distribution .

Let's get a visual intuition for how this works.

Metropolis-Hastings - VISUALLY EXPLAINED!

The video 'Metropolis-Hastings - VISUALLY EXPLAINED!' by Kapil Sachdeva provides a clear, step-by-step visual demonstration of the algorithm for a 1D distribution.

Watch from the beginning to 10:11. Pay close attention to the core loop: Start at a current point. Propose a new point by taking a random step. Calculate the acceptance probability (alpha). Decide whether to move to the new point or stay put.

Now let's formalize the algorithm's steps.

Metropolis-Hastings Algorithm Overview
A visual schematic of the Metropolis-Hastings algorithm. Starting from a current state \(x_t\), a new state is proposed. The algorithm then uses a probabilistic rule based on the target distribution \(P(x)\) to decide whether to accept the new state or to remain at the current state for the next step of the chain.

The Algorithm:

  1. Initialize: Start at an arbitrary state .
  2. Iterate for a large number of steps, :
    a. Propose: Generate a candidate state from a proposal distribution . A common choice is a Gaussian distribution centered at the current state .
    b. Calculate Acceptance Ratio: Compute the ratio:

    The first term is the ratio of target probabilities. The second term, the Hastings ratio, corrects for any asymmetry in the proposal distribution. If the proposal distribution is symmetric (e.g., a Gaussian step), then , and the ratio simplifies to the original Metropolis algorithm ratio:

    c. Accept or Reject:
    • Generate a uniform random number .
    • If , accept the new state: .
    • Otherwise, reject the new state and stay put: .

A crucial feature of this algorithm is that it only depends on the ratio of probabilities, . This means you don't need to know the normalization constant of your probability distribution! This is immensely powerful, as the normalization constant (like the partition function ) is often the very intractable integral we wanted to avoid in the first place.

The underlying principle that ensures this works is the condition of detailed balance. In equilibrium, the probability flow from any state to any other state must equal the flow from to . The acceptance rule is constructed precisely to satisfy this.

The Ising Model in Python: Statistical Mechanics and Permanent Magnets

For a physics-based perspective on detailed balance and its connection to the Metropolis acceptance rule, let's look at its application to the Ising model, a system you're familiar with.

Watch the segment from 02:16 to 06:54. The video explains the Boltzmann distribution and the detailed balance condition, which provides the theoretical foundation for the algorithm's acceptance criteria.

Test your understanding!

Suppose you are sampling a distribution with the Metropolis algorithm (symmetric proposal) and your walker is currently at , where . You propose a move to .

  1. If , what is the probability that you accept this move?
  2. If , what is the probability that you accept this move?
Show answer
  1. The acceptance ratio is . The acceptance probability is . The move is accepted with 100% probability. This makes sense: you always move "uphill" to a more probable state.

  2. The acceptance ratio is . The acceptance probability is . The move is accepted with 40% probability. You sometimes move "downhill," which is essential for exploring the entire distribution.

3. Implementation and Diagnostics

Now, let's translate the algorithm into code. You will implement a simple Metropolis-Hastings sampler in Python.

MetropolisHastings_Tutorial

The 'MetropolisHastings_Tutorial' article provides a clear schematic and then guides you through building and testing the sampler. We will follow its excellent exercises.

First, read section 'Metropolis-Hastings MCMC' to see the algorithm schematic. Then, following the prompts in 'Exercise 2.0: log acceptance ratio' and 'Exercise 2.1: Testing our sampler', try to write a Python function that implements the algorithm to sample a 1D Gaussian distribution. Using log probabilities (log(P(x')) - log(P(x))) is highly recommended for numerical stability.

As you implement and run your sampler, you will quickly discover that its performance depends critically on a few practical details.

Diagnostics and Tuning

How do you know if your sampler is working correctly and efficiently?

  1. Burn-in: The chain needs some number of steps to forget its initial starting position and converge to the target distribution. These initial steps are called the "burn-in" period and should be discarded from your final set of samples.
  2. Trace Plots: A plot of the sample value at each iteration (the "trace") is the most basic diagnostic. It should look like a fuzzy caterpillar exploring the high-probability region, without long-term drifts or getting stuck.
  3. Acceptance Rate: The fraction of proposed moves that are accepted is a key indicator of efficiency.
    • If the proposal step size is too small: Most moves will be accepted, but the walker explores the space very slowly. The trace plot will look highly correlated.
    • If the proposal step size is too large: Most moves will land in low-probability regions and be rejected. The walker will get stuck at the same point for many steps.
    • A rule of thumb is to tune the proposal step size to achieve an acceptance rate of around 20-50%.
Metropolis-Hastings Algorithm Convergence
Histograms of samples generated by the Metropolis-Hastings algorithm. As the number of steps increases from 100 to 100,000, the histogram of the samples provides an increasingly accurate approximation of the true target distribution (red curve).

A Practical Guide to MCMC Part 1: MCMC Basics

This article, 'A Practical Guide to MCMC Part 1', provides excellent visual examples of good and bad sampler performance.

Read the section 'Diagnosing efficiency and convergence'. Compare the three figures showing trace plots and histograms for a jump size that is too small, too large, and just right. This will give you a strong intuition for tuning your own sampler.

4. Application: The 2D Ising Model

Let's apply the Metropolis algorithm to a problem central to condensed matter physics: simulating the 2D Ising model. Here, the "state" is a configuration of spins on a lattice, and the target probability distribution is the Boltzmann distribution, .

The Metropolis algorithm for the Ising model is:

  1. Start with a random lattice of N spins, .
  2. Repeat for many steps:
    a. Pick a spin at a random site .
    b. Propose flipping it: .
    c. Calculate the change in energy, , that this flip would cause.
    d. If , accept the flip.
    e. If , accept the flip with probability .
  3. After a burn-in period, collect measurements of quantities like total magnetization or energy to find their thermal averages.

This allows you to simulate the thermal equilibrium properties of the magnet at a given temperature , including the phase transition from a disordered paramagnet to an ordered ferromagnet.

The Ising Model in Python: Statistical Mechanics and Permanent Magnets

The video 'The Ising Model in Python' walks through this exact application, from the physics principles to the Python code.

Watch the sections explaining the Metropolis algorithm for the Ising model (10:58 - 15:23) and the subsequent code walkthrough (19:23 - 26:29). This will solidify the connection between the general algorithm and a concrete physical simulation.

Conclusion

In this lesson, you have learned the fundamentals of the Metropolis-Hastings algorithm, one of the most important algorithms in computational science.

Key Takeaways:

  • Monte Carlo methods use statistical sampling to solve high-dimensional problems where grid-based methods fail due to the curse of dimensionality.
  • The Metropolis-Hastings algorithm generates a sequence of samples (a Markov chain) that are distributed according to a target probability distribution .
  • Its core is a propose-accept/reject mechanism that satisfies detailed balance, ensuring convergence to the correct distribution.
  • A key strength is its reliance only on the ratio of probabilities, making it applicable even when the distribution's normalization constant is unknown.
  • The performance of the sampler depends critically on tuning the proposal distribution, with the acceptance rate being a key diagnostic.

Preview of the Next Lesson:

We have successfully built a tool for sampling classical probability distributions. Now, we will bring this tool back into the quantum realm. In the next lesson, Variational Monte Carlo (VMC), we will use the Metropolis algorithm to sample the probability distribution defined by a quantum wavefunction itself, . This will allow us to calculate the ground state energy and other properties for many-body quantum systems far larger than what is possible with Exact Diagonalization.

Can't find a good explanation? Sign up and we'll make it for you

Sign up