Algorithm Search⌘K

Algorithmcore

Kinetic Monte Carlo

Also called Bortz-Kalos-Lebowitz algorithm, n-fold way, residence time algorithm.

Simulates a system that moves by rare events with known rates. Each step draws an exponential waiting time from the total rate and picks one event with probability proportional to its rate.

Time
O(N M) worst
Space
O(M) extra
Where
M = the number of possible events in the current state; N = the number of events in the run
Properties
randomizedexactiterativerandomized
Origin
Alfred B. Bortz, Malvin H. Kalos, Joel L. Lebowitz, 1975

Kinetic Monte Carlo (KMC) simulates a system that moves from state to state by rare, separate events, each with a known rate, for example an atom that hops between sites of a crystal surface. In the current state it adds the rates of all possible events, draws the time to the next event from an exponential law with that total rate, and picks one event with probability proportional to its rate. Each step is one event, so KMC reaches seconds or hours of physical time, where molecular dynamics with a step of about 1 fs needs about 101010^{10} steps for one event that takes 25 microseconds. The algorithm is the same as the Gillespie algorithm of chemical kinetics; the difference is the setting: in KMC the states are atomic configurations and the rates usually come from harmonic transition state theory, not from reaction propensities.

In plain words

Think of a crystal surface with a few loose atoms on it. Most of the time each atom only shakes in its site. Now and then one atom jumps to a next site. A simulation of the shaking wastes almost all its work.

Kinetic Monte Carlo skips the shaking. It needs a list of every jump that can happen now, with a rate for each one: how often that jump happens on average. A fast jump is more likely to come first. So the method picks a jump at random, with a chance in proportion to its rate. Then it moves the clock forward by a random waiting time. The waiting time is short when the total rate is high. Then the list changes, and the method repeats. The result is a random history of jumps with the correct statistics, if the list is complete and the rates are right.

The problem

The input is a continuous-time Markov jump process given by its rates: for each state xx, a finite list of events j=1,…,Mj = 1, \ldots, M with rates kj(x)>0k_j(x) > 0 (in s−1\mathrm{s}^{-1}) and target states yj(x)y_j(x). The process stays in xx for a random time, then jumps to yjy_j, and the time and the choice obey

P(event j happens in [t,t+dt)∣state x at t)=kj(x) dt+o(dt).P(\text{event } j \text{ happens in } [t, t + dt) \mid \text{state } x \text{ at } t) = k_j(x)\, dt + o(dt).

The output is a sample path (t0,x0),(t1,x1),…(t_0, x_0), (t_1, x_1), \ldots of this process up to a time tendt_{\mathrm{end}}, and time averages along it. The probabilities p(x,t)p(x, t) of the states solve the master equation dp(y)/dt=∑xp(x)kx→y−p(y)∑zky→zdp(y)/dt = \sum_x p(x) k_{x \to y} - p(y) \sum_z k_{y \to z} (see the chemical master equation); KMC samples paths of this equation and does not solve it.

In materials, an event is a jump over a saddle of the potential energy, and its rate is k=νexp⁡(−Ea/(kBT))k = \nu \exp(-E_a / (k_B T)) with a barrier EaE_a and a prefactor ν\nu, often of order 101210^{12} to 1013 s−110^{13}\ \mathrm{s}^{-1}. Here kBk_B is the Boltzmann constant and TT the temperature.

The algorithm

  1. KINETIC-MONTE-CARLO(x, EVENTS, t_end)
  2. 1t ← 0
  3. 2while t < t_end do
  4. 3(k_1, y_1), ..., (k_M, y_M) ← EVENTS(x)
  5. 4R ← k_1 + ... + k_M ▷ total escape rate of x
  6. 5if R = 0 then return ▷ no event is possible
  7. 6draw u_1 uniform in [0, 1) and u_2 uniform in (0, 1]
  8. 7Δt ← -ln(u_2) / R ▷ exponential waiting time
  9. 8if t + Δt ≥ t_end then add f(x) (t_end - t) to the average, t ← t_end, return
  10. 9add f(x) Δt to the average ▷ x holds during the wait
  11. 10j ← the smallest index with k_1 + ... + k_j > u_1 R
  12. 11t ← t + Δt, x ← y_j
  13. 12record (t, x)
  14. 13return x, t, the path and the time average of f

