Python模拟不起作用

时间:2014-02-19 02:24:26

标签: python numpy matplotlib simulation

我正在创建一个模拟重力波中水粒子的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()

我只是得到一张静态图像,我知道我很接近。我还应该添加什么才能让一切都变得活跃?最好是实时绘图。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

在导入pyplot并将plt.ion()更改为plt.drawNow()之后添加plt.draw(),我的笔记本电脑上可以获得15 fps。第二步是因为我在pyplot中没有drawNow方法。