STEP-BY-STEP TEACHING CODE

Ising and Potts updates.

We build the calculation in small parts and test each part before continuing. The Python notebook follows the same sequence.

We build one local Monte Carlo update before repeating it. The square lattice is periodic. In the Ising model a spin has value -1 or +1; the dimensionless interaction strength is one and temperature is measured in units of the interaction energy divided by Boltzmann’s constant. For Potts grain growth the integers identify grains, not compositions. Neighbor-copy proposals describe the supplied grain-growth kinetics and should not be presented as unbiased equilibrium sampling.

Python notebook · Python notebook collection

If you would like a similar tutorial in Julia or C, email me with the lesson title and your intended use. I can share a Google Colab notebook with step-by-step explanations and worked examples.

Email: saswata_at_msme.iith.ac.in (replace _at_ with @).

Run notebook cells in order. Use Python with NumPy, Matplotlib and Jupyter.

Technical details

The download includes installation commands and the actual check report.

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…

Watch the larger systems evolve

The 16 × 16 arrays in the short lesson let us check individual updates. These saved 256 × 256 calculations show what happens when we repeat those updates across a larger system.

Ising spin alignment

At dimensionless temperature 1.5, blue and red spin domains develop over 200 sweeps. The two colors represent spins −1 and +1. Single-spin Metropolis flips do not conserve their relative amounts.

Potts grain growth

We begin with a distinct label at every site, randomly permuted across the grid. Neighbor-copy updates at temperature 0.3 allow grains to grow over 2,000 sweeps. Colors identify orientation labels, not composition. This is a grain-growth heuristic, rather than an unbiased equilibrium Potts sampler.

Press play on either movie. Each loops back to its initial frame after the last saved state. One sweep is 65,536 attempted updates, not a calibrated physical time. The lattice remains discrete; the larger systems show more of the evolving pattern.

Model details and numerical records

Step 1: Inspect periodic neighbors

We first test the boundary indexing on a grid of known values. Opposite edges are adjacent. Rows and columns identify sites; they are dimensionless indices.

Python

import numpy as np
rng = np.random.default_rng(7)
def neighbor_values(state, row, column):
    rows, columns = state.shape
    return [state[(row + 1) % rows, column], state[(row - 1) % rows, column],
            state[row, (column + 1) % columns], state[row, (column - 1) % columns]]

test_grid = np.arange(9).reshape(3, 3)
assert neighbor_values(test_grid, 0, 0) == [3, 6, 1, 2]
print("Periodic neighbor indexing passed.")

Step 2: Calculate the Ising energy change

Flipping a spin changes each of its four bond energies. In a uniform positive-spin neighborhood the change is +8. We check this before using a probability rule.

Python

def ising_energy_change(old_spin, neighbors):
    return 2 * old_spin * sum(neighbors)

assert ising_energy_change(1, [1, 1, 1, 1]) == 8
assert ising_energy_change(-1, [1, 1, 1, 1]) == -8
print("Ising energy changes passed.")

Step 3: Accept or reject a trial

We always accept a decrease in energy. For an increase we accept with probability exp(-ΔE/T). The dimensionless temperature T must be positive in this implementation. This rule permits occasional uphill moves; energy need not decrease at every update.

Python

def accept_trial(energy_change, temperature, rng):
    if temperature <= 0:
        raise ValueError("Use positive temperature in this example.")
    if energy_change <= 0:
        return True
    return rng.random() < np.exp(-energy_change / temperature)

assert accept_trial(-8, 1.5, rng)
assert accept_trial(0, 1.5, rng)
assert 0 < np.exp(-8 / 1.5) < 1
print("Acceptance checks passed.")

Step 4: A single Ising trial and repeated trials

We choose a random site with replacement. One sweep consists of as many attempted updates as there are sites, so some sites can be chosen more than once. A spin flip does not conserve total spin.

Python

def ising_trial(state, temperature, rng):
    row = rng.integers(state.shape[0])
    column = rng.integers(state.shape[1])
    old = state[row, column]
    change = ising_energy_change(old, neighbor_values(state, row, column))
    if accept_trial(change, temperature, rng):
        state[row, column] = -old

spins = rng.choice([-1, 1], (16, 16))
for trial in range(spins.size * 10):
    ising_trial(spins, 1.5, rng)
assert set(np.unique(spins)) <= {-1, 1}
print("Ising state values:", np.unique(spins))

Step 5: Change the local rule for Potts grain growth

For a Potts trial we propose a neighbor’s label and count unlike neighbors before and after the change. The energy change is the difference in these counts, in units of the grain-boundary interaction. No new grain label can be created by copying a neighbor. We check both the local change and that property.

Python

def potts_energy_change(old, candidate, neighbors):
    before = sum(value != old for value in neighbors)
    after = sum(value != candidate for value in neighbors)
    return after - before

assert potts_energy_change(1, 2, [2, 2, 2, 1]) == -2

def potts_trial(state, temperature, rng):
    row = rng.integers(state.shape[0])
    column = rng.integers(state.shape[1])
    neighbors = neighbor_values(state, row, column)
    candidate = neighbors[rng.integers(4)]
    change = potts_energy_change(state[row, column], candidate, neighbors)
    if accept_trial(change, temperature, rng):
        state[row, column] = candidate

grains = rng.permutation(np.arange(1, 257)).reshape(16, 16)
initial_labels = set(grains.ravel())
for trial in range(grains.size * 10):
    potts_trial(grains, 0.3, rng)
assert set(grains.ravel()) <= initial_labels
print("Grains initially:", len(initial_labels), "remaining labels:", len(np.unique(grains)))

import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 2, figsize=(9, 4))
axes[0].imshow(spins, vmin=-1, vmax=1, cmap="coolwarm")
axes[0].set_title("Ising: spins -1 and +1")
axes[1].imshow(grains, cmap="tab20")
axes[1].set_title("Potts: grain labels")
for ax in axes:
    ax.set_xlabel("Column index")
    ax.set_ylabel("Row index")
plt.show()
Checked result: Step 5: Change the local rule for Potts grain growth
Result from the executed Python notebook.
Technical details

What we checked

We executed all Python notebook cells in a clean kernel. The checks apply to the short examples shown here. They do not establish grid convergence or reproduce every long simulation.

Return to the code collection