Line L7 is inverse transform sampling of the exponential law with rate RR: if u2u_2 is uniform on (0,1](0, 1], then P(−ln⁡u2/R>s)=P(u2<e−Rs)=e−RsP(-\ln u_2 / R > s) = P(u_2 < e^{-Rs}) = e^{-Rs}. Line L10 picks event jj with probability kj/Rk_j / R, because u1Ru_1 R is uniform on [0,R)[0, R) and the interval of event jj has length kjk_j. Line L9 weights the observable ff with the time that the system stays in xx, which is the correct weight for a time average. The two random numbers are independent, and so are the waiting time and the choice, as the proof shows.

The variant of Bortz, Kalos and Lebowitz groups the events into classes with equal rates, picks a class by its total rate and then a member uniformly. This is the same distribution with a shorter search.

Example

A two-state system by hand. Let state A go to B with rate kAB=1k_{AB} = 1 and B go to A with rate kBA=3k_{BA} = 3, in units of s−1\mathrm{s}^{-1}. Each state has one event, so line L10 always picks it, and only u2u_2 matters. Start in A at t=0t = 0:

step state RR u2u_2 Δt=−ln⁡(u2)/R\Delta t = -\ln(u_2) / R tt after the jump new state
1 A 1 0.5 0.693147 0.693147 B
2 B 3 0.9 0.035120 0.728268 A
3 A 1 0.3 1.203973 1.932241 B
4 B 3 0.6 0.170275 2.102515 A

The time in A is 0.693147+1.203973=1.8971200.693147 + 1.203973 = 1.897120 of 2.1025152.102515, a fraction of 0.9023 after four events. The exact long-time fraction is kBA/(kAB+kBA)=3/4k_{BA} / (k_{AB} + k_{BA}) = 3/4, because the mean time in A is 1/kAB=11/k_{AB} = 1 and the mean time in B is 1/kBA=1/31/k_{BA} = 1/3. A run with random.Random(1) gives these fractions:

tendt_{\mathrm{end}} events fraction of time in A
10 18 0.8420
100 151 0.7839
1000 1500 0.7562
10000 15109 0.7477

The error of a time average falls like N−1/2N^{-1/2} in the number NN of events, as for any Monte Carlo integration.

A choice among three events. In a state with rates 1,2,31, 2, 3, the total is R=6R = 6. With u1=0.4u_1 = 0.4, line L10 looks for the first partial sum above u1R=2.4u_1 R = 2.4: the sums are 1,3,61, 3, 6, so it picks event 2. The waiting time has mean 1/R=1/61/R = 1/6 and standard deviation 1/61/6, whatever event follows.

Why KMC is needed. An adatom hop with ν=1013 s−1\nu = 10^{13}\ \mathrm{s}^{-1} and Ea=0.5E_a = 0.5 eV at T=300T = 300 K, where kBT=0.025852k_B T = 0.025852 eV, has the rate k=1013e−0.5/0.025852=3.98×104 s−1k = 10^{13} e^{-0.5 / 0.025852} = 3.98 \times 10^{4}\ \mathrm{s}^{-1}. The mean time between hops is 25.125.1 microseconds, which is 2.5×10102.5 \times 10^{10} MD steps of 1 fs. KMC does one step per hop. At T=600T = 600 K the rate is 6.31×108 s−16.31 \times 10^{8}\ \mathrm{s}^{-1}: the rates of activated events change by orders of magnitude with the temperature.

Correctness

The claim is that the path is an exact sample of the Markov jump process, up to the quality of the random numbers and rounding. The key fact is the race of exponential clocks: if each event jj has an independent exponential clock with rate kjk_j, the first clock to ring rings at a time with the exponential law of rate R=∑jkjR = \sum_j k_j, it is clock jj with probability kj/Rk_j / R, and the time and the index are independent. Lines L6 to L10 draw exactly this pair. By the Markov property, the process after the jump starts afresh from yjy_j, so the loop repeats the same step. The full proof is below; it also shows that the time average of line L9 converges to the stationary average when the chain is irreducible and has finitely many states.

What the proof does not cover is the model. KMC is exact for the rate model it is given. If an event is missing from the catalog, or a rate is wrong, the path is a correct sample of a wrong process. Rates from harmonic transition state theory are an approximation with their own hypotheses.

Proof: Kinetic Monte Carlo samples the Markov jump process exactlyfull

