2014-02-19 69 views
0

我創建一個Python模擬,在引力波車型的水顆粒。到目前爲止我的代碼是Python的模擬工作不

import numpy as np 
#import matplotlib 
import matplotlib.pyplot as plt 
#import pylab 

#pylab.ion() 

h = 2  # water depth 
D = 0.4 # wave amplitude 
k = 1  # wave number 

ds = 0.5 
x = np.arange(0, 15+ds, ds) 
y = np.arange(0, h+ds, ds) 
g = 10 
w = np.sqrt(g*k*np.tanh(k*h)) 
T = 2*np.pi/w 
xx,yy = np.meshgrid(x,y) 
hp = plt.plot(xx[:],yy[:],'x') 
plt.axis('equal') 
plt.axis([0,15,0,8]) #axis equal 
N = 24 

#matplotlib.interactive(True) 

t = 0 
while (True): 
    t = t + T/N 
    dispx = D/np.sinh(k*h) * np.outer(np.cosh(k*y), np.cos(k*x-w*t)) 
    dispy = D/np.sinh(k*h) * np.outer(np.sinh(k*y), np.sin(k*x-w*t)) 
    plt.setp(hp,'XData',xx[:]+dispx[:], 'YData',yy[:]+dispy[:]) 
    plt.drawNow() 

我只是得到一個靜態圖像,我知道我很近。我應該添加什麼來讓所有的東西都移動?最好是實時繪圖。

+3

Matplotlib具有['animation'包(http://matplotlib.org/api/animation_api.html)和[一些例子](http://matplotlib.org/1.3.1/examples/animation/index .html)如何使用它。我強烈希望他們在哈克動畫,有的在我的實驗室儘量讓所有的'pylab' /'ion'廢話,也許它會爲你工作爲好。它使出口視頻非常容易。 –

+0

有沒有一種快速的方式來讓現有的代碼工作?我正在翻譯來自Matlab的一些代碼,我還不是Python專家。 –

回答

2

您可以使用計時器回調:

import numpy as np 
import matplotlib.pyplot as plt 

h = 2  # water depth 
D = 0.4 # wave amplitude 
k = 1  # wave number 

ds = 0.5 
x = np.arange(0, 15+ds, ds) 
y = np.arange(0, h+ds, ds) 
g = 10 
w = np.sqrt(g*k*np.tanh(k*h)) 
T = 2*np.pi/w 
xx,yy = np.meshgrid(x,y) 
hp = plt.plot(xx[:],yy[:],'x') 
plt.axis('equal') 
plt.axis([0,15,0,8]) #axis equal 
N = 24 

fig = plt.gcf() 

def update(): 
    t = 0 
    while (True): 
     t = t + T/N 
     dispx = D/np.sinh(k*h) * np.outer(np.cosh(k*y), np.cos(k*x-w*t)) 
     dispy = D/np.sinh(k*h) * np.outer(np.sinh(k*y), np.sin(k*x-w*t)) 
     plt.setp(hp,'XData',xx[:]+dispx[:], 'YData',yy[:]+dispy[:]) 
     fig.canvas.draw_idle() 
     yield 

timer = fig.canvas.new_timer(interval=10) 
timer.add_callback(update().next) 
timer.start() 

plt.show() 
+0

你確定這是實時的嗎? Matlab仿真會顯示'x的移動速度要快得多。 –

0

我能夠只導入pyplot和改變到plt.draw()後加入plt.ion()讓我的筆記本電腦,每秒15幀。第二步是因爲我在pyplot中沒有drawNow方法。

+0

當我這樣做時,Python會凍結... –