MC-01c The Steady-State Test
A Monte Carlo simulation produces a Markov chain of configurations, and only after the chain has forgotten its initial state do its measurements sample the equilibrium distribution.
MC-01b showed how to inspect the time series of an observable for this, and introduced pyalps.checkSteadyState, which automates the inspection with a statistical test.
This tutorial looks at that test in detail: what it computes, how its cutoff follows from the standard normal distribution , how often it passes when nothing is wrong, and which kinds of non-equilibrium it can and cannot detect.
The test is applied to two applications: classical Monte Carlo of the 2D Ising model with spinmc, and quantum Monte Carlo of the spin-1/2 Heisenberg antiferromagnet with the directed-loop stochastic series expansion code dirloop_sse.
In both, the main finding is the same: the test detects a drift that lasts a large part of the run, reacts only weakly to a large but short transient at the start, and raises false alarms more often than its confidence level suggests whenever the time series is autocorrelated.
The steady-state test
The test statistic
ALPS stores the time series of each observable as at most about 128 bins of consecutive measurements (see How the time series is stored in MC-01b).
checkSteadyState takes these bin values and fits a straight line through the points , , by least squares.
The fitted slope is
If the series has no drift and its values are independent with standard deviation , the slope scatters around zero with standard error . The test estimates by the sample standard deviation of the series, so the slope error is
and the test statistic is the slope in units of its error,
Under these assumptions the signed ratio is approximately a standard normal variable (mean 0, standard deviation 1). The test passes if for a cutoff that depends on the confidence level you choose.
Two details matter later. First, is the standard deviation of the series itself, not of the residuals from the fitted line, so a strong drift also raises and caps at about . Second, the slope error assumes that the bins are independent; MC-01a showed that consecutive measurements are not, and neither are consecutive bins unless each bin is much longer than the autocorrelation time.
The standard normal distribution
is the cumulative distribution function of the standard normal distribution: the probability that is at most ,
It rises from 0 to 1, with , and , and it is symmetric: .
Its inverse , the quantile function, returns the at which reaches a given probability .
In SciPy, is scipy.stats.norm.cdf and is scipy.stats.norm.ppf.
The cutoff
The confidenceInterval argument of checkSteadyState is the probability that a series without drift passes.
The acceptance region is symmetric, so
The probability outside the region is split equally between the two tails, each, which is where comes from. The default gives : the test passes if the slope is within one standard error of zero. A larger widens the region, so it makes the test more lenient, not stricter.
pyalps 3.0.0 and earlier computed the cutoff as instead, which puts in each tail: it is the cutoff for the complementary level . This makes the default test pass a series without drift only 32% of the time, and a larger makes it stricter. The ALPS master branch uses .
The script tutorial1c_test.py computes the test by hand, without ALPS.
Its two functions reproduce checkSteadyState:
import numpy as np
from scipy.stats import norm
def steady_state_z(ts):
"""Return the fitted slope, its standard error and z = |slope| / error."""
ts = np.asarray(ts, dtype=float)
N = len(ts)
t = np.arange(1, N + 1)
slope = np.polyfit(t, ts, 1)[0]
error = np.std(ts, ddof=1) * np.sqrt(12. / (N * (N**2 - 1)))
if error == 0.:
return slope, error, 0. # a constant series, as in pyalps.checkSteadyState
return slope, error, abs(slope) / error
def cutoff(c):
"""z0 such that a standard normal Z satisfies P(|Z| < z0) = c."""
return norm.ppf((1. + c) / 2.)The script then prints for common confidence levels, together with the fraction of series without drift that pass, :
c z0 pass rate z0 (3.0.0) pass rate (3.0.0)
0.6827 1.000 0.683 0.409 0.317
0.9000 1.645 0.900 0.126 0.100
0.9500 1.960 0.950 0.063 0.050
0.9900 2.576 0.990 0.013 0.010and plots the acceptance region on the standard normal density:

Autocorrelated series
The pass rate holds only if the points are independent.
To see what autocorrelation does, tutorial1c_test.py applies the test to 10000 synthetic series of points without any drift, generated by .
Such a series has the integrated autocorrelation time in units of points, as defined in MC-01a: points hold about independent samples, and for independent points.
from scipy.signal import lfilter
rng = np.random.default_rng(2026)
N, samples = 128, 10000
z0 = cutoff(0.6827)
for a in [0., 0.5, 0.8, 0.95]:
noise = rng.normal(size=(samples, N))
noise[:, 0] /= np.sqrt(1 - a**2)
series = lfilter([1.], [1., -a], noise, axis=1)
z = np.array([steady_state_z(s)[2] for s in series])
tau = a / (1 - a)
print('%7.0f %30.3f %5.2f %15.2f'
% (tau, np.mean(z < z0), np.sqrt(np.mean(z**2)), np.sqrt(1 + 2 * tau))) tau fraction passing at c = 0.6827 rms z sqrt(1 + 2 tau) (N = 128 points)
0 0.685 1.00 1.00
1 0.441 1.70 1.73
4 0.250 2.86 3.00
19 0.124 5.02 6.24Independent points () pass at the nominal rate. With correlated points, the slope scatters more than assumes, and a series without any drift fails most of the time. The rms value of grows roughly as while is much smaller than ; at it is 5.0 rather than 6.2. For ALPS time series, here is the autocorrelation time measured in bins: it is small when each bin is much longer than the autocorrelation time of the measurements, and of order one or larger when it is not.
A transient in the first bin
A transient that lasts less than one bin shows up as a single outlier at the start of the time series.
tutorial1c_test.py adds an outlier of size , in units of the noise, to the first point of series without drift:
for A in [5, 10, 20, 40, 100, 1e4]:
series = rng.normal(size=(samples, N))
series[:, 0] += A
z = np.array([steady_state_z(s)[2] for s in series])
print('%7g %8.2f %30.3f %11.3f'
% (A, np.median(z), np.mean(z > z0), np.mean(z > cutoff(0.95))))outlier in the first point only; limit of z: sqrt(3 (N-1) / (N+1)) = 1.719
A median z fraction failing at c = 0.6827 at c = 0.95
5 0.82 0.409 0.088
10 1.15 0.579 0.142
20 1.51 0.847 0.174
40 1.66 0.992 0.132
100 1.71 1.000 0.010
10000 1.72 1.000 0.000
transient 40, 20, 10 in the first three points: median z = 2.54, fraction failing at c = 0.95: 0.994As grows, the outlier dominates both the slope and the standard deviation that the slope is divided by, and approaches , whatever the size of . So a transient confined to the first bin can never by itself fail the test at , where . A moderate outlier still adds to the noise and occasionally pushes above 1.96, most often near ; a larger one fails less and less often. A transient spread over a few bins is different: 40, 20 and 10 noise units in the first three points give a median of 2.5 and fail almost always. Because the bins grow with the length of the run (see MC-01b), a longer run squeezes the same transient into fewer bins and makes it harder to detect.
Models
Classical Monte Carlo is applied to the ferromagnetic Ising model on the square lattice,
introduced by E. Ising, Z. Phys. 31, 253 (1925). Its critical temperature is known exactly from L. Onsager, Phys. Rev. 65, 117 (1944). At the autocorrelation time of local updates is long, which makes it a demanding case for any equilibration test.
Quantum Monte Carlo is applied to the spin-1/2 Heisenberg antiferromagnet on the square lattice,
(W. Heisenberg, Z. Phys. 49, 619 (1928)), simulated with the directed-loop algorithm in the stochastic series expansion of O. F. Syljuåsen and A. W. Sandvik, Phys. Rev. E 66, 046701 (2002). The observable is the energy.
Parameters
| Parameter | Meaning | spinmc drift run | spinmc equilibrated runs | dirloop_sse runs without thermalization | dirloop_sse equilibrated runs |
|---|---|---|---|---|---|
LATTICE | lattice | square lattice | square lattice | square lattice | square lattice |
MODEL | Hamiltonian | Ising | Ising | spin | spin |
local_S | spin per site | – | – | 1/2 | 1/2 |
L | linear lattice size ( sites, periodic) | 128 | 48 | 32 | 32 |
J | coupling | 1 (ferromagnetic) | 1 | 1 (antiferromagnetic) | 1 |
T | temperature | 2.269186 () | 2.269186 | 0.25 | 0.25 |
UPDATE | local or cluster updates | local | local and cluster | – | – |
THERMALIZATION | steps discarded before measuring | 0 | 10000 | 0 | 1000 |
INITIAL_CUTOFF | initial operator-string length (SSE) | – | – | 40000 | – |
SWEEPS | measurement steps | 2000 | 20000 | 2000 | 4000 |
SEED | random-number seed of each run | 1–20 | 1001–1100 | 1–10 | 1001–1100 |
| number of runs | independent runs with these parameters | 20 | 100 per update | 10 | 100 |
With local updates a step is a sweep over all sites; with cluster updates SWEEPS counts single Wolff cluster flips (see MC-01b).
Each run has its own SEED, so that the scripts reproduce the numbers on this page; with other seeds the individual numbers change within the spread discussed below.
Parameter files
The command-line runs use two parameter files.
parm1c_drift starts a large Ising lattice at without thermalization, with the seed of the run plotted below:
LATTICE="square lattice"
MODEL="Ising"
T=2.269186
J=1
UPDATE="local"
THERMALIZATION=0
SWEEPS=2000
SEED=5
{L=128;}parm1c_sse starts the Heisenberg antiferromagnet without thermalization, again with the seed of the run plotted below:
LATTICE="square lattice"
MODEL="spin"
local_S=1/2
T=0.25
J=1
THERMALIZATION=0
INITIAL_CUTOFF=40000
SWEEPS=2000
SEED=1
{L=32;}The repeated runs are set up in the Python scripts below, which build the same parameters in a loop.
Lattice
Both models live on the periodic square lattice, with the coupling on every nearest-neighbor bond:
: : : :
--o---J---o---J---o---J---o---J--
| | | |
J J J J
| | | |
--o---J---o---J---o---J---o---J-- L x L sites, periodic in both directions
| | | |
J J J J
| | | |
--o---J---o---J---o---J---o---J--
: : : :The square lattice gives the Ising model a finite-temperature transition at an exactly known , and it is bipartite, so the Heisenberg antiferromagnet has no sign problem in quantum Monte Carlo.
It is the built-in square lattice of the ALPS lattice library.
Method choice
spinmc offers local Metropolis updates and Wolff cluster updates.
At the autocorrelation time of local updates grows with the system size roughly as (critical slowing down), while cluster updates decorrelate within a few cluster flips (see MC-01a).
Comparing the two shows how the autocorrelation of the time series affects the test.
A run of 30000 steps takes a second or two.
For the quantum model, the Hilbert space of spins has states, far beyond exact diagonalization, while dirloop_sse samples it at in a few seconds per run.
The directed-loop code has no local and cluster variants to compare, but its energy decorrelates quickly, and its operator string starts empty and has to grow to its equilibrium length.
During thermalization the code also adjusts the cutoff of the operator string; without thermalization it stops with “nnonzero reached the maximum value” unless INITIAL_CUTOFF is set large enough.
Running the simulations
On the command line, convert the parameter files to XML and run the two applications:
parameter2xml parm1c_drift
spinmc --Tmin 1 --write-xml parm1c_drift.in.xml
parameter2xml parm1c_sse
dirloop_sse --Tmin 1 --write-xml parm1c_sse.in.xmlThen apply the test to the results in Python (with pyalps 3.0.0, see the note at the end first):
import pyalps
for prefix, observable in [('parm1c_drift', '|Magnetization|'), ('parm1c_sse', 'Energy')]:
data = pyalps.loadMeasurements(pyalps.getResultFiles(prefix=prefix), observable)
for d in pyalps.checkSteadyState(data):
print(prefix, d.props['checkSteadyState'])The three scripts run everything, including the repeated runs, and print the numbers and plots shown below:
python tutorial1c_test.py
python tutorial1c_spinmc.py
python tutorial1c_sse.pyDownload tutorial1c_spinmc.py and tutorial1c_sse.py next to tutorial1c_test.py.
Each defines steady_state_z and cutoff as above, so that the numbers do not depend on the pyalps version (see the note at the end).
On our laptop (Apple M5) tutorial1c_spinmc.py took 7 minutes and tutorial1c_sse.py 3 minutes; on slower machines tutorial1c_spinmc.py can take half an hour.
Results: classical Monte Carlo
A run that is still drifting
tutorial1c_spinmc.py first runs the parameters of parm1c_drift 20 times, with seeds 1 to 20.
It computes the test by hand for each run, and for the run with the median also with pyalps.checkSteadyState; result_files returns the result files in the order of the parameter list:
# the scheduler changes SEED after starting a run, so take it from parms
files = result_files('parm1c_drift')
seeds = [p['SEED'] for p in parms]
series = [np.array(pyalps.loadTimeSeries(f, '|Magnetization|')) for f in files]
z = np.array([steady_state_z(ts)[2] for ts in series])
z0 = cutoff(0.6827)
print('drift runs, %d bins each: z =' % len(series[0]), ' '.join('%.1f' % v for v in sorted(z)))
print('fraction failing at c = 0.6827 (z0 = %.2f): %.2f' % (z0, np.mean(z > z0)))
# the run with the median z, checked by hand and with pyalps.checkSteadyState
i = np.argsort(z)[len(z) // 2]
print('run with SEED = %d: z = %.2f, passes: %s' % (seeds[i], z[i], z[i] < z0))
data = pyalps.loadMeasurements([files[i]], '|Magnetization|')
try:
for d in pyalps.checkSteadyState(data):
s = d.props['checkSteadyState']
print('pyalps.checkSteadyState: z = %.2f, z0 = %.2f, passes: %s'
% (s['statistics']['z'], s['statistics']['z0'], s['value']))
except AttributeError as exc:
# pyalps 3.0.0 calls scipy.linspace, which current SciPy no longer has
print('pyalps.checkSteadyState failed with this pyalps and SciPy:', exc)In our run this printed:
drift runs, 124 bins each: z = 0.1 0.2 0.4 1.8 2.1 3.1 3.7 4.0 5.5 6.0 6.2 6.9 7.4 7.6 7.7 8.5 8.7 8.7 9.0 10.5
fraction failing at c = 0.6827 (z0 = 1.00): 0.85
run with SEED = 5: z = 6.20, passes: False
pyalps.checkSteadyState: z = 6.20, z0 = 1.00, passes: FalseThe hand-computed and agree with the library’s. With pyalps 3.0.0 the library prints instead (see the note at the end), and the run fails as well.

spinmc starts with all spins up.
In the run plotted here, the magnetization averages 0.85 over the first bin of 16 sweeps and falls to about 0.73 within a few dozen sweeps.
After that it keeps wandering slowly between about 0.58 and 0.76: at the autocorrelation time of local updates on a lattice is far longer than this run.
On the time scale of these runs, the magnetization is not in a steady state, whether one calls the slow wandering the end of the initial relaxation or critical slowing down, and 17 of the 20 runs fail.
The three that pass, with = 0.1, 0.2 and 0.4, are runs in which the slow wandering happens to end about where it started, so that the fitted line is flat.
The test sees only the net linear trend, so a single run can pass although it is far from equilibrium.
Many equilibrated runs
Next the script repeats an equilibrated run, with 10000 steps of thermalization, 100 times each with local and with cluster updates, and records how often the test passes:
NRUNS = 100
c = 0.6827
for update in ['local', 'cluster']:
parms = [{
'LATTICE' : "square lattice",
'MODEL' : "Ising",
'L' : 48,
'J' : 1.,
'T' : 2.269186,
'UPDATE' : update,
'THERMALIZATION' : 10000,
'SWEEPS' : 20000,
'SEED' : seed,
} for seed in range(1001, NRUNS + 1001)]
prefix = 'parm1c_' + update
input_file = pyalps.writeInputFiles(prefix, parms)
pyalps.runApplication('spinmc', input_file, Tmin=1, writexml=True)
z = np.array([steady_state_z(pyalps.loadTimeSeries(f, '|Magnetization|'))[2]
for f in pyalps.getResultFiles(prefix=prefix)])
print('%-7s updates: %d runs, fraction passing at c = %g: %.2f (expected %.2f)'
% (update, len(z), c, np.mean(z < cutoff(c)), c))local updates: 100 runs, fraction passing at c = 0.6827: 0.40 (expected 0.68)
cluster updates: 100 runs, fraction passing at c = 0.6827: 0.62 (expected 0.68)| Update | Runs | Fraction passing at | Expected for independent bins |
|---|---|---|---|
| local | 100 | 0.40 | 0.68 |
| cluster | 100 | 0.62 | 0.68 |
With 100 runs the fractions carry a statistical uncertainty of about . The cluster-update runs pass at close to the nominal rate (0.62 against 0.68, about one standard deviation), and their values of follow the distribution of for a standard normal . The local-update runs fail more than half the time although every one of them is equilibrated: their distribution of has a long tail beyond 2.

The reason is the autocorrelation between bins. Each bin of a local-update run averages 256 sweeps, shorter than the integrated autocorrelation time of , which ALPS estimates at 300 to 360 sweeps for this lattice (four runs of 400000 sweeps). Consecutive bins are therefore correlated, with a mean lag-1 correlation of 0.60, and the test sees slow fluctuations as drift. Cluster updates decorrelate within each bin (lag-1 correlation ), and the bins behave as independent samples.
Results: quantum Monte Carlo
A short transient at the start
tutorial1c_sse.py first repeats the parameters of parm1c_sse ten times, with seeds 1 to 10, and computes the test with and without the first bin of each time series:
NSTART = 10
parms = [{
'LATTICE' : "square lattice",
'MODEL' : "spin",
'local_S' : 0.5,
'L' : 32,
'J' : 1.,
'T' : 0.25,
'THERMALIZATION' : 0,
'INITIAL_CUTOFF' : 40000,
'SWEEPS' : 2000,
'SEED' : seed,
} for seed in range(1, NSTART + 1)]
input_file = pyalps.writeInputFiles('parm1c_start_sse', parms)
pyalps.runApplication('dirloop_sse', input_file, Tmin=1, writexml=True)
files = result_files('parm1c_start_sse')
series = [np.array(pyalps.loadTimeSeries(f, 'Energy')) for f in files]
z = np.array([steady_state_z(ts)[2] for ts in series])
z_rest = np.array([steady_state_z(ts[1:])[2] for ts in series])In our run this printed:
runs without thermalization: z = 1.9 1.8 1.8 2.0 2.2 1.9 1.9 1.8 1.7 1.4
the same runs without the first bin: z = 0.7 0.5 0.5 1.0 1.9 1.0 0.8 0.5 0.2 0.7
fraction passing at c = 0.6827 (z0 = 1.00): 0.0 with the first bin, 0.7 without
fraction passing at c = 0.95 (z0 = 1.96): 0.9 with the first bin, 1.0 without
first bin: 307 above the mean of the other bins, 37 times their scatter
The energy relaxes within the first one or two bins of 16 sweeps each, while the operator string grows from its empty initial state. In the run plotted here, the one with the median , the first bin lies 307 above the mean of the later bins, 37 times their scatter, and the second bin still lies about 30 above. Yet is only 1.9: the run fails the default test, where , but passes at . As shown in A transient in the first bin, the first bin alone cannot raise above about , however far it lies from the rest; the second bin and the noise make up the remainder. At all ten runs fail, so at the default level the test does flag the transient, but with between 1.4 and 2.2, far below most drift runs; at nine of the ten pass. This depends on the seed: with other seeds an occasional run passes even at the default level, when the noise in the rest of the series tilts the fitted line the other way. The test is built to detect a linear trend over the whole series; a transient confined to the first bins is better found by looking at the time series, or simply avoided by thermalizing for a few hundred sweeps.
Many equilibrated runs
With 1000 sweeps of thermalization, 100 repeated runs give:
100 equilibrated runs, fraction passing at c = 0.6827: 0.70 (expected 0.68)
Here each bin averages 32 sweeps, already longer than the autocorrelation time of the SSE energy, so the bins are nearly independent and the test passes at its nominal rate, as for the cluster-update Ising runs.
pyalps 3.0.0
pyalps 3.0.0 and earlier. checkSteadyState uses the cutoff , about 0.41 at the default, so it fails about two thirds of series without drift, and a larger confidenceInterval makes it stricter.
It also calls scipy.linspace, which newer SciPy releases no longer provide, so it stops with AttributeError: Module 'scipy' has no attribute 'linspace'.
Both are fixed in the ALPS master branch.
The scripts of this tutorial compute and themselves; if the one call of checkSteadyState in tutorial1c_spinmc.py fails, the script prints a message and goes on. To call checkSteadyState with pyalps 3.0.0, run the following before importing pyalps:
# pyalps 3.0.0 only: restore the NumPy aliases that newer SciPy releases removed
import scipy
import numpy as np
for name in dir(np):
if not hasattr(scipy, name):
setattr(scipy, name, getattr(np, name))The results on this page were produced with the ALPS master branch, in which a run takes exactly SWEEPS measurements. With pyalps 3.0.0 a run keeps measuring until the scheduler’s next check (see Tmin in MC-01b), so it can take more.
This changes the number of bins, not the behavior of the test.
Summary and outlook
checkSteadyState divides the fitted slope of the binned time series by its standard error for independent bins and passes if the ratio is below .
It catches a drift that lasts a large part of the run in most, but not all, runs.
It reacts only weakly to a transient in the first bin, which cannot push above about however large it is, while a transient spread over a few bins is detected.
A run that is stuck, or that drifts up and then down again, can pass, because the test sees only the net linear trend.
And it fails equilibrated runs far more often than when consecutive bins are correlated, as for local updates at .
Use it as a warning, together with the time series itself and the binning analysis of MC-01a, not as proof of equilibration.
- Rerun Part 2 of
tutorial1c_spinmc.pywith . How close are the pass fractions of local and cluster updates to 0.95? - Give the drift run 50000 sweeps of thermalization. Does it pass now? How does the answer depend on ?
- Add consecutive pairs of bins, dropping the last bin if their number is odd, before computing for the local-update runs. How does the pass fraction change, and why?
- Run the local-update experiment at for , 32 and 48. How does the false-alarm rate depend on , and how does that relate to the autocorrelation time of MC-01a?
- Show that for a single outlier in the first point, approaches as the outlier grows. Hint: , where is the correlation coefficient between and . How does the limit change if the outlier is in the middle of the series instead?
- Design a better test for a transient at the start of a run, for example by comparing the means of the first and last quarters of the time series. Does it detect the transient in the SSE runs?