We assume exact arithmetic and exact uniform random numbers u1u_1 in [0,1)[0, 1) and u2u_2 in (0,1](0, 1], independent of each other and of all earlier draws. A Markov jump process with rates kj(x)k_j(x) and targets yj(x)y_j(x) is the process that, in state xx, waits a time τ\tau with P(τ>s)=e−R(x)sP(\tau > s) = e^{-R(x) s}, R(x)=∑jkj(x)R(x) = \sum_j k_j(x), then jumps to yj(x)y_j(x) with probability kj(x)/R(x)k_j(x) / R(x), independently of τ\tau, and then starts afresh from the new state. This is the standard construction of the process from its jump chain and its holding times; it is equivalent to the infinitesimal description P(event j in [t,t+dt))=kj dt+o(dt)P(\text{event } j \text{ in } [t, t + dt)) = k_j\, dt + o(dt).

Lemma 1 (the race of exponential clocks). Let T1,…,TMT_1, \ldots, T_M be independent with P(Tj>s)=e−kjsP(T_j > s) = e^{-k_j s}, kj>0k_j > 0. Let T=min⁡jTjT = \min_j T_j and let JJ be the index of the minimum. Then P(T>s,J=j)=(kj/R)e−RsP(T > s, J = j) = (k_j / R) e^{-R s} for all s≥0s \ge 0, with R=∑jkjR = \sum_j k_j. So TT is exponential with rate RR, P(J=j)=kj/RP(J = j) = k_j / R, and TT and JJ are independent.

Proof. The index of the minimum is unique with probability 1, because the laws have densities. Condition on Tj=rT_j = r:

P(T>s,J=j)=∫s∞kje−kjr∏i≠jP(Ti>r) dr=∫s∞kje−Rr dr=kjRe−Rs.P(T > s, J = j) = \int_s^\infty k_j e^{-k_j r} \prod_{i \ne j} P(T_i > r)\, dr = \int_s^\infty k_j e^{-R r}\, dr = \frac{k_j}{R} e^{-R s}.

Summing over jj gives P(T>s)=e−RsP(T > s) = e^{-Rs}, and s=0s = 0 gives P(J=j)=kj/RP(J = j) = k_j / R. The joint law is the product of the two marginal laws, so TT and JJ are independent. □\square

This is the reason why the two descriptions of the process agree: if every event has its own exponential clock, the first one to ring has the law of the construction above.

Lemma 2 (one step). In state xx with R=R(x)>0R = R(x) > 0, lines L6, L7 and L10 return Δt\Delta t and jj with P(Δt>s,j)=(kj/R)e−RsP(\Delta t > s, j) = (k_j / R) e^{-R s}.

Proof. Line L7 sets Δt=−ln⁡(u2)/R\Delta t = -\ln(u_2) / R. For s≥0s \ge 0, Δt>s\Delta t > s holds if and only if u2<e−Rsu_2 < e^{-Rs}, which has probability e−Rse^{-Rs} because u2u_2 is uniform on (0,1](0, 1] and e−Rs∈(0,1]e^{-Rs} \in (0, 1]. Line L10 picks the smallest jj with Sj>u1RS_j > u_1 R, where Sj=k1+⋯+kjS_j = k_1 + \cdots + k_j and S0=0S_0 = 0. Because Sj−1<SjS_{j-1} < S_j, this is the jj with Sj−1≤u1R<SjS_{j-1} \le u_1 R < S_j. The variable u1Ru_1 R is uniform on [0,R)[0, R), so this has probability (Sj−Sj−1)/R=kj/R(S_j - S_{j-1}) / R = k_j / R. The index depends only on u1u_1 and Δt\Delta t only on u2u_2, so they are independent, and the joint law is the product. □\square

Theorem (exact sampling). Let t0=0<t1<t2<⋯t_0 = 0 < t_1 < t_2 < \cdots be the times recorded by line L12 and x0,x1,…x_0, x_1, \ldots the states. Then the joint law of (tn,xn)n≥0(t_n, x_n)_{n \ge 0}, up to the first nn with tn≥tendt_n \ge t_{\mathrm{end}} or R(xn)=0R(x_n) = 0, is the law of the jump times and states of the Markov jump process started at x0x_0.

