用Python模拟Ising模型

2024-06-16 13:56:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我自学了Metropolis算法,并决定尝试用Python编写它。我选择模拟伊辛模型。我对Python有一个业余的了解,这就是我所想到的-

import numpy as np, matplotlib.pyplot as plt, matplotlib.animation as animation

def Ising_H(x,y):

    s = L[x,y] * (L[(x+1) % l,y] + L[x, (y+1) % l] + L[(x-1) % l, y] + L[x,(y-1) % l])
    H = -J * s
    return H

def mcstep(*args): #One Monte-Carlo Step - Metropolis Algorithm

    x = np.random.randint(l)
    y = np.random.randint(l)
    i = Ising_H(x,y)
    L[x,y] *= -1
    f = Ising_H(x,y)
    deltaH = f - i
    if(np.random.uniform(0,1) > np.exp(-deltaH/T)):
        L[x,y] *= -1

    mesh.set_array(L.ravel())
    return mesh,

def init_spin_config(opt):

    if opt == 'h':
        #Hot Start
        L = np.random.randint(2, size=(l, l)) #lxl Lattice with random spin configuration
        L[L==0] = -1
        return L

    elif opt =='c':
        #Cold Start
        L = np.full((l, l), 1, dtype=int) #lxl Lattice with all +1
        return L

if __name__=="__main__":

     l = 15 #Lattice dimension
     J = 0.3 #Interaction strength
     T = 2.0 #Temperature
     N = 1000 #Number of iterations of MC step
     opt = 'h' 

     L = init_spin_config(opt) #Initial spin configuration

     #Simulation Vizualization
     fig = plt.figure(figsize=(10, 10), dpi=80)
     fig.suptitle("T = %0.1f" % T, fontsize=50)
     X, Y = np.meshgrid(range(l), range(l))
     mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu)
     a = animation.FuncAnimation(fig, mcstep, frames = N, interval = 5, blit = True)
     plt.show()

除了Tkinter异常的“KeyError”和当我尝试16x16或更高版本时的白色条纹,它看起来和工作都很好。现在我想知道这是否正确,因为-

我对如何使用FuncAnimation来做蒙特卡罗模拟和网格图动画感到不舒服-这有意义吗?在

冷启动怎么样?我得到的只是一个红色的屏幕。在

另外,请告诉我钥匙错误和白带。在

“键盘错误”是-

^{pr2}$

Tags: returnifdefasnpfigpltrandom
1条回答
网友
1楼 · 发布于 2024-06-16 13:56:26

你一次问了很多问题。在

  • KeyError:无法复制。奇怪的是,它应该只出现在某些数组大小,而不是其他数组大小。后端可能出了问题,您可以尝试使用另一个后端,方法是将这些行放在脚本的顶部
    import matplotlib
    matplotlib.use("Qt4Agg")
  • 白带:也无法复制,但可能来自自动轴缩放。要避免这种情况,可以手动设置轴限制 plt.xlim(0,l-1) plt.ylim(0,l-1)
  • 使用函数动画进行蒙特卡罗模拟是非常好的。当然,这不是最快的方法,但是如果你想在屏幕上跟踪你的模拟,它没有什么问题。然而,人们可能会问为什么每个时间单位只有一个旋转翻转。但这更像是一个物理问题,而不是编程问题。

  • 冷启动的红色屏幕:在冷启动的情况下,只使用1s初始化网格。这意味着网格中的最小最大值是1。因此,pcolormesh的colormap被规范化为范围[1,1],并且全部为红色。一般来说,您希望colormap跨越[-1,1],这可以使用vminvmax参数来完成。在

    mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
    这也会给你“冷启动”的预期行为。

相关问题 更多 >