PYTHON · STEP-BY-STEP LESSON

Ising and Potts: reproduce the lattice calculations

We write a small part, check it, and then add the next part.

Download the notebook Open in Colab

All Python notebook lessons

Exchange, flip, then four states

We begin by asking what changes in a move. Do two sites swap their states, or does one site change its state? Each strip follows that choice through the energy calculation and the acceptance decision.

Exchange two states · Flip one state · Extend to four states · Follow the code and results

We use a 4 × 4 periodic lattice and unit bond energy, with \(k_{\mathrm B}=1\). Temperature is dimensionless here. For an uphill proposal, we accept when the example draw \(r\) is smaller than \(P\). A move that lowers or preserves the energy is accepted. The sliders let us choose the draw to inspect this decision; the notebook generates random draws.

Exchange: two sites trade places

Two neighboring atoms, ringed in orange, trade places, and they tell the story themselves. A represents \(+1\) and B represents \(-1\). The first panel sets the price of every bond, so we can count the energy change ourselves. An atom smiles when at least three of its four neighbors are the kind it prefers, and frowns when at most one is. The faces are cartoon shorthand, not part of the calculation; the bubbles quote its real numbers. Change the rule, \(T\) and \(r\), and listen to what they say.

1

The rule

I hate B. An A–A or B–B bond is good: its energy is −1.

An A–B bond is bad: its energy is +1. Lower energy is better.

So we tend to gather in patches of our own kind.

2

We meet

I am A. Three of my four neighbors are A, like me.

I am B. Only two of mine are B.

3

A proposal

We have been picked. Shall we trade places?

Let us try. There will still be 8 of you and 8 of me.

4

After the swap

Oh! None of my neighbors is B now.

And only one of mine is A.

5

Count the bonds

Before

5 × (−1) + 2 × (+1) = −3

After

1 × (−1) + 6 × (+1) = +5

Count only the bonds that touch us. Bonds elsewhere did not change.

Before: 5 good and 2 bad. After: 1 good and 6 bad.

That is four more bad bonds, and trading a good bond for a bad one costs 2.

So the energy change is +5 − (−3) = +8.

Whole lattice: \(E_{\mathrm{before}}=\) −8; \(E_{\mathrm{proposed}}=\) 0; \(\Delta E=\) +8

6

Must we go back?

The energy went up by 8. Must we go back?

Not always. At T = 1.5 we may stay with probability P = 0.004828.

\[P=\min\{1,e^{-\Delta E/T}\}.\]

So we draw a number r between 0 and 1. If it lands in the blue part, we stay.

7

The draw decides

r = 0.050 is not smaller than P. We go back.

Home again. The next try starts from this same lattice.

8

Count us

Count us: 8 A.

And 8 B. Accepted or rejected, an exchange keeps these numbers fixed.

Flip a single spin instead, and that promise is gone.

See what a flip does

In symbols, \(E=-J\sum_{\langle ij\rangle}s_i s_j\), counting each bond once, with \(J=+1\) for “A hates B” and \(J=-1\) for “A likes B”. The supplied Ising notebook uses \(J=+1\) and single-spin flips, so this exchange is a comparison. Exchanging unlike states conserves total spin.

Flip: one site, two possible states

Now one spin, ringed in orange, tries to change by itself, while a neighbor watches. With two states, \(+1\) and \(-1\), it has only one alternative: flip. The faces and bond prices work as before, and the number of each state can change.

1

The rule

I am a + spin and I hate −. A bond between matching spins is good: its energy is −1.

A +− bond is bad: its energy is +1. Lower energy is better.

So spins tend to line up in domains.

2

I am picked

I am a + spin. Three of my four neighbors are +, like me.

I am the − spin just below. I am only watching.

3

A proposal

I have been picked. Nobody trades with me. I simply try flipping to −.

Now we are 8 + and 8 −. That would make 7 + and 9 −.

4

After the flip

Now I am −. One of my four neighbors is −.

That looks worse for you. Let us count.

5

Count the bonds

Before

3 × (−1) + 1 × (+1) = −2

After

1 × (−1) + 3 × (+1) = +2

Count only the bonds that touch me. Bonds elsewhere did not change.

Before: 3 good and 1 bad. After: 1 good and 3 bad.

That is two more bad bonds, and trading a good bond for a bad one costs 2.

So the energy change is +2 − (−2) = +4.

Whole lattice: \(E_{\mathrm{before}}=\) −8; \(E_{\mathrm{proposed}}=\) −4; \(\Delta E=\) +4