Proof. By induction on the number nn of steps. For n=0n = 0 both start at (0,x0)(0, x_0). Assume that the first nn pairs have the correct joint law. Given these pairs, step n+1n + 1 uses only the state xnx_n and new random numbers, which are independent of the past. By Lemma 2, it draws the holding time tn+1−tnt_{n+1} - t_n and the next state xn+1=yj(xn)x_{n+1} = y_j(x_n) with the law of the construction, given xnx_n, and independently of the earlier pairs. This is the conditional law of the next jump of the Markov jump process given its past, by the Markov property of the construction. So the first n+1n + 1 pairs have the correct joint law. If R(xn)=0R(x_n) = 0, the state xnx_n is absorbing and the process stays in it, which is what line L5 returns. If tn+Δt≥tendt_n + \Delta t \ge t_{\mathrm{end}}, the next jump is after tendt_{\mathrm{end}}, so the process is in xnx_n on [tn,tend][t_n, t_{\mathrm{end}}], which is what line L8 uses. ■\blacksquare

The time average. Lines L8 and L9 add f(xn)f(x_n) times the length of the part of [tn,tn+1)[t_n, t_{n+1}) that lies in [0,tend][0, t_{\mathrm{end}}]. The sum is exactly ∫0tf(x(s)) ds\int_0^{t} f(x(s))\, ds for the piecewise constant path x(s)x(s), and the result is this integral divided by tt. If the state space is finite and the process is irreducible, the ergodic theorem for Markov jump processes gives 1t∫0tf(x(s)) ds→∑xπ(x)f(x)\frac{1}{t}\int_0^t f(x(s))\, ds \to \sum_x \pi(x) f(x) almost surely as t→∞t \to \infty, where π\pi is the unique stationary distribution.

For the two-state system of the page this limit can be found directly. The visits to A and B alternate. The times in A are independent with mean 1/kAB1 / k_{AB} and the times in B are independent with mean 1/kBA1 / k_{BA}. By the renewal reward theorem, the long-run fraction of time in A is the mean time in A over the mean length of one cycle,

1/kAB1/kAB+1/kBA=kBAkAB+kBA,\frac{1 / k_{AB}}{1 / k_{AB} + 1 / k_{BA}} = \frac{k_{BA}}{k_{AB} + k_{BA}},

which is also π(A)\pi(A) from the balance π(A)kAB=π(B)kBA\pi(A) k_{AB} = \pi(B) k_{BA}. With kAB=1k_{AB} = 1 and kBA=3k_{BA} = 3 it is 3/43/4.

What is not proved. The theorem is about the rate model. It says nothing about whether the rates are right, whether the catalog of events is complete, or whether the real system is a Markov jump process. For atomic systems, the Markov property holds only approximately, when the system loses the memory of how it entered a state before it leaves it. This is the separation of time scales that transition state theory assumes.

Complexity

In the real RAM model, one step costs one call of EVENTS, MM additions for line L4 and up to MM additions and comparisons for line L10, so Θ(M)\Theta(M) apart from EVENTS. A run of NN events costs O(NM)O(N M) and O(M)O(M) extra space.

  • Search. A binary tree of partial sums (a sum tree, or a Fenwick tree) gives line L10 in O(log⁡M)O(\log M) time, and a change of one rate in O(log⁡M)O(\log M) time.
  • Update. On a lattice, one event changes only the rates of nearby sites, so the catalog update is O(1)O(1) per step at fixed range, and a step costs O(log⁡M)O(\log M) with the tree.
  • Physical time. The mean step is 1/R1/R. If the fastest event is much faster than the events of interest, most steps go to the fast event and the run advances slowly. This is a property of the rates, not of the algorithm.

Properties

  • Rejection free. Each step makes one event. The older rejection method proposes an event with a fixed upper bound of the rates and rejects it with probability 1−kj/kmax⁡1 - k_j / k_{\max}; it gives the same process with more steps when the rates differ much.
  • Exact in time. The waiting times are exponential, not the mean 1/R1/R. A fixed increment 1/R1/R gives the correct mean time but the wrong distribution of times.
  • No time step. There is no discretization error in time, unlike tau-leaping.
  • Randomized. The output is a random path. Two runs with different seeds differ, and averages need many events.

