Yes, I am familiar with Manim, the mathematical animation engine developed in Python. Using Manim within a Jupyter notebook can be a great way to iteratively develop animations and integrate them with other data analysis workflows.
Here's a comprehensive guide on how to use Manim in Jupyter notebooks, along with some complex examples to get you started.
Installing Manim for Jupyter Notebook
First, ensure you have Manim Community Edition (ManimCE) installed, as it's the actively maintained version of Manim. You can install it using pip:
pip install manim
To use Manim in a Jupyter notebook, you will need to install IPython and ipympl for interactive plots:
pip install ipython ipympl
Setting Up Manim in Jupyter Notebook
In your Jupyter notebook, you can set up Manim to render animations directly within the notebook cells. Here's how to configure it:
- Import Necessary Modules:
import manim
from manim import *
- Set Up Jupyter Magic Command:
Manim provides magic commands to facilitate rendering within Jupyter notebooks. You can define a custom magic command to simplify the rendering process:
from IPython.display import HTML, display
from IPython import get_ipython
def manim_render(scene):
video = scene.renderer.file_writer.movie_file_path
return HTML(f"""
<video autoplay loop controls style="width: 100%">
<source src="{video}" type="video/mp4">
</video>
""")
ipython = get_ipython()
def run_manim_scene(scene_cls):
scene = scene_cls()
scene.render()
display(manim_render(scene))
ipython.magic("reload_ext autoreload")
ipython.magic("autoreload 2")
Complex Examples
Below are some complex examples demonstrating advanced features of Manim within Jupyter notebooks.
Example 1: Fourier Series Approximation of a Square Wave
This example visualizes the Fourier series approximation of a square wave using rotating vectors and drawn paths.
class FourierSeries(Scene):
def construct(self):
# Number of terms in the Fourier series
N = 50
# Set up the time parameter
t = ValueTracker(0)
# Create the vectors and the path
vectors = VGroup()
origin = ORIGIN
for k in range(1, 2*N, 2): # Only odd harmonics
coef = (4 / (k * PI))
freq = k
vector = always_redraw(
lambda k=k, coef=coef, freq=freq:
Vector(RIGHT * coef * np.cos(freq * t.get_value()) + UP * coef * np.sin(freq * t.get_value())).shift(origin)
)
vectors.add(vector)
origin = vector.get_end()
path = TracedPath(origin.get_end, stroke_color=YELLOW)
# Animate
self.add(vectors, path)
self.play(
t.animate.increment_value(2 * PI),
rate_func=linear,
run_time=10
)
# Run the scene
run_manim_scene(FourierSeries)
Explanation:
- ValueTracker: Used to simulate the passage of time
t.
- Vectors: A series of vectors representing the terms of the Fourier series.
- TracedPath: Draws the path traced by the tip of the last vector.
- Animation: The time
t is incremented to animate the movement.
Example 2: Visualizing a Complex Function Mapping
This example demonstrates the mapping of a grid under a complex function ( f(z) = z^2 ).
class ComplexMapping(Scene):
def construct(self):
# Create a grid of points in the complex plane
real_values = np.linspace(-2, 2, 20)
imag_values = np.linspace(-2, 2, 20)
points = VGroup()
for x in real_values:
for y in imag_values:
dot = Dot(point=complex_to_R3(complex(x, y)), radius=0.04)
points.add(dot)
# Apply a complex function to each point
def update_points(mob):
for dot in mob:
z = R3_to_complex(dot.get_center())
w = z ** 2 # Complex function
dot.move_to(complex_to_R3(w))
return mob
transformed_points = always_redraw(lambda: update_points(points))
# Animate the transformation
self.play(FadeIn(points))
self.play(Transform(points, transformed_points), run_time=5)
self.wait()
# Run the scene
run_manim_scene(ComplexMapping)
Explanation:
- Grid of Points: Represents a grid in the complex plane.
- Complex Function: ( f(z) = z^2 ).
- Transformation: Maps each point through the complex function and animates the transformation.
Example 3: Parametric Surface Plotting
This example plots a parametric surface, such as a Möbius strip.
class MobiusStrip(ThreeDScene):
def construct(self):
# Set up camera
self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
# Define the parametric surface
mobius = ParametricSurface(
lambda u, v: np.array([
(1 + (v/2)*np.cos(u/2)) * np.cos(u),
(1 + (v/2)*np.cos(u/2)) * np.sin(u),
(v/2)*np.sin(u/2)
]),
u_range=[0, TAU],
v_range=[-1, 1],
checkerboard_colors=[BLUE_D, BLUE_E],
resolution=(15, 32)
)
# Add surface to scene
self.add(mobius)
self.begin_ambient_camera_rotation(rate=0.2)
self.wait(10)
# Run the scene
run_manim_scene(MobiusStrip)
Explanation:
- ThreeDScene: Enables 3D capabilities in Manim.
- ParametricSurface: Defines a Möbius strip using parametric equations.
- Camera Rotation: Animates the camera to rotate around the object.
Example 4: Differential Equation Visualization
Visualizing solutions to differential equations, like the Lorenz attractor.
class LorenzAttractor(ThreeDScene):
def construct(self):
# Parameters for the Lorenz system
sigma = 10
rho = 28
beta = 8 / 3
dt = 0.01
num_steps = 10000
# Initial conditions
x, y, z = 0.1, 0.0, 0.0
points = []
for _ in range(num_steps):
dx = sigma * (y - x) * dt
dy = (x * (rho - z) - y) * dt
dz = (x * y - beta * z) * dt
x += dx
y += dy
z += dz
points.append([x, y, z])
# Convert points to Manim Line
trajectory = Line3D(
points=points,
stroke_color=YELLOW,
stroke_width=0.5
)
# Set up camera
self.set_camera_orientation(phi=75 * DEGREES, theta=30 * DEGREES)
# Add trajectory to scene
self.add(trajectory)
self.begin_ambient_camera_rotation(rate=0.2)
self.wait(10)
# Run the scene
run_manim_scene(LorenzAttractor)
Explanation:
- Differential Equations: Numerically solves the Lorenz system.
- Trajectory: Creates a 3D line from computed points.
- Animation: Camera rotation to view the attractor from different angles.
Notes
- Performance Considerations: Rendering complex animations can be resource-intensive. Adjust parameters like resolution and number of steps to suit your system.
- Interactivity: Manim does not support interactive widgets within Jupyter notebooks. To interact with animations, you may need to export them as videos or GIFs.
- Version Compatibility: Ensure that you are using compatible versions of Manim and Jupyter. The code above is compatible with Manim Community Edition.
Additional Resources
Conclusion
Using Manim within Jupyter notebooks allows for an integrated development and presentation workflow. The examples provided demonstrate how to create complex mathematical animations, from Fourier series visualizations to 3D parametric surfaces and differential equation trajectories.
Feel free to modify and expand upon these examples to suit your specific needs. Happy animating!