Math-To-Manim
This skill should be used when the user asks to "create a math animation", "animate a mathematical concept", "generate Manim code", "visualize [topic] with animation", "explain [concept] visually", "create an educational video", "build a Manim scene", or mentions "reverse knowledge tree", "prerequisite discovery", or "verbose prompt generation". Provides a complete six-agent workflow for transforming any concept into professional Manim animations through recursive prerequisite discovery.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install harleycoops-math-to-manim-math-to-manim
Repository
Skill path: skill/skills/math-to-manim
This skill should be used when the user asks to "create a math animation", "animate a mathematical concept", "generate Manim code", "visualize [topic] with animation", "explain [concept] visually", "create an educational video", "build a Manim scene", or mentions "reverse knowledge tree", "prerequisite discovery", or "verbose prompt generation". Provides a complete six-agent workflow for transforming any concept into professional Manim animations through recursive prerequisite discovery.
Open repositoryBest for
Primary workflow: Research & Ops.
Technical facets: Full Stack.
Target audience: everyone.
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: HarleyCoops.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install Math-To-Manim into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/HarleyCoops/Math-To-Manim before adding Math-To-Manim to shared team environments
- Use Math-To-Manim for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: Math-To-Manim
description: This skill should be used when the user asks to "create a math animation", "animate a mathematical concept", "generate Manim code", "visualize [topic] with animation", "explain [concept] visually", "create an educational video", "build a Manim scene", or mentions "reverse knowledge tree", "prerequisite discovery", or "verbose prompt generation". Provides a complete six-agent workflow for transforming any concept into professional Manim animations through recursive prerequisite discovery.
version: 1.0.0
---
# Math-To-Manim: Reverse Knowledge Tree Animation Pipeline
Transform any concept into professional mathematical animations using a six-agent workflow that requires NO training data - only pure LLM reasoning.
## Core Innovation: Reverse Knowledge Tree
Instead of training on example animations, this system recursively asks: **"What must I understand BEFORE this concept?"** This builds pedagogically sound animations that flow naturally from foundation concepts to advanced topics.
## When to Use This Skill
Invoke this workflow when:
- Creating mathematical or scientific animations
- Building educational visualizations with Manim
- Generating code from conceptual explanations
- Needing pedagogically structured content progression
## The Six-Agent Pipeline
### Agent 1: ConceptAnalyzer
Parse user intent to extract:
- **Core concept** (specific topic name)
- **Domain** (physics, math, CS, etc.)
- **Level** (beginner/intermediate/advanced)
- **Goal** (learning objective)
### Agent 2: PrerequisiteExplorer (Key Innovation)
Recursively build knowledge tree:
1. Ask: "What are the prerequisites for [concept]?"
2. For each prerequisite, recursively ask the same question
3. Stop when hitting foundation concepts (high school level)
4. Build DAG structure with depth tracking
**Foundation detection criteria**: Would a high school graduate understand this without further explanation?
### Agent 3: MathematicalEnricher
For each node in the tree, add:
- LaTeX equations (2-5 key formulas)
- Variable definitions and interpretations
- Worked examples with typical values
- Complexity-appropriate rigor
### Agent 4: VisualDesigner
For each node, design:
- Visual elements (graphs, 3D objects, diagrams)
- Color scheme (maintain consistency)
- Animation sequences (FadeIn, Transform, etc.)
- Camera movements and transitions
- Duration and pacing
### Agent 5: NarrativeComposer
Walk tree from foundation to target:
1. Topologically sort nodes
2. Generate 200-300 word segment per concept
3. Include exact LaTeX, colors, animations
4. Stitch into 2000+ token verbose prompt
### Agent 6: CodeGenerator
Generate working Manim code:
- Use Manim Community Edition
- Handle LaTeX with raw strings: `r"$\frac{a}{b}$"`
- Implement all visual specifications
- Produce runnable Python file
## Workflow Execution
To execute this workflow for a user request:
### Step 1: Analyze the Concept
```python
# Extract intent
analysis = {
"core_concept": "quantum tunneling",
"domain": "physics/quantum mechanics",
"level": "intermediate",
"goal": "Understand barrier penetration"
}
```
### Step 2: Build Knowledge Tree
Recursively discover prerequisites with max depth of 3-4 levels:
```
Target: quantum tunneling
├─ wave-particle duality
│ ├─ de Broglie wavelength [FOUNDATION]
│ └─ Heisenberg uncertainty
├─ Schrödinger equation
│ ├─ wave function
│ └─ probability density
└─ potential barriers [FOUNDATION]
```
### Step 3: Enrich with Mathematics
Add to each node:
- Primary equations in LaTeX
- Variable definitions
- Physical interpretations
### Step 4: Design Visuals
Specify for each concept:
- Elements: `['wave_function', 'potential_barrier']`
- Colors: `{'wave': 'BLUE', 'barrier': 'RED'}`
- Animations: `['FadeIn', 'Create', 'Transform']`
- Duration: 15-30 seconds per concept
### Step 5: Compose Narrative
Generate verbose prompt with:
- Scene-by-scene instructions
- Exact LaTeX formulas
- Specific animation timings
- Color and position details
### Step 6: Generate Code
Produce complete Python file:
```python
from manim import *
class ConceptAnimation(ThreeDScene):
def construct(self):
# Implementation following verbose prompt
...
```
## Critical Implementation Details
### LaTeX Handling
Always use raw strings for LaTeX:
```python
equation = MathTex(r"E = mc^2")
```
### Color Consistency
Define color palette at scene start and reuse throughout.
### Transition Pattern
Connect concepts with smooth animations:
- Previous concept fades
- New concept builds from prior elements
- Use `Transform` or `ReplacementTransform`
### Verbose Prompt Format
Structure prompts with:
1. Overview section with concept count and duration
2. Scene-by-scene instructions
3. Exact specifications (no ambiguity)
See `references/verbose-prompt-format.md` for complete template.
## Output Files
The pipeline generates:
- `{concept}_prompt.txt` - Verbose prompt
- `{concept}_tree.json` - Knowledge tree structure
- `{concept}_animation.py` - Manim Python code
- `{concept}_result.json` - Complete metadata
## Additional Resources
### Reference Files
- **`references/reverse-knowledge-tree.md`** - Detailed algorithm explanation
- **`references/agent-system-prompts.md`** - All six agent prompts
- **`references/verbose-prompt-format.md`** - Complete prompt template
- **`references/manim-code-patterns.md`** - Code generation patterns
### Example Files
- **`examples/pythagorean-theorem/`** - Complete workflow example
## Quick Start
For immediate use, follow this simplified pattern:
1. **Parse**: Extract the core concept from user input
2. **Discover**: Build prerequisite tree (depth 3-4)
3. **Enrich**: Add math and visual specs to each node
4. **Compose**: Generate verbose prompt (2000+ tokens)
5. **Generate**: Produce working Manim code
The key insight: verbose, specific prompts with exact LaTeX and visual specifications produce dramatically better code than vague descriptions.
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### references/verbose-prompt-format.md
```markdown
# Verbose Prompt Format
The verbose prompt is the bridge between the knowledge tree and working Manim code. A well-structured verbose prompt produces dramatically better animations than vague descriptions.
## Why Verbose Prompts Work
1. **LaTeX forces precision**: Exact mathematical notation leaves no ambiguity
2. **Detailed cinematography**: Specific colors, positions, and timings guide code generation
3. **Sequential structure**: Clear scene ordering produces organized code
4. **Complete specifications**: Nothing left to guess or infer
## Complete Template
```markdown
# Manim Animation: {TARGET_CONCEPT}
## Overview
This animation builds {TARGET_CONCEPT} from first principles through a carefully
constructed knowledge tree. Each concept is explained with mathematical rigor
and visual clarity, building from foundational ideas to advanced understanding.
**Total Concepts**: {CONCEPT_COUNT}
**Progression**: {CONCEPT_1} → {CONCEPT_2} → ... → {TARGET_CONCEPT}
**Estimated Duration**: {TOTAL_SECONDS} seconds ({MINUTES}:{SECONDS:02d})
## Animation Requirements
- Use Manim Community Edition (manim)
- All LaTeX must be in raw strings: r"$\\frac{a}{b}$"
- Use MathTex() for equations, Text() for labels
- Maintain color consistency throughout
- Ensure smooth transitions between scenes
- Include voiceover-friendly pacing (2-3 seconds per concept introduction)
## Scene Sequence
### Scene 1: {CONCEPT_1}
**Timestamp**: 0:00 - 0:15
Begin by fading in the coordinate axes using FadeIn(axes) with WHITE color.
Position the axes at ORIGIN. Next, display the foundational equation
r"$y = mx + b$" using MathTex() in BLUE color, positioning it at the TOP
of the screen using .to_edge(UP).
Create the equation using Write(equation) animation over 2 seconds. Then,
draw a sample line using Create(line) in YELLOW color, showing a concrete
example of y = 2x + 1. Label the line with Text("slope = 2") in GREEN,
positioned to the RIGHT of the line.
Wait 1 second, then fade all elements to prepare for the next concept using
FadeOut(Group(axes, equation, line, label)).
---
### Scene 2: {CONCEPT_2}
**Timestamp**: 0:15 - 0:30
{SIMILAR DETAILED DESCRIPTION}
---
### Scene N: {TARGET_CONCEPT}
**Timestamp**: {START} - {END}
This is the culminating scene. Transform the previous elements to show how
all concepts connect to {TARGET_CONCEPT}. Display the key equation
r"${MAIN_EQUATION}$" prominently in the center using MathTex() with GOLD color.
Highlight the connection to prerequisites by using Indicate() on relevant
terms. Add a final summary text explaining the core insight.
---
## Final Notes
This animation is designed to be pedagogically sound and mathematically rigorous.
The progression from {FIRST_CONCEPT} to {TARGET_CONCEPT} ensures that viewers
have all necessary prerequisites before encountering advanced concepts.
All visual elements, colors, and transitions have been specified to maintain
consistency and clarity throughout the {TOTAL_SECONDS}-second animation.
Generate complete, working Manim Community Edition Python code that implements
this scene sequence with all specified mathematical notation, visual elements,
colors, and animations.
```
## Scene Segment Structure
Each scene segment should include:
### 1. Timestamp Header
```markdown
### Scene 3: Schrödinger Equation
**Timestamp**: 0:30 - 0:45
```
### 2. Opening Action
Start with a verb describing the first animation:
- "Begin by fading in..."
- "Start with the transformation of..."
- "Open by displaying..."
### 3. Equation Display
Include exact LaTeX with positioning:
```
Display the equation r"$i\hbar\frac{\partial}{\partial t}\Psi = \hat{H}\Psi$"
using MathTex() in BLUE color, centered at ORIGIN.
```
### 4. Visual Elements
Specify all objects with:
- Manim class: `MathTex()`, `Text()`, `Axes()`, `Circle()`
- Color: `BLUE`, `RED`, `YELLOW`, etc.
- Position: `ORIGIN`, `UP`, `LEFT`, `.to_edge()`, `.next_to()`
### 5. Animation Sequence
List animations in order:
```
1. FadeIn(axes) over 1 second
2. Write(equation) over 2 seconds
3. Create(graph) following the equation curve
4. Indicate(key_term) with YELLOW highlight
5. Wait 1 second
6. FadeOut(Group(all_elements))
```
### 6. Transition Hook
End with setup for next scene:
```
The equation remains on screen, shifted to the upper left,
as we introduce the next concept.
```
## Color Palette Guidelines
Maintain consistency across scenes:
| Element Type | Recommended Color |
|--------------|-------------------|
| Primary equations | BLUE |
| Secondary equations | YELLOW |
| Axes/grids | WHITE or GREY |
| Graphs/curves | YELLOW, GREEN |
| Labels | GREEN |
| Highlights | GOLD or ORANGE |
| Warnings/errors | RED |
| Success/completion | GREEN |
## Timing Guidelines
| Content Type | Duration |
|--------------|----------|
| Simple equation display | 2-3 seconds |
| Complex equation with explanation | 4-5 seconds |
| Graph/visualization creation | 3-4 seconds |
| Transition between concepts | 1-2 seconds |
| Pause for comprehension | 1 second |
| Complete scene | 15-30 seconds |
## Example: Complete Scene Segment
```markdown
### Scene 4: Wave-Particle Duality
**Timestamp**: 0:45 - 1:05
Begin by transforming the previous probability wave into a particle
representation using ReplacementTransform(wave, particle). The particle
appears as a Dot() in YELLOW at the center of the screen.
Next, display de Broglie's equation r"$\lambda = \frac{h}{p}$" using
MathTex() in BLUE color, positioned at the TOP using .to_edge(UP).
Write the equation over 2 seconds.
Below the equation, create a Text() label explaining each variable:
- r"$\lambda$" = wavelength (GREEN)
- r"$h$" = Planck's constant (YELLOW)
- r"$p$" = momentum (ORANGE)
Position these labels in a VGroup(), arranged vertically with
.arrange(DOWN, buff=0.3), and place them at the RIGHT side of the screen.
Now demonstrate the wave-particle connection: Create a sinusoidal wave
using ParametricFunction() in PURPLE, with amplitude that varies based
on the particle's momentum. Use Create(wave) animation over 3 seconds.
Show that as momentum increases (particle moving faster), wavelength
decreases. Use ValueTracker to animate momentum from 1 to 5, with the
wave responding in real-time using always_redraw().
Conclude by highlighting the key insight: matter has wave properties.
Use Circumscribe(equation) with GOLD color to emphasize the equation,
then FadeOut all elements except the equation, which shifts to upper-left
corner for the next scene.
```
## Common Pitfalls to Avoid
1. **Vague descriptions**: "Show the equation" → "Display r'$E=mc^2$' using MathTex() in BLUE at TOP"
2. **Missing positions**: Always specify where elements appear
3. **Unclear timing**: Include duration for each animation
4. **No transitions**: Explicitly describe how scenes connect
5. **Inconsistent colors**: Define palette and stick to it
6. **Missing LaTeX escaping**: Use raw strings with double backslashes
```
### references/reverse-knowledge-tree.md
```markdown
# Reverse Knowledge Tree Algorithm
The Reverse Knowledge Tree is the core innovation that eliminates the need for training data in generating educational animations.
## The Core Insight
Traditional approaches require training on example animations. This system instead uses pure reasoning:
**For any concept X, recursively ask: "What must I understand BEFORE X?"**
This builds a Directed Acyclic Graph (DAG) of knowledge dependencies that naturally produces pedagogically sound content.
## Algorithm Details
### Data Structure: KnowledgeNode
```python
@dataclass
class KnowledgeNode:
concept: str # The concept name
depth: int # 0 = target, higher = more foundational
is_foundation: bool # True if no further prerequisites needed
prerequisites: List['KnowledgeNode'] # Child nodes
# Added by enrichment agents
equations: Optional[List[str]] # LaTeX equations
definitions: Optional[Dict[str, str]] # Variable definitions
visual_spec: Optional[Dict] # Animation specifications
narrative: Optional[str] # Scene description
```
### Exploration Process
```python
async def explore(concept: str, depth: int = 0) -> KnowledgeNode:
# Check termination conditions
if depth >= max_depth or is_foundation(concept):
return KnowledgeNode(
concept=concept,
depth=depth,
is_foundation=True,
prerequisites=[]
)
# Discover prerequisites via LLM
prerequisites = await discover_prerequisites(concept)
# Recursively explore each prerequisite
child_nodes = []
for prereq in prerequisites:
child_nodes.append(await explore(prereq, depth + 1))
return KnowledgeNode(
concept=concept,
depth=depth,
is_foundation=False,
prerequisites=child_nodes
)
```
### Foundation Detection
A concept is foundational if a typical high school graduate would understand it without further explanation.
**Examples of foundation concepts:**
- velocity, distance, time, acceleration
- force, mass, energy
- waves, frequency, wavelength
- numbers, addition, multiplication
- basic geometry (points, lines, angles)
- functions, graphs
**Examples of non-foundation concepts:**
- Lorentz transformations
- gauge theory
- differential geometry
- tensor calculus
- quantum operators
- Hilbert spaces
### Prerequisite Discovery Prompt
```
You are an expert educator and curriculum designer.
Your task is to identify the ESSENTIAL prerequisite concepts someone must
understand BEFORE they can grasp a given concept.
Rules:
1. Only list concepts that are NECESSARY for understanding (not just helpful)
2. Order from most to least important
3. Assume high school education as baseline
4. Focus on concepts that enable understanding, not historical context
5. Be specific - prefer "special relativity" over "relativity"
6. Limit to 3-5 prerequisites maximum
Return ONLY a JSON array of concept names.
```
## Caching Strategy
To avoid redundant API calls:
1. **In-memory cache**: Store discovered prerequisites by concept name
2. **Optional Atlas integration**: Use Nomic Atlas for semantic caching and search
```python
async def lookup_prerequisites(concept: str) -> List[str]:
# Check cache first
if concept in cache:
return cache[concept]
# Check Atlas if enabled
if atlas_client:
results = atlas_client.search_similar(concept)
if exact_match_found(results):
return results[0].prerequisites
# Discover via LLM
prerequisites = await discover_prerequisites(concept)
# Cache results
cache[concept] = prerequisites
if atlas_client:
atlas_client.store(concept, prerequisites)
return prerequisites
```
## Tree Traversal for Animation
After building the tree, traverse from leaves (foundations) to root (target):
### Topological Sort
```python
def topological_sort(root: KnowledgeNode) -> List[KnowledgeNode]:
visited = set()
result = []
def dfs(node):
if node.concept in visited:
return
visited.add(node.concept)
# Visit prerequisites first (foundations)
for prereq in node.prerequisites:
dfs(prereq)
# Then add this node
result.append(node)
dfs(root)
return result # Foundation → Target order
```
This ensures:
- Foundation concepts appear first in animation
- Each concept builds on previously explained ones
- Viewers have necessary background before advanced topics
## Configuration Options
| Parameter | Default | Description |
|-----------|---------|-------------|
| `max_depth` | 4 | Maximum tree depth before forcing foundation |
| `max_prerequisites` | 5 | Maximum prerequisites per concept |
| `cache_enabled` | True | Use in-memory caching |
| `atlas_enabled` | False | Use Nomic Atlas for persistent caching |
## Example Tree
**Input**: "Explain quantum tunneling"
**Generated Tree**:
```
quantum tunneling (depth 0)
├─ wave-particle duality (depth 1)
│ ├─ de Broglie wavelength (depth 2) [FOUNDATION]
│ └─ Heisenberg uncertainty principle (depth 2)
│ └─ wave function (depth 3) [FOUNDATION]
├─ Schrödinger equation (depth 1)
│ ├─ wave function (depth 2) [FOUNDATION]
│ └─ potential energy (depth 2) [FOUNDATION]
└─ potential barriers (depth 1) [FOUNDATION]
```
**Animation Order** (after topological sort):
1. de Broglie wavelength
2. wave function
3. Heisenberg uncertainty principle
4. wave-particle duality
5. potential energy
6. potential barriers
7. Schrödinger equation
8. quantum tunneling
Each concept builds on what came before, creating a natural learning progression.
```
### references/agent-system-prompts.md
```markdown
# Agent System Prompts
Complete system prompts for all six agents in the Math-To-Manim pipeline.
## Agent 1: ConceptAnalyzer
**Purpose**: Parse user input to extract core concept and metadata.
```
You are an expert at analyzing educational requests and extracting key information.
Analyze the user's question and extract:
1. The MAIN concept they want to understand (be specific)
2. The scientific/mathematical domain
3. The appropriate complexity level
4. Their learning goal
Return ONLY valid JSON with these exact keys:
- core_concept
- domain
- level (must be: "beginner", "intermediate", or "advanced")
- goal
```
**Example Output**:
```json
{
"core_concept": "quantum entanglement",
"domain": "physics/quantum mechanics",
"level": "intermediate",
"goal": "Understand how entangled particles maintain correlation across distances"
}
```
## Agent 2: PrerequisiteExplorer
### Foundation Detection Prompt
```
You are an expert educator analyzing whether a concept is foundational.
A concept is foundational if a typical high school graduate would understand it
without further mathematical or scientific explanation.
Examples of foundational concepts:
- velocity, distance, time, acceleration
- force, mass, energy
- waves, frequency, wavelength
- numbers, addition, multiplication
- basic geometry (points, lines, angles)
- functions, graphs
Examples of non-foundational concepts:
- Lorentz transformations
- gauge theory
- differential geometry
- tensor calculus
- quantum operators
- Hilbert spaces
```
### Prerequisite Discovery Prompt
```
You are an expert educator and curriculum designer.
Your task is to identify the ESSENTIAL prerequisite concepts someone must
understand BEFORE they can grasp a given concept.
Rules:
1. Only list concepts that are NECESSARY for understanding (not just helpful)
2. Order from most to least important
3. Assume high school education as baseline (don't list truly basic things)
4. Focus on concepts that enable understanding, not just historical context
5. Be specific - prefer "special relativity" over "relativity"
6. Limit to 3-5 prerequisites maximum
Return ONLY a JSON array of concept names, nothing else.
```
## Agent 3: MathematicalEnricher
```
You are an expert mathematician and educator specializing in clear mathematical notation.
Your task is to enrich a concept with precise mathematical content suitable
for a Manim animation.
For the given concept, provide:
1. Key equations (2-5 LaTeX formulas with double backslashes)
2. Variable definitions (what each symbol means)
3. Physical/mathematical interpretation
4. One worked example with typical values
Rules:
- Use Manim-compatible LaTeX (double backslashes: \\frac, \\sum, etc.)
- Include units where appropriate
- Adjust complexity to the concept level
- Be precise but not overwhelming
Return JSON with these keys:
- equations: list of LaTeX strings
- definitions: dict mapping symbols to meanings
- interpretation: string explaining what equations represent
- example: worked calculation with numbers
```
**Example Output**:
```json
{
"equations": [
"E = mc^2",
"E^2 = (pc)^2 + (m_0 c^2)^2",
"\\gamma = \\frac{1}{\\sqrt{1 - v^2/c^2}}"
],
"definitions": {
"E": "Total energy",
"m": "Relativistic mass",
"m_0": "Rest mass",
"c": "Speed of light (299,792,458 m/s)",
"v": "Velocity",
"\\gamma": "Lorentz factor"
},
"interpretation": "Mass and energy are equivalent, related by c squared.",
"example": "For m = 1 kg: E = (1 kg)(3×10⁸ m/s)² = 9×10¹⁶ J"
}
```
## Agent 4: VisualDesigner
```
You are an expert Manim animator specializing in educational visualizations.
Design visual specifications for animating the given concept.
For each concept, specify:
1. Visual elements (what objects to create)
2. Color scheme (Manim color constants)
3. Animation sequences (FadeIn, Create, Transform, etc.)
4. Transitions from previous concepts
5. Camera movements (for 3D scenes)
6. Duration and pacing
Rules:
- Use Manim color constants: BLUE, RED, GREEN, YELLOW, PURPLE, ORANGE, WHITE
- Specify positions: LEFT, RIGHT, UP, DOWN, ORIGIN, or coordinates
- Use standard Manim animations: FadeIn, FadeOut, Create, Write, Transform
- Include camera.frame instructions for 3D
- Maintain visual consistency with previous scenes
Return JSON with these keys:
- elements: list of visual elements to create
- colors: dict mapping elements to colors
- animations: list of animation steps
- transitions: how to connect to previous concept
- camera_movement: string describing camera (or "none")
- layout: description of spatial arrangement
- duration: estimated seconds for this scene
```
**Example Output**:
```json
{
"elements": ["equation_main", "graph_function", "axes", "labels"],
"colors": {
"equation_main": "BLUE",
"graph_function": "YELLOW",
"axes": "WHITE",
"labels": "GREEN"
},
"animations": [
"FadeIn(axes)",
"Write(equation_main)",
"Create(graph_function)",
"FadeIn(labels)"
],
"transitions": "Transform previous equation into new form",
"camera_movement": "none",
"layout": "Equation at top, graph centered below",
"duration": 20
}
```
## Agent 5: NarrativeComposer
```
You are an expert educational animator who writes detailed,
LaTeX-rich prompts for Manim Community Edition animations.
Your narrative segments should:
1. Connect naturally to what was just explained
2. Introduce the new concept smoothly
3. Include ALL equations in proper LaTeX format (use double backslashes)
4. Specify exact visual elements, colors, positions
5. Describe animations and transitions precisely
6. Use enthusiastic, second-person teaching tone
7. Be 200-300 words of detailed Manim instructions
Critical: ALL LaTeX must use Manim-compatible syntax with double backslashes.
Format each segment as a complete scene description for Manim.
```
**Segment Request Format**:
```
Write a 200-300 word narrative segment for a Manim animation.
Segment {N} of {total}
Concept: {concept_name}
Previous concepts covered: {list}
{if final: "This is the FINAL segment - the target concept!"}
Mathematical content:
Equations: {equations_json}
Definitions: {definitions_json}
Visual specification:
Elements: {elements_json}
Colors: {colors_json}
Animations: {animations_json}
Layout: {layout}
Duration: {duration} seconds
Write a detailed Manim animation segment that:
1. Starts by connecting to the previous concept (if any)
2. Introduces {concept} naturally
3. Displays the key equations with exact LaTeX notation
4. Specifies colors, positions, and timing
5. Describes each animation step clearly
6. Sets up for the next concept (if not final)
```
## Agent 6: CodeGenerator
```
You are an expert Manim Community Edition animator.
Generate complete, working Python code that implements the animation
described in the prompt.
Requirements:
- Use Manim Community Edition (manim, not manimlib)
- Import: from manim import *
- Create a Scene class (or ThreeDScene for 3D content)
- Use proper LaTeX with raw strings: r"$\\frac{a}{b}$"
- Include all specified visual elements, colors, animations
- Follow the scene sequence exactly
- Ensure code is runnable with: manim -pql file.py SceneName
Code structure:
1. Imports at top
2. Scene class definition
3. construct() method with all animations
4. Helper methods if needed (keep in same class)
Return ONLY the Python code, no explanations.
```
## Temperature Settings
| Agent | Temperature | Rationale |
|-------|-------------|-----------|
| ConceptAnalyzer | 0.3 | Consistent, focused extraction |
| PrerequisiteExplorer (foundation) | 0.0 | Binary yes/no decision |
| PrerequisiteExplorer (discovery) | 0.3 | Balanced creativity/consistency |
| MathematicalEnricher | 0.3 | Accurate mathematics |
| VisualDesigner | 0.5 | Creative but structured |
| NarrativeComposer | 0.7 | Creative narrative flow |
| CodeGenerator | 0.3 | Reliable, working code |
## Token Limits
| Agent | Max Tokens | Purpose |
|-------|------------|---------|
| ConceptAnalyzer | 500 | Short JSON response |
| PrerequisiteExplorer | 500 | JSON array of concepts |
| MathematicalEnricher | 1500 | Equations and definitions |
| VisualDesigner | 1500 | Visual specifications |
| NarrativeComposer | 1500 | 200-300 word segment |
| CodeGenerator | 8000 | Complete Python file |
```
### references/manim-code-patterns.md
```markdown
# Manim Code Patterns
Best practices and patterns for generating high-quality Manim Community Edition code.
## Basic Structure
```python
from manim import *
class ConceptAnimation(Scene): # or ThreeDScene for 3D
def construct(self):
# Setup phase
self.setup_scene()
# Scene 1: Foundation concept
self.scene_foundation()
# Scene 2: Build up
self.scene_buildup()
# Scene 3: Target concept
self.scene_target()
def setup_scene(self):
"""Initialize shared elements and colors"""
self.colors = {
'primary': BLUE,
'secondary': YELLOW,
'highlight': GOLD,
'axes': WHITE
}
def scene_foundation(self):
"""First concept - foundation level"""
pass
def scene_buildup(self):
"""Intermediate concepts"""
pass
def scene_target(self):
"""Final target concept"""
pass
```
## LaTeX Handling
### Always Use Raw Strings
```python
# Correct
equation = MathTex(r"E = mc^2")
fraction = MathTex(r"\frac{a}{b}")
integral = MathTex(r"\int_0^\infty f(x) dx")
# Incorrect - will cause errors
equation = MathTex("E = mc^2") # Works but bad practice
fraction = MathTex("\frac{a}{b}") # FAILS - backslash issues
```
### Complex Equations
```python
# Multi-line equations
schrodinger = MathTex(
r"i\hbar\frac{\partial}{\partial t}\Psi",
r"=",
r"\hat{H}\Psi"
)
# Color specific parts
schrodinger[0].set_color(BLUE) # Left side
schrodinger[2].set_color(GREEN) # Right side
```
### Text with Math
```python
# Use Tex for mixed content
mixed = Tex(r"The energy ", r"$E$", r" equals ", r"$mc^2$")
mixed[1].set_color(BLUE)
mixed[3].set_color(YELLOW)
```
## Animation Patterns
### Sequential Animations
```python
# One after another
self.play(FadeIn(axes))
self.play(Write(equation))
self.play(Create(graph))
self.wait(1)
```
### Simultaneous Animations
```python
# Multiple at once using AnimationGroup
self.play(
FadeIn(axes),
Write(title),
run_time=2
)
# Or comma-separated
self.play(FadeIn(axes), Write(title))
```
### Smooth Transitions
```python
# Transform one object into another
self.play(Transform(old_equation, new_equation))
# Replace without animation artifact
self.play(ReplacementTransform(old, new))
# Fade transition
self.play(FadeOut(old), FadeIn(new))
```
## Positioning Patterns
### Relative Positioning
```python
# Edge positioning
equation.to_edge(UP)
graph.to_edge(LEFT, buff=1)
# Corner positioning
label.to_corner(UR) # Upper right
# Relative to another object
label.next_to(equation, DOWN, buff=0.5)
arrow.next_to(point, RIGHT)
```
### Grouping and Arrangement
```python
# Vertical arrangement
equations = VGroup(eq1, eq2, eq3)
equations.arrange(DOWN, buff=0.5)
equations.to_edge(LEFT)
# Horizontal arrangement
labels = VGroup(l1, l2, l3)
labels.arrange(RIGHT, buff=1)
```
### Coordinate-Based
```python
# Absolute position
point.move_to(np.array([2, 1, 0]))
point.move_to(2*RIGHT + 1*UP)
# Shift relative
equation.shift(2*LEFT + 0.5*UP)
```
## Color Management
### Consistent Color Palette
```python
class ConceptAnimation(Scene):
# Define colors as class attributes
PRIMARY = BLUE
SECONDARY = YELLOW
HIGHLIGHT = GOLD
AXES_COLOR = WHITE
GRAPH_COLOR = GREEN
def construct(self):
equation = MathTex(r"E = mc^2").set_color(self.PRIMARY)
highlight_box = SurroundingRectangle(equation, color=self.HIGHLIGHT)
```
### Color Transitions
```python
# Animate color change
self.play(equation.animate.set_color(RED))
# Highlight temporarily
self.play(
equation.animate.set_color(GOLD),
run_time=0.5
)
self.play(
equation.animate.set_color(BLUE),
run_time=0.5
)
```
## 3D Scene Patterns
### Basic 3D Setup
```python
class ThreeDConcept(ThreeDScene):
def construct(self):
# Set up 3D axes
axes = ThreeDAxes()
# Position camera
self.set_camera_orientation(phi=75*DEGREES, theta=45*DEGREES)
# Add ambient rotation
self.begin_ambient_camera_rotation(rate=0.1)
self.play(Create(axes))
# Create 3D surface
surface = Surface(
lambda u, v: np.array([u, v, np.sin(u)*np.cos(v)]),
u_range=[-3, 3],
v_range=[-3, 3],
resolution=(30, 30)
)
self.play(Create(surface))
self.wait(5)
```
### Camera Movements
```python
# Move camera smoothly
self.move_camera(phi=60*DEGREES, theta=30*DEGREES, run_time=2)
# Zoom
self.move_camera(zoom=1.5, run_time=1)
# Frame movement
self.play(self.camera.frame.animate.shift(2*RIGHT))
```
## Value Tracking and Updates
### Dynamic Updates
```python
# Create tracker
momentum = ValueTracker(1)
# Create object that depends on tracker
wavelength = always_redraw(
lambda: MathTex(
rf"\lambda = {1/momentum.get_value():.2f}"
).to_edge(UP)
)
self.add(wavelength)
# Animate the tracker
self.play(momentum.animate.set_value(5), run_time=3)
```
### Updaters for Continuous Animation
```python
# Add updater to object
dot = Dot()
dot.add_updater(lambda m, dt: m.shift(0.5*RIGHT*dt))
self.add(dot)
self.wait(3) # Dot moves continuously
dot.clear_updaters() # Stop movement
```
## Error Prevention
### Common Fixes
```python
# Problem: LaTeX rendering fails
# Solution: Use raw strings and double backslashes
eq = MathTex(r"\frac{d}{dx}") # Correct
# Problem: Object not visible
# Solution: Check z_index for overlapping
foreground.set_z_index(1)
background.set_z_index(0)
# Problem: Animation too fast/slow
# Solution: Specify run_time
self.play(Create(complex_graph), run_time=3)
# Problem: Jerky transitions
# Solution: Use rate functions
self.play(
Transform(a, b),
rate_func=smooth,
run_time=2
)
```
### Defensive Patterns
```python
# Check object exists before animating
if hasattr(self, 'previous_equation'):
self.play(FadeOut(self.previous_equation))
# Group cleanup
def clear_scene(self):
self.play(*[FadeOut(mob) for mob in self.mobjects])
# Safe color access
color = getattr(self, 'PRIMARY', BLUE)
```
## Scene Organization
### Breaking Complex Animations into Methods
```python
class QuantumTunneling(ThreeDScene):
def construct(self):
self.intro_foundation()
self.show_wave_function()
self.demonstrate_barrier()
self.show_tunneling()
self.conclusion()
def intro_foundation(self):
"""Foundation concepts"""
title = Text("Wave-Particle Duality")
self.play(Write(title))
self.wait(2)
self.play(FadeOut(title))
def show_wave_function(self):
"""Wave function visualization"""
# Detailed implementation
pass
# ... other methods
```
### Reusable Components
```python
def create_labeled_equation(tex_string, label_text, color=BLUE):
"""Create equation with label below"""
equation = MathTex(tex_string).set_color(color)
label = Text(label_text, font_size=24).next_to(equation, DOWN)
return VGroup(equation, label)
# Usage
energy_eq = create_labeled_equation(r"E = mc^2", "Mass-energy equivalence")
self.play(FadeIn(energy_eq))
```
## Rendering Commands
```bash
# Preview quality (fast)
manim -pql animation.py SceneName
# Medium quality
manim -pqm animation.py SceneName
# High quality (slow)
manim -pqh animation.py SceneName
# 4K quality
manim -pqk animation.py SceneName
# Save as GIF
manim -pql --format=gif animation.py SceneName
```
```