Variants and improvements

  • Lattice KMC. The states are occupations of the sites of a fixed lattice, and the catalog is a short table of local moves with fixed barriers. This is the fastest and most common form.
  • On-the-fly or adaptive KMC. The catalog is built in each new state by saddle searches, for example with the dimer method, and rates come from harmonic transition state theory. The catalog may be incomplete, and the method gives a bound on what it misses only with extra assumptions.
  • First reaction method. Draw one exponential time for each event and take the smallest. This is the same distribution with MM random numbers per step.
  • Time-dependent rates. If the rates change with time, for example in a temperature ramp, line L7 must solve ∫tt+ΔtR(s) ds=−ln⁡u2\int_t^{t + \Delta t} R(s)\, ds = -\ln u_2 instead.
  • Accelerated dynamics. Parallel replica dynamics, hyperdynamics and temperature accelerated dynamics find the events by molecular dynamics instead of from a list.

When to use it

Use KMC when the dynamics is a sequence of rare events whose types and rates you know, and the time scale of interest is far beyond molecular dynamics: diffusion and growth on surfaces, annealing of radiation damage, vacancy diffusion in alloys, catalysis. Use molecular dynamics when you do not know the events, or when the motion is not a sequence of separate events, for example in a liquid. Use tau-leaping when many events fire in a short time and their exact order is not important.

Pitfalls

  • A missing event. The catalog of line L3 must hold every event that can happen. An event that is not in the list never happens, and nothing in the run shows this.
  • The logarithm of zero. Line L6 must draw u2u_2 in (0,1](0, 1], for example as 1−u1 - u with uu in [0,1)[0, 1). With u2=0u_2 = 0, line L7 gives an infinite time.
  • A fixed time increment. Writing Δt=1/R\Delta t = 1/R in line L7 keeps the mean time but gives wrong waiting time distributions and wrong time correlations.
  • Unweighted averages. An average over the recorded states without the weights Δt\Delta t of line L9 is an average over events, not over time. It gives the wrong value: in the two-state example it gives 1/2, not 3/4.
  • The low barrier problem. If two states are joined by a very fast event, the run flips between them at almost every step and the clock hardly moves. Merge such states into one, or use an accelerated variant.
  • Rates without detailed balance. For a system in thermal equilibrium the rates must satisfy detailed balance with respect to the Boltzmann distribution. Rates from barriers of the same saddle seen from both sides do; rates fitted one by one may not.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

kinetic_monte_carlo.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kinetic-monte-carlo/. The authors are listed in prov/SFQPD9.jsonl.
"""Kinetic Monte Carlo by the residence time algorithm (Bortz, Kalos and Lebowitz 1975).

The system is a continuous-time Markov jump process. In a state x, the
function events(x) gives the list of possible events as pairs (k_j, y_j):
the rate k_j > 0 of event j and the state y_j after it. One step of the
algorithm draws the waiting time from an exponential law with rate
R = k_1 + ... + k_M, picks event j with probability k_j / R, and jumps.

The catalog of events must be complete: an event that is missing has rate
zero in the simulation, and no later step can correct this.

Cost per step: one call of events(x) and Theta(M) work for the sum and the
linear search, for M events. A sum tree makes the search O(log M).
"""

import math
from typing import Callable, Hashable, Optional

State = Hashable
Events = Callable[[State], list[tuple[float, State]]]


def select_event(rates: list[float], r: float) -> int:
    """The smallest index j with k_0 + ... + k_j > r, for 0 <= r < sum(rates)."""
    acc = 0.0
    for j, k in enumerate(rates):
        acc += k
        if acc > r:
            return j
    # r is within rounding of the total: take the last event with a positive rate.
    for j in range(len(rates) - 1, -1, -1):
        if rates[j] > 0:
            return j
    raise ValueError("no event has a positive rate")


def kinetic_monte_carlo(
    x: State, events: Events, t_end: float, rng,
    observe: Optional[Callable[[State], float]] = None, max_steps: int = 10**6,
):
    """Run the residence time algorithm from state x until time t_end.

    rng needs a method random() that returns a float in [0, 1).
    Returns (x, t, path, average): the final state, the final time
    (t_end, or the time of the last event if no event is possible), the
    list of (time, state) after each event with (0, x) first, and the
    time average over [0, t] of observe(state) (None if observe is None).
    """
    t = 0.0                                                   # @line L1
    path = [(t, x)]
    integral = 0.0
    for _ in range(max_steps):
        if t >= t_end:                                        # @line L2
            break
        ev = events(x)                                        # @line L3
        rates = [k for k, _ in ev]
        total = sum(rates)                                    # @line L4
        if total <= 0.0:                                      # @line L5
            break
        u1 = rng.random()                                     # @line L6
        u2 = 1.0 - rng.random()                               # @line L6
        dt = -math.log(u2) / total                            # @line L7
        if t + dt >= t_end:                                   # @line L8
            if observe is not None:
                integral += observe(x) * (t_end - t)
            t = t_end
            break
        if observe is not None:                               # @line L9
            integral += observe(x) * dt
        j = select_event(rates, u1 * total)                   # @line L10
        t += dt                                               # @line L11
        x = ev[j][1]                                          # @line L11
        path.append((t, x))                                   # @line L12
    average = None
    if observe is not None and t > 0:
        average = integral / t
    return x, t, path, average                                # @line L13


