Skip to content

Commit 75c975b

Browse files
Emanuel Gullclaude
andcommitted
Rewrite MC-01a and MC-01b tutorials for accuracy and style
MC-01a: fix code block languages (parameter files and shell commands were incorrectly tagged as Python); fix task file count (said 1-5, should be 1-6); remove outdated Internet Explorer reference; expand the cluster updates section to include full code and a physical explanation of critical slowing down; add an explanatory intro on autocorrelation times and binning. MC-01b: remove broken "Read here" placeholder; rewrite the terse "The headers:" code fragments into proper prose-plus-code sections; expand the convergence section to explain what checkConvergence does and when to act on its output; add a Questions section. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent f81ff6b commit 75c975b

2 files changed

Lines changed: 136 additions & 158 deletions

File tree

content/en/tutorials/mcs/mc01a.md

Lines changed: 80 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,25 @@ toc: true
66
weight: 2
77
---
88

9-
The first tutorial is an introduction to an important topic in Monte Carlo simulations: autocorrelation time. The input files for this tutorial are available in your ALPS distribution, in a directory called `mc-01-autocorrelations`.
9+
In a Monte Carlo simulation, successive configurations are generated by a random walk through configuration space, so consecutive measurements are statistically correlated.
10+
The autocorrelation time $\tau$ is the number of Monte Carlo steps over which this correlation decays.
11+
Because only one independent sample is obtained per $2\tau$ steps, a naive error estimate that treats all measurements as independent underestimates the true statistical error — sometimes severely.
12+
This tutorial illustrates the problem using local updates on the 2D Ising model at its critical temperature, and shows how cluster updates cure it.
1013

1114
## Local updates
1215

13-
We will start with local updates in an Ising model. We will simulate an Ising model on finite square lattices (L=2, 4, ..., 48) at the critical temperature $T_C=2.269186$ using **local** updates.
14-
This tutorial can be run either on the command line or in Python. We recommend the Python version on your local machine, and the command line version for large simulations on clusters.
16+
We simulate the Ising model on finite square lattices ($L = 2, 4, \ldots, 48$) at the critical temperature $T_c = 2.269186$ using **local** (single-spin-flip) updates.
1517

16-
## Setting up and running the simulation on the command line
18+
#### Setting up and running on the command line
1719

18-
To set up and run the simulation on the command line, we first create a parameter file that specifies the parameters of the simulation(s). The <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/parm1a" download>downloadable file</a> will be titled `parm1a` and its contents shall be:
20+
The parameter file <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/parm1a" download>`parm1a`</a> specifies six simulation tasks — one for each system size — sharing all other parameters:
1921

