2017-02-03 32 views
3

我自學了Metropolis算法,並決定嘗試在Python中進行編碼。我選擇模擬Ising模型。我的Python愛好者瞭解和這裏就是我想出了 -在Python中模擬Ising模型

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異常」當我嘗試上面,一個16×16或任何東西,它看起來並且工作正常。現在我想知道的是,如果這是正確的,因爲 -

我對我如何使用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> 
+0

在哪裏特別是你會得到一個KeyError?你能提供一個堆棧跟蹤嗎? – lordingtar

回答

3

你問了很多問題,在同一時間。

  • KeyError:不能再現。奇怪的是,它應該只發生在一些數組大小而不是其他數組中。也許事情是錯誤的後端,您可以嘗試通過將這些線路在腳本
    import matplotlib
    matplotlib.use("Qt4Agg")
  • 白色條紋的頂部使用一個不同:也不能被複制,但可能他們來自一個自動軸縮放。爲了避免這種情況,您可以設置軸限制手動 plt.xlim(0,l-1) plt.ylim(0,l-1)
  • 使用FuncAnimation做蒙特卡羅模擬是完全沒有問題。當然,這不是最快的方法,但如果你想在屏幕上跟隨你的模擬,那沒有什麼問題。然而,人們可能會問,爲什麼每個時間單位只有一個自旋翻轉。但這更多的是關於物理學的問題,而不是編程問題。

  • 用於冷啓動的紅色屏幕:在冷啓動的情況下,僅用1 s初始化電網。這意味着網格中的最小值最大值爲1。因此,pcolormesh的顏色表被標準化爲範圍[1,1],全部爲紅色。一般而言,您希望顏色圖跨越[-1,1],這可以使用vminvmax參數完成。

    mesh = plt.pcolormesh(X, Y, L, cmap = plt.cm.RdBu, vmin=-1, vmax=1)
    這應該會給你「冷啓動」的預期行爲。

+0

我不知道KeyError,但我用可能的解決方案更新了答案。 – ImportanceOfBeingErnest

+0

您的回答幫助我解決了冷啓動問題並刪除了白色條紋,謝謝!就像你說的那樣,這兩種情況都是錯誤的範圍。如果你想看看,我還用KeyError問題的堆棧跟蹤編輯了我的問題!我確實同意FuncAnimation不會是最快的,我期待着玩,並且實際上看到系統達到平衡。我寧願看看磁化和自相關函數。但有沒有另一種方式來動態更新matplotlib圖並可視化模擬? –

+0

除了使用'FuncAnimation'外,您還可以手動或在一個循環內調用'mcstep',這需要添加'fig.canvas.draw()'和可能''plt.pause(1e-5)'來更新繪製並防止窗口變得無法響應。但是讓我問一下:不使用FuncAnimation的原因是什麼? – ImportanceOfBeingErnest