Yes, I’m familiar with Manim, the Mathematical Animation Engine developed by 3Blue1Brown. Manim is a powerful tool for creating precise and high-quality mathematical animations programmatically using Python. While Manim is typically used via command-line scripts, it can also be integrated into Jupyter Notebooks to leverage the interactive capabilities of the notebook environment.
Below, I’ll guide you through an advanced example using Manim within a Jupyter Notebook. This example will demonstrate creating a complex animation that includes multiple scenes, transformations, graph plotting, and interactive elements such as sliders to control parameters in real time.
Prerequisites
-
Install Manim
First, ensure that you have Manim installed. You can install it via pip:
pip install manim
For the latest features, you might want to install it directly from the GitHub repository:
pip install git+https://github.com/ManimCommunity/manim.git
-
Install Jupyter Notebook
If you haven't already, install Jupyter Notebook:
pip install notebook
-
Install Additional Dependencies
To facilitate running Manim within Jupyter, install the ipympl backend and ipywidgets for interactive widgets:
pip install ipympl ipywidgets
-
Set Up Jupyter Extensions (Optional)
For enhanced interactivity, you might want to enable Jupyter extensions:
jupyter nbextension enable --py widgetsnbextension
Note: Some extensions might require additional setup depending on your Jupyter installation.
Example: Interactive Parametric Graph Animation
In this advanced example, we will animate a parametric curve (a Lissajous curve) and allow interactive control over its parameters using sliders. This will demonstrate:
- Creating parametric functions.
- Plotting graphs in Manim.
- Using transformations and dynamic updates.
- Integrating interactive widgets within Jupyter.
Step 1: Import Required Libraries
First, import the necessary libraries and modules.
import numpy as np
from manim import *
from IPython.display import display, HTML
import ipywidgets as widgets
from IPython.display import Video
import tempfile
import os
Step 2: Define the Manim Scene
Create a Manim scene that plots a Lissajous curve based on parameters configurable via sliders.
class LissajousScene(Scene):
def __init__(self, a=3, b=2, delta=0, **kwargs):
super().__init__(**kwargs)
self.a = a
self.b = b
self.delta = delta
def construct(self):
# Title
title = Text("Lissajous Curve", font_size=48)
self.play(Write(title))
self.wait(1)
self.play(FadeOut(title))
# Axes
axes = Axes(
x_range=(-3, 3),
y_range=(-3, 3),
x_length=6,
y_length=6,
axis_config={"color": WHITE},
)
axes.add_coordinate_labels(font_size=10)
self.play(Create(axes))
# Parametric function
lissajous = ParametricFunction(
lambda t: axes.c2p(
np.sin(self.a * t + self.delta),
np.sin(self.b * t),
0
),
t_range=np.array([0, TAU, 0.01]),
color=RED,
stroke_width=2
)
# Animation
self.play(Create(lissajous), run_time=4)
self.wait(1)
# Add dots moving along the curve
dot_a = Dot(color=BLUE).move_to(lissajous.get_start())
dot_b = Dot(color=GREEN).move_to(lissajous.get_start())
self.add(dot_a, dot_b)
# Updaters for dots
def update_dot_a(mob, dt):
alpha = (self.time / self.duration) % 1
mob.move_to(lissajous.point_from_proportion(alpha))
def update_dot_b(mob, dt):
alpha = (self.time / self.duration) % 1
mob.move_to(lissajous.point_from_proportion(alpha + 0.5))
dot_a.add_updater(update_dot_a)
dot_b.add_updater(update_dot_b)
self.wait(5)
# Remove updaters
dot_a.remove_updater(update_dot_a)
dot_b.remove_updater(update_dot_b)
self.play(FadeOut(VGroup(lissajous, dot_a, dot_b, axes)))
Step 3: Render the Scene
Since Manim typically renders scenes to video files, we'll write a function to render the scene and display it within the Jupyter Notebook.
def render_scene(a=3, b=2, delta=0):
# Create a temporary directory to store the video
with tempfile.TemporaryDirectory() as temp_dir:
# Define the scene
class TempScene(LissajousScene):
def __init__(self, **kwargs):
super().__init__(a=a, b=b, delta=delta, **kwargs)
# Render the scene using Manim's CLI interface
command = [
"manim",
"-pql", # low quality for quick rendering; use -pqh for high quality
"--disable_caching",
"--format=gif", # to get GIF output for easy embedding
temp_dir,
__file__, # current file
"TempScene"
]
# Since __file__ might not be defined in Jupyter, use an alternative approach
# Instead, use Manim's programmatic interface
config.media_dir = temp_dir
scene = TempScene()
scene.render()
# Locate the rendered GIF
gif_path = os.path.join(temp_dir, "TempScene.gif")
if os.path.exists(gif_path):
# Read and display the GIF
with open(gif_path, "rb") as f:
data = f.read()
display(HTML(f'<img src="data:image/gif;base64,{data.encode("base64").decode()}">'))
else:
print("Rendering failed.")
Note: The above render_scene function uses Manim's CLI for simplicity. However, integrating Manim's rendering directly within Jupyter can be more involved. For this example, we'll instead save the animation as a video file and display it.
Alternatively, here's a refined approach using Manim's programmatic interface without relying on shell commands:
def render_lissajous(a=3, b=2, delta=0):
# Initialize Manim configuration for file output
from manim import config, tempconfig
with tempfile.TemporaryDirectory() as temp_dir:
with tempconfig({
"media_dir": temp_dir,
"format": "gif",
"write_to_movie": True,
"quality": "low_quality",
"disable_caching": True,
}):
# Instantiate and render the scene
scene = LissajousScene(a=a, b=b, delta=delta)
scene.render()
# Locate the rendered file
gif_path = os.path.join(temp_dir, "LissajousScene.gif")
if os.path.exists(gif_path):
# Read and display the GIF
with open(gif_path, "rb") as f:
import base64
data = f.read()
b64 = base64.b64encode(data).decode()
display(HTML(f'<img src="data:image/gif;base64,{b64}">'))
else:
print("Rendering failed.")
Step 4: Create Interactive Widgets
Use ipywidgets to create sliders that control the parameters a, b, and delta of the Lissajous curve.
# Define sliders for parameters
a_slider = widgets.IntSlider(value=3, min=1, max=10, step=1, description='a:')
b_slider = widgets.IntSlider(value=2, min=1, max=10, step=1, description='b:')
delta_slider = widgets.FloatSlider(value=0, min=0, max=2*np.pi, step=0.1, description='delta:')
# Define a function to update the animation when sliders change
def update_animation(a, b, delta):
# Clear previous output
clear_output(wait=True)
# Display sliders again
display(a_slider, b_slider, delta_slider)
# Render and display the animation
render_lissajous(a, b, delta)
# Link the sliders to the update function
widgets.interactive(update_animation, a=a_slider, b=b_slider, delta=delta_slider)
Step 5: Putting It All Together
Combine the widgets and rendering function to create an interactive animation within the Jupyter Notebook.
from IPython.display import display, clear_output
# Initial display of sliders
display(a_slider, b_slider, delta_slider)
# Initial render
render_lissajous(a=a_slider.value, b=b_slider.value, delta=delta_slider.value)
# Define the observer function
def on_value_change(change):
render_lissajous(a=a_slider.value, b=b_slider.value, delta=delta_slider.value)
# Attach observers to sliders
a_slider.observe(on_value_change, names='value')
b_slider.observe(on_value_change, names='value')
delta_slider.observe(on_value_change, names='value')
Note: Rendering animations with Manim can be time-consuming, especially within a Jupyter Notebook environment. The above approach renders a GIF for each parameter change, which can be slow if sliders are moved rapidly. For a smoother experience, consider debouncing the slider updates or limiting the frequency of renders.
Advanced Features Demonstrated
- Parametric Functions: Plotting parametric curves based on mathematical functions.
- Transformations: Animating the creation and transformation of mathematical objects.
- Dynamic Updaters: Using updaters to make objects move or change over time.
- Interactive Widgets: Integrating
ipywidgets sliders to control animation parameters in real time.
- Rendering to GIF: Exporting animations to GIFs for easy embedding and display within Jupyter.
Additional Advanced Example: Fourier Series Approximation
Another complex and fascinating example is visualizing Fourier series approximations to various functions, such as square waves or sawtooth waves. Below is an outline of how you might implement such an animation.
Overview
- Objective: Animate the convergence of a Fourier series to approximate a square wave.
- Components:
- Individual harmonic sine waves.
- Summation of harmonics increasing over time.
- Visualization of the approximation alongside the target square wave.
Implementation Steps
- Define the Target Function: A square wave function.
- Compute Fourier Series Terms: Sum of sine waves with specific coefficients.
- Create Individual Wave Components: Each sine wave as a separate
ParametricFunction.
- Animate the Summation Process: Incrementally add harmonics to the sum.
- Display Convergence: Show how the sum approaches the square wave.
Example Code Snippet
class FourierSeriesScene(Scene):
def construct(self):
# Title
title = Text("Fourier Series Approximation", font_size=48)
self.play(Write(title))
self.wait(1)
self.play(FadeOut(title))
# Axes
axes = Axes(
x_range=(-PI, PI, PI/2),
y_range=(-1.5, 1.5, 0.5),
x_length=10,
y_length=4,
axis_config={"color": WHITE},
)
axes.add_coordinate_labels(font_size=10, decimal_number_config={"num_decimal_places":1})
self.play(Create(axes))
# Target square wave
def square_wave(x):
return 1 if x > 0 else -1
square_wave_graph = axes.get_graph(
lambda x: square_wave(x),
discontinuities=[0],
color=YELLOW
)
self.play(Create(square_wave_graph))
# Fourier series parameters
series = VMobject(color=BLUE)
series.set_points_as_corners([axes.c2p(-PI, 0, 0), axes.c2p(-PI, 0, 0)])
self.add(series)
num_harmonics = 10
for n in range(1, num_harmonics + 1):
if n % 2 == 0:
continue # Only odd harmonics for square wave
coefficient = (4 / (n * PI)) * (-1)**((n-1)//2)
harmonic = always_redraw(lambda: axes.get_graph(
lambda x: sum(
(4/(k * PI)) * np.sin(k * x) for k in range(1, n+1, 2)
),
color=BLUE
))
self.play(Create(harmonic), run_time=1)
series.become(harmonic)
self.wait(0.5)
self.wait(2)
Rendering and Display
You can use a similar approach as the previous example to render and display this scene within a Jupyter Notebook, adjusting the rendering settings as needed.
Tips for Using Manim in Jupyter Notebooks
-
Performance Considerations: Rendering complex animations can be resource-intensive and time-consuming within a Jupyter environment. For extensive projects, consider developing and rendering scenes separately using Python scripts.
-
Display Formats: While GIFs are convenient for embedding, they can be large in size and have limited color depth. For higher quality, consider rendering to MP4 or other video formats and using HTML video players within Jupyter.
-
Interactivity: Leveraging ipywidgets allows for interactive parameter adjustments, but be mindful of rendering times to maintain a responsive notebook experience.
-
Debugging: Developing and debugging Manim scenes is often easier in a script-based environment with direct access to logs and error messages. Use Jupyter for visualization and interactivity once your scenes are functioning correctly.
-
Cache Management: Disable caching during interactive development to ensure that changes are rendered immediately. This can be done using Manim configuration options as shown in the examples.
Conclusion
Integrating Manim with Jupyter Notebooks provides a powerful platform for creating and interacting with mathematical animations. While the integration requires careful handling of rendering processes and performance optimizations, the combination offers an excellent tool for educational purposes, demonstrations, and explorations of mathematical concepts.
Feel free to expand upon the provided examples, experiment with different mathematical functions, and explore Manim’s extensive features to create your own sophisticated animations within Jupyter Notebooks.