Creating an engaging and aesthetically pleasing 3D visualization using Manim for your Kalman Filter results is a fantastic idea! Below is a comprehensive example that builds upon your initial code. This script sets up a 3D scene with axes, plots both true and estimated positions as moving spheres, includes a timestamp, and adds smooth camera rotations to emulate the style of 3Blue1Brown.
Complete Code Example
from manim import *
import numpy as np
import pandas as pd
# Load your data
try:
true_positions = pd.read_csv('true_positions.csv', header=None).values # Shape: (N, 3)
true_velocities = pd.read_csv('true_velocities.csv', header=None).values # Shape: (N, 3)
estimated_positions = pd.read_csv('estimated_positions.csv', header=None).values # Shape: (N, 3)
estimated_velocities = pd.read_csv('estimated_velocities.csv', header=None).values # Shape: (N, 3)
except FileNotFoundError as e:
print(f"Error: {e}")
# You might want to handle the error or exit
def calculate_axes_ranges(positions):
min_vals = positions.min(axis=0)
max_vals = positions.max(axis=0)
padding = 50 # Add some space around the max range for better visibility
return min_vals - padding, max_vals + padding
# Calculate overall min and max for all positions to set up the axes
min_values, max_values = calculate_axes_ranges(np.concatenate((true_positions, estimated_positions), axis=0))
# Define axis ranges with step sizes for better tick management
x_range = [min_values[0], max_values[0], 50]
y_range = [min_values[1], max_values[1], 50]
z_range = [min_values[2], max_values[2], 50]
class KalmanFilter3DVisualization(ThreeDScene):
def construct(self):
# Set up the camera orientation
self.set_camera_orientation(phi=75 * DEGREES, theta=-45 * DEGREES)
# Create 3D axes
axes = ThreeDAxes(
x_range=x_range,
y_range=y_range,
z_range=z_range,
x_length=10,
y_length=10,
z_length=10,
axis_config={
"color": BLUE,
"include_ticks": True,
"include_numbers": True,
"font_size": 24,
}
)
# Add labels to axes
x_label = axes.get_x_axis_label(Tex("X"), edge=RIGHT, direction=RIGHT)
y_label = axes.get_y_axis_label(Tex("Y"), edge=UP, direction=UP)
z_label = axes.get_z_axis_label(Tex("Z"), edge=OUT, direction=OUT)
self.play(Create(axes), Write(x_label), Write(y_label), Write(z_label))
self.wait(1)
# Initialize spheres for true and estimated positions
true_sphere = Sphere(radius=0.5, color=GREEN).move_to(axes.c2p(*true_positions[0]))
estimated_sphere = Sphere(radius=0.5, color=RED).move_to(axes.c2p(*estimated_positions[0]))
# Add spheres to the scene
self.play(FadeIn(true_sphere), FadeIn(estimated_sphere))
self.wait(1)
# Initialize timestamp Text
timestamp = Tex(f"T = 0", font_size=24).to_edge(DOWN)
self.play(Write(timestamp))
self.wait(0.5)
# Determine number of frames based on your data length
N = len(true_positions)
# To manage performance, you might want to skip some frames if N is too large
frame_step = max(1, N // 200) # Adjust to ensure smooth animation
for i in range(1, N, frame_step):
# Get the current positions
true_pos = true_positions[i]
est_pos = estimated_positions[i]
# Calculate new positions in Manim's coordinate system
true_manim_pos = axes.c2p(*true_pos)
est_manim_pos = axes.c2p(*est_pos)
# Update sphere positions
self.play(
true_sphere.animate.move_to(true_manim_pos),
estimated_sphere.animate.move_to(est_manim_pos),
# Update timestamp
Transform(timestamp, Tex(f"T = {i}", font_size=24).to_edge(DOWN)),
run_time=0.05,
rate_func=linear
)
# Optionally, add trails by continuously adding lines or dots
# For simplicity and performance, it's omitted here
# Optional: Keep the final frame for a moment
self.wait(2)
# Optional: Add camera rotation for better visualization
self.begin_ambient_camera_rotation(rate=0.1) # Rotate slowly
self.wait(5)
self.stop_ambient_camera_rotation()
# Fade out all objects at the end
self.play(FadeOut(VGroup(axes, true_sphere, estimated_sphere, timestamp)),
run_time=2)
Explanation of the Code
-
Data Loading:
- The script starts by loading your CSV files containing true and estimated positions and velocities.
- It handles potential
FileNotFoundError to ensure the script doesn't crash if files are missing.
-
Axis Range Calculation:
- The
calculate_axes_ranges function determines the minimum and maximum values across all position data to set up the axes with appropriate padding for better visualization.
-
Setting Up the 3D Scene:
- The
ThreeDAxes object is created with the computed ranges. The x_length, y_length, and z_length define the visual length of the axes in the scene, which you can adjust based on your preference.
- Axis labels (
X, Y, Z) are added for clarity.
-
Initializing Spheres:
- Two spheres represent the true and estimated positions. They are initialized at the starting positions of your data (
T=0).
- Colors are set to differentiate between true (
GREEN) and estimated (RED) positions.
-
Timestamp Display:
- A
Tex object displays the current timestamp (T = i) at the bottom of the screen. This updates as the animation progresses.
-
Animating the Spheres:
- The animation iterates through the position data, updating the position of both spheres at each timestep.
- The
frame_step is calculated to ensure that the animation runs smoothly without causing performance issues, especially if N is large.
- The spheres move to their new positions with
animate.move_to, and the timestamp updates accordingly with a Transform.
-
Camera Rotation:
- To emulate the dynamic and engaging style of 3Blue1Brown, ambient camera rotation is initiated after the spheres have moved to their final positions. The
begin_ambient_camera_rotation method adds a slow, continuous rotation to the camera, making the 3D visualization more captivating.
- The rotation stops after 5 seconds with
stop_ambient_camera_rotation.
Additional Enhancements
To make your visualization even more engaging and informative, consider the following enhancements:
-
Trails:
- You can add trails or paths for each sphere to show the trajectory over time. Use
VMobject with lines connecting previous positions.
# Initialize paths
true_path = VMobject(color=GREEN)
true_path.set_points_as_corners([true_sphere.get_center(), true_sphere.get_center()])
estimated_path = VMobject(color=RED)
estimated_path.set_points_as_corners([estimated_sphere.get_center(), estimated_sphere.get_center()])
self.add(true_path, estimated_path)
# Inside the loop after moving spheres
true_path.add_points_as_corners([true_path.get_end(), true_sphere.get_center()])
estimated_path.add_points_as_corners([estimated_path.get_end(), estimated_sphere.get_center()])
-
Velocity Vectors:
- Display velocity vectors using arrows to represent the direction and magnitude of velocity at each timestep.
# Initialize velocity arrows
true_velocity_arrow = Arrow3D(start=true_sphere.get_center(),
end=true_sphere.get_center() + axes.c2p(*(true_velocities[0])),
color=GREEN)
estimated_velocity_arrow = Arrow3D(start=estimated_sphere.get_center(),
end=estimated_sphere.get_center() + axes.c2p(*(estimated_velocities[0])),
color=RED)
self.add(true_velocity_arrow, estimated_velocity_arrow)
# Inside the loop after moving spheres
self.play(
true_velocity_arrow.animate.become(
Arrow3D(
start=true_sphere.get_center(),
end=true_sphere.get_center() + axes.c2p(*(true_velocities[i])),
color=GREEN
)
),
estimated_velocity_arrow.animate.become(
Arrow3D(
start=estimated_sphere.get_center(),
end=estimated_sphere.get_center() + axes.c2p(*(estimated_velocities[i])),
color=RED
)
),
run_time=0.05,
rate_func=linear
)
-
Interactivity:
- Although Manim animations are generally pre-rendered, consider generating interactive visualizations using Manim's interactive features or exporting frames for use in interactive platforms.
-
Color Gradients:
- Use color gradients to represent time progression, making older positions fade while newer ones are brighter.
Running the Animation
-
Save the Script:
- Save the complete script in a Python file, for example,
kalman_visualization.py.
-
Install Manim Community:
-
Render the Animation:
-
Use the Manim command to render your scene. From the terminal, navigate to the directory containing your script and run:
manim -pql kalman_visualization.py KalmanFilter3DVisualization
-
The flags -pql denote:
-p: Preview the video once rendered.
-ql: Render at low quality for faster processing. Change to -qm for medium quality or -qh for high quality as needed.
-
Adjust Performance:
- If rendering is slow or the animation is choppy, consider increasing
frame_step to skip more frames, thereby reducing the total number of animations.
Final Thoughts
This visualization provides a clear and dynamic comparison between the true and estimated positions of an object over time, leveraging the power of Manim to create smooth and visually appealing animations. Customize the colors, sphere sizes, camera angles, and additional elements like trails or velocity vectors to best fit your data and the story you wish to convey.
Feel free to tweak and enhance the script to better suit your specific requirements and to explore more of Manim's capabilities!