6

Must I flip back?

The energy went up by 4. Must I flip back?

Not always. At T = 1.5 you may stay − with probability P = 0.06948.

\[P=\min\{1,e^{-\Delta E/T}\}.\]

So I draw a number r between 0 and 1. If it lands in the blue part, I stay.

7

The draw decides

r = 0.050 is smaller than P. I stay −!

The energy went up and the flip was still accepted. Uphill steps are allowed.

8

Count us

Count us: 7 +.

And 9 −. That flip changed both numbers by one.

An accepted flip changes the counts. An exchange never does.

What if there are four states?

In symbols, \(\Delta E=2Js_i\sum_{j\text{ neighboring }i}s_j\), consistent with counting each bond once in \(E=-J\sum_{\langle ij\rangle}s_i s_j\). The supplied Ising notebook uses single-spin flips with \(J=+1\). A flip does not conserve total spin.

Four states: which label comes next?

We extend the picture to four orientation labels, A, B, C and D. The characters are now tiles, each carrying the label of its site. At a selected site, we propose copying one neighbor’s label. Here A becomes B. The letters name states; they are not numerical spin components.

1

The rule

A bond between matching labels is good: it costs 0.

A bond between different labels is bad: it costs 1. That bond is a piece of grain boundary.

So grains tend to grow and their boundaries tend to shrink.

2

We meet

I carry label A. Two of my four neighbors carry it too.

I carry B, right next door. C and D sit elsewhere on this lattice.

3

A proposal

We have been picked. May I copy your label?

Copy it. I keep B. Nothing is traded, so A drops to 3 sites and B rises to 4.

4

After the copy

Now I carry B. Only one of my four neighbors matches me.

You lost two A matches and gained one B match.

5

Count the bonds

Before

2 × (0) + 2 × (+1) = +2

After

1 × (0) + 3 × (+1) = +3

Count only the bonds that touch me. Bonds elsewhere did not change.

Before: 2 good and 2 bad. After: 1 good and 3 bad.

That is one more bad bond, and trading a good bond for a bad one costs 1.

So the energy change is +3 − (+2) = +1.

Whole lattice: \(E_{\mathrm{before}}=\) 17; \(E_{\mathrm{proposed}}=\) 18; \(\Delta E=\) +1

6

Must I go back?

The energy went up by 1. Must I go back to A?

Not always. At T = 0.3 you may keep B with probability P = 0.03567.

\[P=\min\{1,e^{-\Delta E/T}\}.\]

So I draw a number r between 0 and 1. If it lands in the blue part, I keep B.

7

The draw decides

r = 0.010 is smaller than P. I keep B!

The energy went up and the copy was still accepted. Uphill steps are allowed.

8

Count us

Count us: 3 A, 4 B, 5 C, 4 D.

One site moved from A to B. C and D did not change.

These letters name orientations. They are not components of one spin.

Follow the code and results

In symbols, \(E=\sum_{\langle ij\rangle}(1-\delta_{s_i,s_j})\), where \(\delta\) is 1 when the labels match and 0 otherwise. Here a matching bond costs 0 rather than \(-1\), so trading a good bond for a bad one costs 1. The supplied neighbor-copy rule is a grain-growth heuristic; this proposal with the simple Metropolis acceptance rule is not generally an unbiased equilibrium Potts sampler.

The calculation, one step at a time

We show the purpose of each notebook cell beside its code and recorded result. The controls move through those results; they do not execute Python in the browser. The notebook remains available for running or changing the calculation.

Loading the lesson…

We propose changes at randomly selected lattice sites. In the Ising model s is a spin, either −1 or 1. In the Potts example s is an orientation label. de is the proposed energy change. temperature is measured in units of the interaction energy divided by Boltzmann's constant. A sweep consists of n² trial updates. The Potts neighbor-copy rule models grain-growth kinetics, not equilibrium sampling.

We develop this calculation in small steps. We run a cell, inspect its result and test it before adding the next part. Run the cells in order in Jupyter. A code cell defines a part of the calculation or carries it out; defining a function does not run it.

I permit free noncommercial teaching, learning and demonstrations with acknowledgment. Research and commercial use require my written permission. Earlier licensed releases retain their permissions. Read the code-use terms.

Copyright (c) 2026 Saswata Bhattacharyya.

Step 1: Prepare the Python environment