def arrhenius_rate(prefactor: float, barrier: float, kT: float) -> float:
    """The harmonic transition state theory rate nu exp(-E / kT)."""
    return prefactor * math.exp(-barrier / kT)
test_kinetic_monte_carlo.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kinetic-monte-carlo/. The authors are listed in prov/SFQPD9.jsonl.
import math
import random

import pytest

from kinetic_monte_carlo import arrhenius_rate, kinetic_monte_carlo, select_event


class FixedRng:
    """Returns the given numbers in order, so that a run can be checked by hand."""

    def __init__(self, values):
        self.values = list(values)

    def random(self):
        return self.values.pop(0)


def two_state(k_ab, k_ba):
    return lambda x: [(k_ab, "B")] if x == "A" else [(k_ba, "A")]


def test_select_event():
    rates = [1.0, 2.0, 3.0]
    assert select_event(rates, 0.0) == 0
    assert select_event(rates, 0.999) == 0
    assert select_event(rates, 1.0) == 1
    assert select_event(rates, 2.999) == 1
    assert select_event(rates, 3.0) == 2
    assert select_event(rates, 5.999) == 2
    assert select_event([1.0, 0.0], 1.0) == 0


def test_trace_by_hand():
    # The page example: k_AB = 1, k_BA = 3. Each step uses (u1, 1 - u2).
    u = [(0.5, 0.5), (0.2, 0.9), (0.7, 0.3), (0.1, 0.6)]
    flat = [v for a, b in u for v in (a, 1.0 - b)]
    x, t, path, avg = kinetic_monte_carlo(
        "A", two_state(1.0, 3.0), 10.0, FixedRng(flat + [0.5, 0.5]),
        observe=lambda s: 1.0 if s == "A" else 0.0, max_steps=4)
    times = [p[0] for p in path]
    states = [p[1] for p in path]
    assert states == ["A", "B", "A", "B", "A"]
    expect = [0.0]
    for (u1, u2), rate in zip(u, [1.0, 3.0, 1.0, 3.0]):
        expect.append(expect[-1] - math.log(u2) / rate)
    assert times == pytest.approx(expect, abs=1e-12)
    assert times[1:] == pytest.approx([0.693147, 0.728268, 1.932241, 2.102515], abs=1e-6)
    in_a = (times[1] - times[0]) + (times[3] - times[2])
    assert avg == pytest.approx(in_a / times[-1], abs=1e-12)


def test_two_state_time_fraction():
    rng = random.Random(1)
    k_ab, k_ba = 1.0, 3.0
    _, t, path, frac = kinetic_monte_carlo(
        "A", two_state(k_ab, k_ba), 2500.0, rng,
        observe=lambda s: 1.0 if s == "A" else 0.0)
    assert t == 2500.0
    assert len(path) < 10000
    assert frac == pytest.approx(k_ba / (k_ab + k_ba), abs=0.02)


def test_residence_time_and_choice():
    rng = random.Random(2)
    rates = [1.0, 2.0, 3.0]
    n = 6000
    waits, counts = [], [0, 0, 0]
    for _ in range(n):
        _, _, path, _ = kinetic_monte_carlo(
            0, lambda s: [(k, j + 1) for j, k in enumerate(rates)] if s == 0 else [],
            1e9, rng)
        waits.append(path[1][0])
        counts[path[1][1] - 1] += 1
    mean = sum(waits) / n
    var = sum((w - mean) ** 2 for w in waits) / (n - 1)
    total = sum(rates)
    # Exponential law with rate 6: mean 1/6, standard deviation 1/6.
    assert abs(mean - 1 / total) < 4 * (1 / total) / math.sqrt(n)
    assert var == pytest.approx(1 / total ** 2, rel=0.1)
    for j, k in enumerate(rates):
        p = k / total
        assert abs(counts[j] / n - p) < 4 * math.sqrt(p * (1 - p) / n)


