[英]How to animate matplotlib.imshow()?
我是一名物理专业的学生,试图在 Python 中使用 Metropolis 算法来模拟 2D Ising 模型。 我想看看 imshow() 的时间演变,并使用了下面的代码。 但是程序输出一个空白图。 我该怎么办? 谢谢您的帮助!!
n = 50
ims =[]
def lattice(p):
init_random = np.random.random((n,n))
d = np.zeros((n,n))
d[init_random>=p] = 1
d[init_random<p] = -1
return d
def energy(lattice):
kern = generate_binary_structure(2, 1)
kern[1][1] = False
e = -lattice * convolve(lattice, kern, mode='constant', cval=0)
return e.sum()
def metropolis(s, b, t, e):
s = s.copy()
for t in range(0,t-1):
x = np.random.randint(0,n)
y = np.random.randint(0,n)
si = s[x,y]
sf = -1*si
ei = 0
ef = 0
if x > 0:
ei += -si*s[x-1,y]
ef += -sf*s[x-1,y]
if x < n-1:
ei += -si*s[x+1,y]
ef += -sf*s[x+1,y]
if y > 0:
ei += -si*s[x,y-1]
ef += -sf*s[x,y-1]
if y < n-1:
ei += -si*s[x,y+1]
ef += -sf*s[x,y+1]
de = ef - ei
if (de>0)*(np.random.random() < np.exp(-b*de)):
s[x,y] = sf
elif (de<=0):
s[x,y] = sf
im = plt.imshow(s, animated = True)
ims.append([im])
return ims
u = lattice(0.25)
e = energy(u)
fig = plt.figure(figsize=(6,6))
ims = metropolis(u, 0.7, 100, e)
ani = animation.ArtistAnimation(fig, ims, interval = 50, blit = True, repeat_delay = 100)
plt.show()
我只需要添加导入并更改 def 能量部分(特别是 e= 行)。 它在我的系统中运行良好。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import ndimage, convolve
n = 50
ims =[]
def lattice(p):
init_random = np.random.random((n,n))
d = np.zeros((n,n))
d[init_random>=p] = 1
d[init_random<p] = -1
return d
def energy(lattice):
kern = ndimage.generate_binary_structure(2, 1)
kern[1][1] = False
e = -lattice * ndimage.convolve(lattice, kern, mode='constant', cval=1)
return e.sum()
def metropolis(s, b, t, e):
s = s.copy()
for t in range(0,t-1):
x = np.random.randint(0,n)
y = np.random.randint(0,n)
si = s[x,y]
sf = -1*si
ei = 0
ef = 0
if x > 0:
ei += -si*s[x-1,y]
ef += -sf*s[x-1,y]
if x < n-1:
ei += -si*s[x+1,y]
ef += -sf*s[x+1,y]
if y > 0:
ei += -si*s[x,y-1]
ef += -sf*s[x,y-1]
if y < n-1:
ei += -si*s[x,y+1]
ef += -sf*s[x,y+1]
de = ef - ei
if (de>0)*(np.random.random() < np.exp(-b*de)):
s[x,y] = sf
elif (de<=0):
s[x,y] = sf
im = plt.imshow(s, animated = True)
ims.append([im])
return ims
u = lattice(0.25)
e = energy(u)
fig = plt.figure(figsize=(6,6))
ims = metropolis(u, 0.7, 100, e)
ani = animation.ArtistAnimation(fig, ims, interval = 50, blit = True, repeat_delay = 100)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.