Reputation: 83
I am trying to code the Ising Model using Python.
I think, I've coded it correctly, but I have a problem with the animation or the plotting. I seem to plot a new image of every configuration, instead of updating the existing one, resulting in a lot of saved images that I don't need. I just want a single plot that is being updated, if that's possible.
I know, I am plotting inside the loop, but I don't recall that being an issue, when I want to plot every iteration. Can it be a problem with Seaborn's heatmap?
I've attached my code:
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import seaborn as sns
#Constants
J = 1
h = 1
kbT = 1
beta = 1
#Grid
L = 20 #Dimensions
N = L**2 #Total number of grid points
#Initial configuration
spins = 2*np.random.randint(2, size = (L,L))-1
E = []
i = 0
plt.figure()
while i < 100000:
for i in range(1,N):
i += 1
s = tuple(npr.randint(0, L, 2)) # Random initial coordinate
# x and y coordinate
(sx, sy) = s
# Periodic boundary condition
sl = (sx-1, sy)
sr = ((sx+1)%L, sy)
sb = (sx, sy-1)
st = (sx, (sy+1)%L)
# Energy
E = spins[s] * ( spins[sl] + spins[sr] + spins[sb] + spins[st] )
if E <= 0 : # If negative, flip
spins[s] *= -1
else:
x = np.exp(-E/kbT) # If positve, check condition
q = npr.rand()
if x > q:
spins[s] *= -1
# Plot (heatmap)
sns.heatmap(spins, cmap = 'magma')
plt.pause(10e-10)
plt.draw()
plt.show()
Upvotes: 1
Views: 2111
Reputation: 2019
I think the function ion
and clf
could do the trick.
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
import seaborn as sns
#Constants
J = 1
h = 1
kbT = 1
beta = 1
#Grid
L = 20 #Dimensions
N = L**2 #Total number of grid points
#Initial configuration
spins = 2*np.random.randint(2, size = (L,L))-1
E = []
i = 0
plt.ion()
plt.figure()
plt.show()
while i < 100000:
for i in range(1,N):
i += 1
s = tuple(npr.randint(0, L, 2)) # Random initial coordinate
# x and y coordinate
(sx, sy) = s
# Periodic boundary condition
sl = (sx-1, sy)
sr = ((sx+1)%L, sy)
sb = (sx, sy-1)
st = (sx, (sy+1)%L)
# Energy
E = spins[s] * ( spins[sl] + spins[sr] + spins[sb] + spins[st] )
if E <= 0 : # If negative, flip
spins[s] *= -1
else:
x = np.exp(-E/kbT) # If positve, check condition
q = npr.rand()
if x > q:
spins[s] *= -1
# Plot (heatmap)
plt.clf()
sns.heatmap(spins, cmap = 'magma')
plt.pause(10e-10)
With the function ion
you are making interactive the plot, so you need to:
Here the reference for the ion
function.
Reference for clf
is here
Upvotes: 1