20-
```Python
22+
```
2123
LATTICE="square lattice"
2224
T=2.269186
2325
J=1
2426
THERMALIZATION=10000
25-
SWEEPS=50000
27+
SWEEPS=50000
2628
UPDATE="local"
2729
MODEL="Ising"
2830
{L=2;}
@@ -33,170 +35,148 @@ MODEL="Ising"
3335
{L=48;}
3436
```
3537

36-
This actually specifies six simulation tasks in one simulation job, all tasks having identical parameters except for the lattice length `L`.
38+
Convert the parameter file to XML and run:
3739

38-
ALPS expects one *job file* to specify the job as a whole and a *task file* for each simulation task within it, all in XML format. So in order to run the simulation, we first need to convert this parameter file. ALPS provides a simple tool to do this: We can just run
39-
40-
```Python
41-
parameter2xml parm1a
4240
```
43-
44-
in the folder of the parameter file. This will generate six task files (one for each length L) named `parm1a.task1.in.xml` through `parm1a.task6.in.xml` and a job description file `parm1a.in.xml`. We can open the job file with an XML browser to check the status of our simulation once we have started it.
45-
46-
The simulation can be started on a single processor by running
47-
48-
```Python
41+
parameter2xml parm1a
4942
spinmc --Tmin 10 --write-xml parm1a.in.xml
5043
```
5144

52-
or on multiple processors (in our example 8) using MPI by
53-
54-
```Python
55-
mpirun -np 8 spinmc --mpi --Tmin 10 --write-xml parm1a.in.xml
56-
```
57-
58-
(In the following examples we will refer to the single processor commands only.) By setting the argument `--Tmin 10`, we tell the scheduler to check if the simulation is finished every 10 seconds initially. (The time is then dynamically adapted by the scheduler according to the needs of the simulation.)
45+
`--Tmin 10` tells the scheduler to check for completion every 10 seconds initially (it adapts dynamically thereafter).
46+
`--write-xml` stores the results in XML output files alongside the binary HDF5 files; omit it for faster I/O on large runs.
5947

60-
The progress of a simulation is saved in the XML output file as the simulation is run. If a simulation is halted, such as due to pressing Ctrl-C or reaching the CPU time limit, it may be continued by starting the simulation with the XML output file instead of the input job file. Since our input job file was named `parm1a.in.xml`, the output file will be named `parm1a.out.xml` and we may restart the simulation by running
48+
If the simulation is interrupted it can be resumed by passing the output file instead:
6149

62-
```Python
50+
```
6351
spinmc --Tmin 10 --write-xml parm1a.out.xml
6452
```
6553

66-
The option "--write-xml" tells the simulation to store the results of each simulation also in an XML output file (`parm1a.task\[1-5\].out.xml`) which you can open from the job description file parm1a.out.xml using your XML browser or alternatively by converting the output to a text file using one of the following commands:
54+
To inspect results as plain text:
6755

68-
```Python
69-
firefox ./parm1a.out.xml
70-
convert2text parm1a.out.xml
7156
```
72-
73-
The results of a single task stored, for example, in `parm1a.task1.out.xml`, can be displayed by using either of the following commands:
74-
75-
- Linux: `firefox ./parm1a.task1.out.xml`
76-
- MacOS: `open -a safari parm1a.task1.out.xml`
77-
- Windows: `"C:\Program Files\Internet Explorer\iexplore.exe" parm1a.task1.out.xml`
78-
- Text output on Linux or MacOS: `convert2text parm1a.task1.out.xml`
79-
80-
Note that writing XML files can be very slow if you perform many measurements, and it is then better to work with the binary results in the HDF5 files.
81-
82-
To obtain more detailed information on the simulation runs, such as to check the convergence of errors, we can convert the run files of the tasks (`parm1a.task\[1-6\].out.run1`) into XML files by typing
83-
84-
```Python
85-
convert2xml parm1a.task*.out.run1
57+
convert2text parm1a.out.xml
8658
```
8759

88-
which will generate the XML output files `parm1a.task\[1-6\].out.run1.xml` which we may open or convert to text just like the output XML files.
89-
90-
Look at all six tasks and, by studying the binning analysis in the files `parm1a.task\[1-6\].out.run1.xml`, observe that for large lattices the errors no longer converge. To create plots, we recommend using the Python tools described below.
91-
92-
## Setting up and running the simulation in Python
93-
94-
The `pyalps` package is a wrapper for ALPS: All it does is call the commands described in the previous section as if they were run in a terminal. It is superior for plotting because the output of the simulation can be read directly into a Python data structure and accessed by `matplotlib`, and it also comes with a wrapper `pyalps.plot` for certain matplotlib functions to neatly plot data generated by `pyalps`.
60+
#### Setting up and running in Python
9561

96-
To set up and run the simulation in Python, we create a script named <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/tutorial1a.py" download>`tutorial1a.py`</a>. The first part of this script must import the required modules and prepare the input job and task files. Instead of writing a parameter file and using `convert2xml`, we store a list containing each task's parameters as a dictionary, like so:
62+
The script <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/tutorial1a.py" download>`tutorial1a.py`</a> runs the same simulation from Python.
63+
Import the required modules and build the parameter list:
9764

