在Python

时间:2017-02-03 21:54:21

标签: python numpy matplotlib montecarlo markov-chains

我自学了Metropolis算法并决定尝试用Python编写代码。我选择模拟Ising模型。我对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()

除了' KeyError'当我尝试使用16x16或其他任何东西时,从Tkinter异常和白色条带开始,它看起来和工作正常。现在我想知道的是,如果这是正确的,因为 -

我对如何使用FuncAnimation进行蒙特卡罗模拟和动画我的网格图感到不舒服 - 这是否有意义?

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

另外,请告诉我关于KeyError和白色条带的信息。

' KeyError'来了 -

Exception in Tkinter callback
Traceback (most recent call last):
   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1540, in __call__
      return self.func(*args)
   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 590, in callit
   func(*args)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_tkagg.py", line 147, in _on_timer
      TimerBase._on_timer(self)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 1305, in _on_timer
      ret = func(*args, **kwargs)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 1049, in _step
      still_going = Animation._step(self, *args)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 855, in _step
      self._draw_next_frame(framedata, self._blit)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 873, in _draw_next_frame
      self._pre_draw(framedata, blit)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 886, in _pre_draw
      self._blit_clear(self._drawn_artists, self._blit_cache)
   File "/usr/local/lib/python2.7/dist-packages/matplotlib/animation.py", line 926, in _blit_clear
      a.figure.canvas.restore_region(bg_cache[a])
KeyError: <matplotlib.axes._subplots.AxesSubplot object at 0x7fd468b2f2d0>

1 个答案:

答案 0 :(得分:3)

你一次提出很多问题。

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

  • 用于冷启动的红色屏幕:如果是冷启动,则仅使用1 s初始化网格。这意味着网格中的最小最大值为1。因此,pcolormesh的colormap标准化为范围[1,1]并且全部为红色。通常,您希望色彩映射跨越[-1,1],这可以使用vminvmax参数来完成。

    mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
    这也应该为&#34;冷启动&#34;。

  • 提供预期的行为
相关问题