def test_random_walk_mean_square_displacement():
    rng = random.Random(3)
    k, t_end, walkers = 1.0, 5.0, 500
    hop = lambda x: [(k, x - 1), (k, x + 1)]
    sq = [kinetic_monte_carlo(0, hop, t_end, rng)[0] ** 2 for _ in range(walkers)]
    mean = sum(sq) / walkers
    # <x^2> = 2 k t; x is the difference of two Poisson(5) counts, so Var(x^2) = 210.
    assert abs(mean - 2 * k * t_end) < 4 * math.sqrt(210 / walkers)


def expm_times_vector(q, p0, t, terms=60):
    """p0 exp(Q t) by the Taylor series, for a small generator Q and a small t."""
    n = len(p0)
    out = list(p0)
    term = list(p0)
    for m in range(1, terms):
        term = [sum(term[i] * q[i][j] for i in range(n)) * t / m for j in range(n)]
        out = [a + b for a, b in zip(out, term)]
    return out


def test_three_state_chain_against_master_equation():
    # 0 <-> 1 <-> 2 with rates 2, 1 (from 1 to 0 and to 2) and 0.5 back.
    k = {(0, 1): 2.0, (1, 0): 1.0, (1, 2): 1.0, (2, 1): 0.5}
    events = lambda x: [(r, j) for (i, j), r in k.items() if i == x]
    q = [[0.0] * 3 for _ in range(3)]
    for (i, j), r in k.items():
        q[i][j] += r
        q[i][i] -= r
    t_end = 0.7
    p_exact = expm_times_vector(q, [1.0, 0.0, 0.0], t_end)
    assert sum(p_exact) == pytest.approx(1.0, abs=1e-12)
    rng = random.Random(4)
    n = 3000
    counts = [0, 0, 0]
    for _ in range(n):
        counts[kinetic_monte_carlo(0, events, t_end, rng)[0]] += 1
    for j in range(3):
        p = p_exact[j]
        assert abs(counts[j] / n - p) < 4 * math.sqrt(p * (1 - p) / n)


def test_absorbing_state_stops():
    x, t, path, _ = kinetic_monte_carlo("A", lambda s: [(1.0, "B")] if s == "A" else [],
                                        100.0, random.Random(5))
    assert x == "B" and len(path) == 2 and t == path[-1][0] < 100.0


def test_arrhenius_rate():
    kT = 8.617333262e-5 * 300.0
    assert arrhenius_rate(1e13, 0.5, kT) == pytest.approx(1e13 * math.exp(-0.5 / kT))
    assert arrhenius_rate(1e13, 0.5, kT) == pytest.approx(3.98e4, rel=0.01)

History

Bortz, Kalos and Lebowitz published the n-fold way for Ising spin systems in 1975. It removes the rejected moves of the Metropolis method at low temperature by grouping the spins into classes by their flip rate. Gillespie published the same direct method for coupled chemical reactions in 1976. Fichthorn and Weinberg discussed in 1991 the conditions under which the simulated time is a physical time. Voter's 2007 chapter gives the method as it is used in materials science, with rates from transition state theory.

References

  1. A. B. Bortz, M. H. Kalos and J. L. Lebowitz, A new algorithm for Monte Carlo simulation of Ising spin systems, Journal of Computational Physics 17(1), 1975, 10-18, the n-fold way, with classes of spins by their flip rate and the time per step
  2. Arthur F. Voter, Introduction to the kinetic Monte Carlo method, in Radiation Effects in Solids, NATO Science Series, Springer, 2007, 1-23, the residence time algorithm, the exponential waiting time and the rates from transition state theory
  3. Kristen A. Fichthorn and W. H. Weinberg, Theoretical foundations of dynamical Monte Carlo simulations, Journal of Chemical Physics 95(2), 1991, 1090-1096, the conditions under which the Monte Carlo time is a physical time (a Poisson process for each event)
  4. Daniel T. Gillespie, A general method for numerically simulating the stochastic time evolution of coupled chemical reactions, Journal of Computational Physics 22(4), 1976, 403-434, the direct method, the same algorithm for well-mixed chemical reactions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example