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.
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.
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.
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.
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 matplotlibimportnumpyasnpassertnp.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.
frompathlibimportPathimportsysimportnumpyasnp
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.
defrun(mode='ising',output='mc_output',n=256,sweeps=None,save_every=None):ifmodenotin('ising','potts'):raiseValueError('ising or potts')sweeps=(2000ifmode=='potts'else200)ifsweepsisNoneelsesweepssave_every=(25ifmode=='potts'else5)ifsave_everyisNoneelsesave_everyout=Path(output)out.mkdir(parents=True,exist_ok=True)rng=np.random.default_rng(7)s=rng.choice([-1,1],(n,n))ifmode=='ising'elserng.permutation(np.arange(1,n*n+1)).reshape(n,n)rows=[]temperature=1.5ifmode=='ising'else0.3forsweepinrange(sweeps+1):ifsweep:for_inrange(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=-oldifmode=='ising'elsenb[rng.integers(4)]de=2*old*sum(nb)ifmode=='ising'elsesum((v!=candidateforvinnb))-sum((v!=oldforvinnb))ifde<=0orrng.random()<np.exp(-de/temperature):s[i,j]=candidateifsweep%save_every==0:energy=-np.mean(s*(np.roll(s,1,0)+np.roll(s,1,1)))ifmode=='ising'elsenp.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='')returns
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)assertset(np.unique(ising)).issubset({-1,1})assertpotts.min()>=1andpotts.max()<=256print("Both short calculations completed.")
Both short calculations completed.
# I run the complete original defaults only when I choose to do so.run_full_calculation=Falseifrun_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.
importmatplotlib.pyplotaspltfig,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")foraxinaxes:ax.set_xlabel("Lattice column")ax.set_ylabel("Lattice row")plt.show()
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.