Matplotlib散点图动画不断崩溃Python

时间:2013-12-12 19:59:05

标签: python animation matplotlib

我在网上发现了一些关于在matplotlib动画崩溃Python时该怎么做的片状资源。

这是代码。我知道dt变量的点数或小数的某些变化可能会导致一些压倒性的计算,但我真的可以使用一些帮助。总的来说,它表现得非常缓慢,我需要让它顺利运行。代码用于物理类,它不是优化问题 - 项目的目标不是优化matplotlib的动画设施,而是在相空间中建模系统。我可以使用任何帮助。

import matplotlib
#matplotlib.use("TkAgg")
from matplotlib import animation
import matplotlib.pyplot as plt
import matplotlib.pylab as pl
import numpy as np
import math

# Create the window and the plot.
fig = plt.figure()
fig.canvas.set_window_title("Modelling Non-Linear Chaotic Systems in Phase ")
ax = fig.add_subplot(111)

##### CONSTANTS #####
NUM_POINTS = 40 # The number of points to discretize.
AUTOSCALE = False # Sets autoscale to true or false. If true, there will be odd (expected to a degree) behavior as time goes on.
NO_TRAIL = False # Adds a trail.
##### CONSTANTS #####

##### Cool Settings #####
# Double tail swirl.
# k = .2
# alpha = .4
# dt = .1
#####           #####

##### VARIABLES #####
m = 1 # mass constant
k = 5 # spring constant
alpha = .3 # stretch/deformation constant
dt = .01 # change in time
interval = 100 # interval in milliseconds between each animation
##### VARIABLES #####

class Point():
    def x():
        return self.x

    def y():
        return self.y

    def pos(xy):
        self.x=xy[0]
        self.y=xy[1]

    # initial_pos is a tuple
    def __init__(self, initial_pos):
        self.initial_position = initial_pos
        self._x = initial_pos[0]
        self._y = initial_pos[1]
        self.x = self._x
        self.y = self._y

def evolve(x_map, y_map, l):
    return [Point([x_map(el), y_map(el)]) for el in l]

"""
Lagrangian
L = T - V = .5dq^2 - .5kq^2 - .333alpha*q^3
p = mdq; dx = p/m
Hamiltonian
H = p^2/m - L
H = p^2/m - p^2/2m + .5kq^2 + .333alpha*q^3
dp = -partial(H)/partial(q) = -kq - alpha*q^2
dx = partial(H)/partial(p) = p/m
"""
def time_dependent_funcs(name, dt):
### This is the adjustment of p over time. ###
def p_map(point):
    p = point.y
    q = point.x
    try:
        dp = -1*k*q-alpha*q**2
        ddp = -k*p/m-alpha*q*p/m
        return p+dp*dt+ddp*dt**2
    except:
        return p
### End adjustment of p.                   ###
### This is the adjustment of q over time. ###
    def q_map(point):
        q = point.x
        p = point.y
        try:
            dq = p/m
            dp = -1*k*q-alpha*q**2
            ddp = -k*p/m-alpha*q*p/m
            return q+dq*dt+ddp*dt**2/m
        except:
            return q
    ### End adjustment of q.                   ###
    if name == "p_map":
    return p_map
    elif name == "q_map":
        return q_map

# Used this post to help create this function: http://stackoverflow.com/questions/14619876/how-do-i-generate-pair-of-random-points-in-a-circle-using-matlab
def circle(r, n):
    l = []
    for i in range(n):
    x=r+1 # necessary to enter loop
    y=r+1 # necessary to enter loop
    while (x**2 + y**2) > r**2:
        x = 2*r*np.random.randn()
        y = 2*r*np.random.randn()
        l.append(Point([x,y]))
    return l

### DOESN'T CURRENTLY WORK
def square(h, n):
    l = []
    for i in range(n):
        x=h+1 # necessary to enter loop
        y=h+1 # necessary to enter loop
        while x < h and y < h:
            x = np.random.randn()
            y = np.random.randn()
        l.append(Point([x,y]))
    return l

def rand(n):
    return [Point([np.random.randn(),np.random.randn()]) for i in range(n)]

def x(l):
    return [el.x for el in l]

def y(l):
    return [el.y for el in l]

#list_of_points = rand(NUM_POINTS) # works
#list_of_points = square(.2, 400) # doesn't currently work
list_of_points = circle(20,NUM_POINTS) # need this to be a global

def init():
    global list_of_points, dt
    scat = ax.scatter(x(list_of_points), y(list_of_points),color="blue", animated=NO_TRAIL)
    if NO_TRAIL:
        return scat,
def animate(i):
    global list_of_points, dt
    map_p = time_dependent_funcs("p_map", dt)
    map_q = time_dependent_funcs("q_map", dt)
    ### evolve the points ###
    list_of_points = evolve(map_q, map_p, list_of_points)
    scat = ax.scatter(x(list_of_points), y(list_of_points), color="blue",lw=2, animated=NO_TRAIL)
    if NO_TRAIL:
        return scat,

### Animates the figure fig by executing init_func init (initially) followed by animation function
### animate for 10 frames at an interval of 100ms all the while erasing the last animation (blit=True).
ani = animation.FuncAnimation(fig, animate, init_func=init, frames = 100,     interval=interval,blit=NO_TRAIL,save_count=0)

if not AUTOSCALE:
        plt.autoscale(enable=False)
plt.show()

0 个答案:

没有答案