9865
```Python
9966
import pyalps
10067
import matplotlib.pyplot as plt
10168
import pyalps.plot
10269

10370
parms = []
104-
for l in [2,4,8,16,32,48]:
71+
for l in [2, 4, 8, 16, 32, 48]:
10572
parms.append(
10673
{
10774
'LATTICE' : "square lattice",
10875
'T' : 2.269186,
109-
'J' : 1 ,
76+
'J' : 1,
11077
'THERMALIZATION' : 10000,
11178
'SWEEPS' : 50000,
11279
'UPDATE' : "local",
11380
'MODEL' : "Ising",
11481
'L' : l
11582
}
11683
)
117-
```
118-
119-
and convert this into an XML job file with the function
120-
121-
```Python
122-
input_file = pyalps.writeInputFiles('parm1a',parms)
123-
```
124-
125-
The input_file variable may be used as an input for `pyalps.runApplication` as shown below:
12684

127-
```Python
128-
pyalps.runApplication('spinmc',input_file,Tmin=5,writexml=True)
85+
input_file = pyalps.writeInputFiles('parm1a', parms)
86+
pyalps.runApplication('spinmc', input_file, Tmin=5, writexml=True)
12987
```
13088

131-
`spinmc` is the name of the terminal command to be called. The option `writexml=True` tells ALPS to write XML files, `input_file` is the path to the XML job input file, and `Tmin=5` again tells ALPS to check every 5 seconds for completion of the simulation.
89+
#### Evaluating and plotting
13290

133-
We next load the binning analysis for the absolute value of the magnetization from the output files using `pyalps.loadBinningAnalysis`, and flatten the list of lists we get with `pyalps.flatten`:
91+
Load the binning analysis for the magnetization and label each dataset by system size:
13492

13593
```Python
136-
binning = pyalps.loadBinningAnalysis(pyalps.getResultFiles(prefix='parm1a'),'|Magnetization|')
94+
binning = pyalps.loadBinningAnalysis(pyalps.getResultFiles(prefix='parm1a'), '|Magnetization|')
13795
binning = pyalps.flatten(binning)
138-
```
13996

140-
We may give each data set a label which will be displayed in any graph specifying the lattice size:
141-
142-
```Python
14397
for dataset in binning:
144-
dataset.props['label'] = 'L='+str(dataset.props['L'])
145-
```
146-
147-
`pyalps.plot` functions will respect this. And finally we create a plot showing the binning analysis graphically:
98+
dataset.props['label'] = 'L=' + str(dataset.props['L'])
14899

149-
```Python
150100
plt.figure()
151-
plt.xlabel('binning level')
101+
plt.xlabel('Binning level')
152102
plt.ylabel('Error of |Magnetization|')
153103
pyalps.plot.plot(binning)
154104
plt.legend()
155105
plt.show()
156106
```
157107

158-
To make separate plots for each system size we make a loop over all data sets:
108+
A binning analysis groups measurements into blocks of increasing size and tracks how the estimated error changes.
109+
If measurements were independent the error would be constant across levels; if they are correlated the error grows with block size and only converges once blocks are larger than $2\tau$.
110+
111+
For separate plots per system size:
159112

160113
```Python
161114
for dataset in binning:
162115
plt.figure()
163-
plt.title('Binning analysis for L='+str(dataset.props['L']))
164-
plt.xlabel('binning level')
116+
plt.title('Binning analysis for L=' + str(dataset.props['L']))
117+
plt.xlabel('Binning level')
165118
plt.ylabel('Error of |Magnetization|')
166119
pyalps.plot.plot(dataset)
167-
120+
168121
plt.show()
169122
```
170123

171-
From the produced figure below, you can clearly see that the errors do not converge for large system sizes.
124+
For small system sizes the errors converge quickly, but for the largest sizes the error is still growing at the highest binning level, showing that the simulation has not produced enough independent samples.
172125

