简体   繁体   English

在Python中模拟Ising模型

[英]Simulating the Ising Model in Python

I taught myself the Metropolis Algorithm and decided to try code it in Python. 我自学了Metropolis算法并决定尝试用Python编写代码。 I chose to simulate the Ising model. 我选择模拟Ising模型。 I have an amateur understanding of Python and with that here is what I came up with - 我对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()

Apart from a 'KeyError' from a Tkinter exception and white bands when I try a 16x16 or anything above that, it looks and works fine. 除了来自Tkinter异常的'KeyError'和白色频带,当我尝试16x16或其他任何东西时,它看起来和工作正常。 Now what I want to know is if this is right because - 现在我想知道的是,如果这是正确的,因为 -

I am uncomfortable with how I have used FuncAnimation to do the Monte Carlo simulation AND animate my mesh plot - does that even make sense? 我对如何使用FuncAnimation进行蒙特卡罗模拟和动画我的网格图感到不舒服 - 这是否有意义?

And How about that cold start? 那冷启动怎么样? All I am getting is a red screen. 我得到的只是一个红色的屏幕。

Also, please tell me about the KeyError and the white banding. 另外,请告诉我KeyError和白色条带。

The 'KeyError' came up as - '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>

You are asking a lot of questions at a time. 你一次要问很多问题。

  • KeyError : cannot be reproduced. KeyError :无法再现。 It's strange that it should only occur for some array sizes and not others. 奇怪的是,它应该仅针对某些阵列大小而不是其他阵列大小。 Possibly something is wrong with the backend, you may try to use a different one by placing those lines at the top of the script 后端可能有问题,您可以尝试使用不同的方法,将这些行放在脚本的顶部
    import matplotlib
    matplotlib.use("Qt4Agg")
  • white bands : cannot be reproduced either, but possibly they come from an automated axes scaling. 白色条带 :也不能再现,但它们可能来自自动轴缩放。 To avoid that, you can set the axes limits manually plt.xlim(0,l-1) plt.ylim(0,l-1) 为避免这种情况,您可以手动设置轴限制plt.xlim(0,l-1) plt.ylim(0,l-1)
  • Using FuncAnimation to do the Monte Carlo simulation is perfectly fine. 使用FuncAnimation进行蒙特卡罗模拟非常精细。 f course it's not the fastest method, but if you want to follow your simulation on the screen, there is nothing wrong with it. 当然,这不是最快的方法,但是如果你想在屏幕上跟踪你的模拟,它就没有任何问题。 One may however ask the question why there would be only one spin flipping per time unit. 然而,人们可能会问为什么每个时间单位只有一次旋转翻转。 But that is more a question on the physics than about programming. 但这更像是关于物理学而不是编程的问题。

  • Red screen for cold start : In the case of the cold start, you initialize your grid with only 1 s. 冷启动的红色屏幕 :在冷启动的情况下,只需1秒即可初始化网格。 That means the minimum and maximum value in the grid is 1 . 这意味着网格中的最小值最大值为1 Therefore the colormap of the pcolormesh is normalized to the range [1,1] and is all red. 因此,pcolormesh的colormap标准化为范围[1,1]并且全部为红色。 In general you want the colormap to span [-1,1] , which can be done using vmin and vmax arguments. 通常,您希望colormap跨越[-1,1] ,这可以使用vminvmax参数来完成。

    mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
    This should give you the expected behaviour also for the "cold start". 这应该为您提供“冷启动”的预期行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM