enthought / mayavi

3D visualization of scientific data in Python
http://docs.enthought.com/mayavi/mayavi/
Other
1.3k stars 284 forks source link

Problem with Animation : mlab.plot3d and mlab_source #1120

Closed caimingxue closed 2 years ago

caimingxue commented 2 years ago

Hello :)

I'm having some issues in trying to make an animation with Mayavi

In particular, below you may find a code for solving a classical Lorenz System, which I can easily plot. I would like to create an animation and show the state evolution to some students as it changes over time, by using

mlab.plot3d

When I run the code, I can see that I'm not able to update the animation.

I have already checked e.g. the solution in #696. but I didn't manage to go very far. Could you please help me to figure out what I should change?

Thanks in advance,

Best regards,

Stefano

from future import absolute_import, division, print_function import numpy as np from scipy.integrate import odeint from mayavi import mlab import moviepy.editor as mpy

rho = 28.0 sigma = 10.0 beta = 8.0 / 3.0

def f(state, t): x, y, z = state # Unpack the state vector return sigma (y - x), x (rho - z) - y, x y - beta z # Derivatives

state0 = [1.0, 1.0, 1.0] t = np.arange(0.0, 40.0, 0.01) dim_t = len(t)

states = odeint(f, state0, t)

x, y, z = states[:, 0], states[:, 1], states[:, 2]

mlab.plot3d(0,0,0,0) trajectory = mlab.plot3d(x, y, z, t, colormap='hot', tube_radius=None)

@mlab.animate(delay=100) def anim(): f = mlab.gcf() while True: for (i, j, k, w) in zip(x, y, z, t): print('Updating scene...')

        trajectory.mlab_source.set(i=i, j=j, k=k, w=w)

        yield

anim() mlab.show()

prabhuramachandran commented 2 years ago

This is not an issue. When you do plot3d(x, y, z, t), it actually shows you the entire trajectory. You should use set only when the shape does not change. Also set should use (x=i, y=j, k=k) but this will also not solve the issue. See the modified script below which perhaps does what you want. I show the full trajectory and a small marker that walks along this trajectory.

import numpy as np
from scipy.integrate import odeint
from mayavi import mlab
import moviepy.editor as mpy

rho = 28.0
sigma = 10.0
beta = 8.0 / 3.0

def f(state, t):
    x, y, z = state  # Unpack the state vector
    return sigma * (y - x), x * (rho - z) - y, x * y - beta * z  # Derivatives

state0 = [1.0, 1.0, 1.0]
t = np.arange(0.0, 40.0, 0.01)
dim_t = len(t)

states = odeint(f, state0, t)

x, y, z = states[:, 0], states[:, 1], states[:, 2]

marker = mlab.points3d(x[0], y[0], z[0])
trajectory = mlab.plot3d(x, y, z, t, colormap='hot', tube_radius=None)

@mlab.animate(delay=20)
def anim():
    while True:
        for (i, j, k, w) in zip(x, y, z, t):
            marker.mlab_source.set(x=i, y=j, z=k)
            yield

anim()
mlab.show()