我正在尝试制作一个向左或向右移动的小粒子动画,但该图形在运行后立即关闭。我尝试在论坛上阅读一些提示,但没有帮助。
无法理解为什么动画对我不起作用。
我看了一些例子,但没有发现我犯的错误。
你能帮我吗?
import numpy as np
import random
from scipy.spatial.distance import pdist, squareform
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
class ParticleBox:
"""
init_state is a 3D array of x,y coordinates + probability to go left or right
bounds is the size of the box: [xmin, xmax, ymin, ymax]
"""
def __init__(self,
init_state, bounds = [-9, 9, -2, 2],
size = 0.04, step_size=0.05):
self.init_state = np.asarray(init_state, dtype=float)
self.size = size
self.state = self.init_state.copy()
self.time_elapsed = 0
self.bounds = bounds
self.ycorbeg=range(len(self.state))
def step(self, dts):
pr=0.4
pl=0.4
ps=0.2
self.time_elapsed+=dts
for i in range(len(self.state)):
print c
c=random.random()
if c<pr:
print c
self.state[i,2]=ze
elif (pr<=c and c<pr+pl):
self.state[i,2]=-step_size
else:
self.state[i,0]=self.state[i,0]
self.state[:, 0] += dt * self.state[:, 2]
np.random.seed(0)
beginx=np.random.rand(1000)-0.5
lenbegin=len(beginx)
def beginy(lenbegin,maxy=250):
i=0
beginy=np.zeros(lenbegin)
while i<lenbegin:
for j in range(int(-maxy/2),int(maxy/2)):
beginy[i]=j/50.0
i+=1
if len(beginx)==len(beginy):
ze=np.zeros(len(beginy))
print zip(beginx,beginy,ze)[0]
return zip(beginx,beginy,ze)
else:
raise ValueError
init_state=beginy(lenbegin)
box = ParticleBox(init_state)
dts = 1. / 30
#------------------------------------------------------------
# set up figure and animation
fig = plt.figure()
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
xlim=(-3.2, 3.2), ylim=(-2.4, 2.4))
# particles holds the locations of the particles
particles, = ax.plot([], [], 'bo', ms=6)
# rect is the box edge
rect = plt.Rectangle(box.bounds[::2],
box.bounds[1] - box.bounds[0],
box.bounds[3] - box.bounds[2],
ec='none', lw=2, fc='none')
ax.add_patch(rect)
def init():
"""initialize animation"""
global box, rect
particles.set_data([], [])
rect.set_edgecolor('none')
return particles, rect
def animate(i):
"""perform animation step"""
global box, rect, dts, fig
box.step(dts)
ms = int(fig.dpi * 2 * box.size * fig.get_figwidth()
/ np.diff(ax.get_xbound())[0])
# update pieces of the animation
rect.set_edgecolor('k')
particles.set_data(box.state[:, 0], box.state[:, 1])
particles.set_markersize(ms)
return particles, rect
anim = animation.FuncAnimation(fig, animate, frames=600,
interval=10, blit=True, init_func=init)
plt.show()