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
- Model
- Real RAM
- Properties
- randomizedexactiterativerandomized
- Evidence
- Proof sketchCode in 1 languages
- 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 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 , a finite list of events with rates (in ) and target states . The process stays in for a random time, then jumps to , and the time and the choice obey
The output is a sample path of this process up to a time , and time averages along it. The probabilities of the states solve the master equation (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 with a barrier and a prefactor , often of order to . Here is the Boltzmann constant and the temperature.
The algorithm
KINETIC-MONTE-CARLO(x, EVENTS, t_end)- 1
t ← 0 - 2
while t < t_end do - 3
(k_1, y_1), ..., (k_M, y_M) ← EVENTS(x) - 4
R ← k_1 + ... + k_M ▷ total escape rate of x - 5
if R = 0 then return ▷ no event is possible - 6
draw u_1 uniform in [0, 1) and u_2 uniform in (0, 1] - 7
Δt ← -ln(u_2) / R ▷ exponential waiting time - 8
if t + Δt ≥ t_end then add f(x) (t_end - t) to the average, t ← t_end, return - 9
add f(x) Δt to the average ▷ x holds during the wait - 10
j ← the smallest index with k_1 + ... + k_j > u_1 R - 11
t ← t + Δt, x ← y_j - 12
record (t, x) - 13
return x, t, the path and the time average of f
Line L7 is inverse transform sampling of the exponential law with rate : if is uniform on , then . Line L10 picks event with probability , because is uniform on and the interval of event has length . Line L9 weights the observable with the time that the system stays in , 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 and B go to A with rate , in units of . Each state has one event, so line L10 always picks it, and only matters. Start in A at :
| step | state | 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 of , a fraction of 0.9023 after four events. The exact long-time fraction is , because the mean time in A is and the mean time in B is . A run with random.Random(1) gives these fractions:
| 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 in the number of events, as for any Monte Carlo integration.
A choice among three events. In a state with rates , the total is . With , line L10 looks for the first partial sum above : the sums are , so it picks event 2. The waiting time has mean and standard deviation , whatever event follows.
Why KMC is needed. An adatom hop with and eV at K, where eV, has the rate . The mean time between hops is microseconds, which is MD steps of 1 fs. KMC does one step per hop. At K the rate is : 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 has an independent exponential clock with rate , the first clock to ring rings at a time with the exponential law of rate , it is clock with probability , 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 , 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 in and in , independent of each other and of all earlier draws. A Markov jump process with rates and targets is the process that, in state , waits a time with , , then jumps to with probability , independently of , 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 .
Lemma 1 (the race of exponential clocks). Let be independent with , . Let and let be the index of the minimum. Then for all , with . So is exponential with rate , , and and are independent.
Proof. The index of the minimum is unique with probability 1, because the laws have densities. Condition on :
Summing over gives , and gives . The joint law is the product of the two marginal laws, so and are independent.
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 with , lines L6, L7 and L10 return and with .
Proof. Line L7 sets . For , holds if and only if , which has probability because is uniform on and . Line L10 picks the smallest with , where and . Because , this is the with . The variable is uniform on , so this has probability . The index depends only on and only on , so they are independent, and the joint law is the product.
Theorem (exact sampling). Let be the times recorded by line L12 and the states. Then the joint law of , up to the first with or , is the law of the jump times and states of the Markov jump process started at .
Proof. By induction on the number of steps. For both start at . Assume that the first pairs have the correct joint law. Given these pairs, step uses only the state and new random numbers, which are independent of the past. By Lemma 2, it draws the holding time and the next state with the law of the construction, given , 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 pairs have the correct joint law. If , the state is absorbing and the process stays in it, which is what line L5 returns. If , the next jump is after , so the process is in on , which is what line L8 uses.
The time average. Lines L8 and L9 add times the length of the part of that lies in . The sum is exactly for the piecewise constant path , and the result is this integral divided by . If the state space is finite and the process is irreducible, the ergodic theorem for Markov jump processes gives almost surely as , where 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 and the times in B are independent with mean . 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,
which is also from the balance . With and it is .
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, additions for line L4 and up to additions and comparisons for line L10, so apart from EVENTS. A run of events costs and extra space.
- Search. A binary tree of partial sums (a sum tree, or a Fenwick tree) gives line L10 in time, and a change of one rate in time.
- Update. On a lattice, one event changes only the rates of nearby sites, so the catalog update is per step at fixed range, and a step costs with the tree.
- Physical time. The mean step is . 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 ; it gives the same process with more steps when the rates differ much.
- Exact in time. The waiting times are exponential, not the mean . A fixed increment 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 random numbers per step.
- Time-dependent rates. If the rates change with time, for example in a temperature ramp, line L7 must solve 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 in , for example as with in . With , line L7 gives an infinite time.
- A fixed time increment. Writing 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 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.
# 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
- 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
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag SFQPD9 Edit this page History Report an error Markdown