173126
![](/figs/mcs01binlocal.png)
174127

175128
## Cluster updates
176129

177-
We next repeat the simulations, but using cluster updates. We want to change three parameters:
130+
Near a critical point, local updates are particularly inefficient: the autocorrelation time $\tau$ grows as $\tau \sim L^z$ with a large dynamical exponent $z \approx 2$, a phenomenon called *critical slowing down*.
131+
Cluster algorithms, such as the Wolff and Swendsen–Wang updates, flip entire correlated clusters of spins at once and reduce $z$ to near zero, drastically shortening the autocorrelation time.
178132

179-
| **Name** | |
180-
| :------- | :------- |
181-
| THERMALIZATION | 1000 |
182-
| SWEEPS | 100000 |
183-
| UPDATE | "cluster" |
133+
Repeat the simulation with the following three parameter changes:
184134

185-
To run the simulations we follow the same procedure as above, using either
186-
- <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/parm1b" download>`parm1b`</a> for the command-line input file, or
187-
- <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/tutorial1b.py" download>`tutorial1b.py`</a> for the Python script.
135+
| Parameter | Value |
136+
| :--- | :--- |
137+
| `THERMALIZATION` | 1000 |
138+
| `SWEEPS` | 100000 |
139+
| `UPDATE` | `"cluster"` |
188140

189-
You will get curves looking like the ones below. Now the errors have converged and can be trusted.
141+
#### Setting up and running on the command line
190142

191-
![](/figs/mcs01bincluster.png)
143+
Download <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/parm1b" download>`parm1b`</a> and run:
192144

193-
## Questions
145+
```
146+
parameter2xml parm1b
147+
spinmc --Tmin 10 --write-xml parm1b.in.xml
148+
```
149+
150+
#### Setting up and running in Python
194151

195-
- Are the errors converged? (To check this convert the run files as described above.)
196-
- Why do longer autocorrelation times lead to slower error convergence?
197-
- On what system parameters do the autocorrelation times depend on? Check by changing parameters in the input file.
198-
- Can you explain why cluster updates are more efficient than local updates?
152+
The script <a href="https://github.com/ALPSim/ALPS/blob/master/tutorials/mc-01-autocorrelations/tutorial1b.py" download>`tutorial1b.py`</a> adapts `tutorial1a.py`: change the prefix to `parm1b`, set `'UPDATE': "cluster"`, reduce `THERMALIZATION` to 1000, and increase `SWEEPS` to 100000.
199153

154+
#### Evaluating and plotting
200155

156+
Load and plot the binning analysis as before, replacing the prefix with `parm1b`:
201157

158+
```Python
159+
binning = pyalps.loadBinningAnalysis(pyalps.getResultFiles(prefix='parm1b'), '|Magnetization|')
160+
binning = pyalps.flatten(binning)
161+
162+
for dataset in binning:
163+
dataset.props['label'] = 'L=' + str(dataset.props['L'])
164+
165+
plt.figure()
166+
plt.xlabel('Binning level')
167+
plt.ylabel('Error of |Magnetization|')
168+
pyalps.plot.plot(binning)
169+
plt.legend()
170+
plt.show()
171+
```
172+
173+
With cluster updates the errors converge at all system sizes, confirming that the autocorrelation time is now short enough to trust the error estimates.
174+
175+
![](/figs/mcs01bincluster.png)
176+
177+
## Questions
202178

179+
- At which system sizes do the errors fail to converge with local updates? Why does the problem worsen with $L$?
180+
- Why do longer autocorrelation times lead to underestimated statistical errors?
181+
- With cluster updates, does the binning analysis converge at all system sizes? How many more sweeps would be needed to achieve the same result with local updates for $L = 48$?
182+
- Try changing `T` away from the critical temperature. How does the autocorrelation time change, and why?

0 commit comments

Comments
 (0)