We install the packages listed in the next cell once in the same environment as the notebook. In Jupyter or Colab, remove the comment marker from the installation line below if a package is missing. NumPy stores arrays and evaluates numerical operations. Matplotlib displays plots. Pillow reads and writes images. This installation does not change the model parameters.

# %pip install numpy matplotlib
import numpy as np
assert np.isfinite(np.array([0.0, 1.0])).all()
print("NumPy is ready:", np.__version__)
NumPy is ready: 2.1.3

Step 2: Prepare the next part of the calculation

We define the following operations. These are the same operations as in the original source, written on separate lines so their order is clear. Inspect their values before running the next cell.

from pathlib import Path
import sys
import numpy as np

Step 3: Run the complete example

We keep the original algorithm, parameters, seed and output conventions. We inspect the saved diagnostics before interpreting the pictures. A finite run is not evidence of convergence or equilibrium.

def run(mode='ising', output='mc_output', n=256, sweeps=None, save_every=None):
    if mode not in ('ising', 'potts'):
        raise ValueError('ising or potts')
    sweeps = (2000 if mode == 'potts' else 200) if sweeps is None else sweeps
    save_every = (25 if mode == 'potts' else 5) if save_every is None else save_every
    out = Path(output)
    out.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(7)
    s = rng.choice([-1, 1], (n, n)) if mode == 'ising' else rng.permutation(np.arange(1, n * n + 1)).reshape(n, n)
    rows = []
    temperature = 1.5 if mode == 'ising' else 0.3
    for sweep in range(sweeps + 1):
        if sweep:
            for _ in range(n * n):
                i, j = rng.integers(n, size=2)
                nb = [s[(i + 1) % n, j], s[(i - 1) % n, j], s[i, (j + 1) % n], s[i, (j - 1) % n]]
                old = s[i, j]
                candidate = -old if mode == 'ising' else nb[rng.integers(4)]
                de = 2 * old * sum(nb) if mode == 'ising' else sum((v != candidate for v in nb)) - sum((v != old for v in nb))
                if de <= 0 or rng.random() < np.exp(-de / temperature):
                    s[i, j] = candidate
        if sweep % save_every == 0:
            energy = -np.mean(s * (np.roll(s, 1, 0) + np.roll(s, 1, 1))) if mode == 'ising' else np.mean(s != np.roll(s, 1, 0)) + np.mean(s != np.roll(s, 1, 1))
            rows.append([sweep, energy, s.mean()])
            np.savetxt(out / f'field_{sweep:04d}.csv', s, delimiter=',', fmt='%d')
    np.savetxt(out / 'diagnostics.csv', rows, delimiter=',', header='sweep,energy_per_site,mean_label_or_spin', comments='')
    return s

Step 4: Our short test run

We first run both rules on a 16² grid for five sweeps, with the original seed and temperature. This tests execution and legal labels, not equilibrium. The unchanged full defaults, 256² and 200 or 2000 sweeps, remain available in the optional cell. A pure Python trial loop can take a long time.

ising = run("ising", "ising-check", n=16, sweeps=5, save_every=1)
potts = run("potts", "potts-check", n=16, sweeps=5, save_every=1)
assert set(np.unique(ising)).issubset({-1, 1})
assert potts.min() >= 1 and potts.max() <= 256
print("Both short calculations completed.")
Both short calculations completed.
# I run the complete original defaults only when I choose to do so.
run_full_calculation = False
if run_full_calculation:
    run("ising", "ising-results")
    run("potts", "potts-results")

Plot and interpret the result

We distinguish spin values from orientation labels. Potts colors indicate labels only; they are not crystallographic angles. Five sweeps on 16² sites are a short execution check, not the published full movies.

import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
axes[0].imshow(ising, cmap="coolwarm", vmin=-1, vmax=1)
axes[0].set_title("Ising: spin values −1 and 1")
axes[1].imshow(potts, cmap="tab20")
axes[1].set_title("Potts: orientation labels")
for ax in axes:
    ax.set_xlabel("Lattice column")
    ax.set_ylabel("Lattice row")
plt.show()
Computed result from the Ising and Potts: reproduce the lattice calculations notebook
Result from the executed notebook cell.

Step 5: Review and extend the calculation

Then we change one input, predict its effect and compare the result with that prediction. A successful check establishes the tested property; it does not establish convergence or equilibrium.

Technical details

We first restart the kernel and run all the required cells. The notebook embeds the calculation directly and does not need that script to run.

Technical details

Read the notebook execution checks

More step-by-step Python lessons