【Manim Code Generation Rule: Avoid Markdown Code Block Delimiters in Python Code】
Problem Description A
SyntaxError: invalid syntax
occurs because the generated Python script contains Markdown code block delimiters (```) outside of string literals or comments.Reason The character sequence ```is not recognized as valid Python syntax. It is a formatting element used in Markdown to denote code blocks. Including these delimiters directly in the Python script causes the interpreter to raise a
SyntaxError
.Correct Practice (Must Follow)
- Ensure that the generated script contains only valid Python code.
- Must not include Markdown code block delimiters (
) anywhere in the script except within string literals (e.g., `code_string = """...
python\n..."""`) or as part of comments (e.g., `#
python`). - Review the generated code to remove any instances of ``` that are not part of valid Python syntax.
Correct Code Example
# --- Incorrect Code (Causes SyntaxError) --- # ... (previous code) ... # def some_function(): # print("Hello") # # ``` # Error: Invalid syntax here # # class MyScene(Scene): # ... # --- Correct Code --- # ... (previous code) ... def some_function(): print("Hello") # REMOVED the invalid ``` delimiter class MyScene(Scene): # ... pass # Ensure class is not empty
【Manim Code Generation Rule: Avoid adding non-VMobjects to VGroup when clearing or grouping all scene elements】
Problem Description A
TypeError: Only values of type VMobject can be added as submobjects of VGroup, but the value Mobject (...) is of type Mobject. You can try adding this value into a Group instead.
occurs when attempting to add Mobjects fromself.mobjects
into aVGroup
.Reason The
VGroup
class is specifically designed to contain onlyVMobject
instances (vectorized mobjects). Theself.mobjects
list, however, can contain any type ofMobject
, including non-vectorized types (likeImageMobject
,OpenGLMobject
, or potentially others). Attempting to add a non-VMobject
fromself.mobjects
into aVGroup
using methods like.add()
or by passingself.mobjects
to theVGroup
constructor (VGroup(*self.mobjects)
) violates this type restriction and raises theTypeError
.Correct Practice (Must Follow)
- When you need to group or iterate through all Mobjects currently in the scene (
self.mobjects
), especially for operations like clearing the scene, you must use the more generalGroup
class instead ofVGroup
. - The
Group
class can contain any type ofMobject
. - To group all current mobjects, use
Group(*self.mobjects)
. - To iterate and add mobjects to a container that might include non-VMobjects, initialize a
Group
and use its.add()
method. - Do not use
VGroup(*self.mobjects)
or add elements fromself.mobjects
to aVGroup
if there's a possibility thatself.mobjects
contains non-VMobject
types.
- Correct Code Example
from manim import Scene, VGroup, Group, FadeOut, Circle, ImageMobject # Necessary imports
# Assume you have an ImageMobject or other non-VMobject in the scene
# image = ImageMobject("my_image.png")
# self.add(image)
class MyScene(Scene):
def construct(self):
circle = Circle()
self.add(circle)
# Assume an ImageMobject was added elsewhere or in setup
# self.add(ImageMobject("path/to/image.png")) # This is a non-VMobject
# --- Incorrect Code (Causes TypeError if self.mobjects contains non-VMobjects) ---
# elements_to_remove_bad = VGroup()
# for mob in self.mobjects:
# elements_to_remove_bad.add(mob) # Error if mob is not a VMobject
# --- Correct Code (Using Group to handle all Mobject types) ---
elements_to_remove_good = Group()
for mob in self.mobjects:
elements_to_remove_good.add(mob) # This works for any Mobject type
# Alternative Correct Code (More concise for grouping all)
all_scene_mobjects = Group(*self.mobjects)
# Example usage for clearing:
# self.play(FadeOut(all_scene_mobjects))
# self.clear() # Clears self.mobjects list
self.wait() # Keep scene alive for example
【Manim Code Generation Rule: Ensure Custom Color Variables Are Defined Before Use】
Problem Description A
NameError: name '...' is not defined
occurs when the code attempts to use a custom color variable (e.g.,MY_GREEN
) that has not been assigned a value beforehand.Reason The Python interpreter encountered a variable name (in this case,
MY_GREEN
) that was used (e.g.,MY_FUNCTION_COLOR = MY_GREEN
) but had not been defined anywhere in the accessible scope. This often happens because the variable definition was accidentally omitted, misspelled, or commented out in the custom colors section at the beginning of the script.Correct Practice (Must Follow)
- Before using any custom color variable, must ensure it is explicitly defined and assigned a value in the script.
- Define all custom color constants (like
MY_WHITE
,MY_BLACK
,MY_BLUE
,MY_RED
,MY_GRAY
,MY_GREEN
, etc.) together in a dedicated section near the top of the script (after imports, before class definitions) for clarity and easy management. - Double-check that every custom color variable referenced within the scene's methods or constant definitions has a corresponding, uncommented definition in the custom colors section.
Correct Code Example
# --- Custom Colors --- MY_WHITE = "#FFFFFF" MY_BLACK = "#000000" MY_BLUE = "#0077CC" MY_RED = "#CC3333" MY_GRAY = "#888888" MY_GREEN = "#339933" # <--- MUST ensure this definition exists and is uncommented # Define other colors or variables using the defined colors MY_RELATION_COLOR = MY_BLUE MY_FUNCTION_COLOR = MY_GREEN # <--- Now MY_GREEN is defined # ... other imports and helper functions ... class CombinedScene(Scene): # ... setup method ... def play_section_02(self): # ... other code ... graph = axes.plot(lambda x: x**2, color=MY_FUNCTION_COLOR, x_range=[-2.2, 2.2], use_smoothing=True) # <--- Using the defined variable # ... rest of the method ... # ... other methods ... # ... main execution block ...
【Manim Code Generation Rule: Avoid Passing discontinuous
to Axes.plot
if it Causes TypeError】
Problem Description A
TypeError: Mobject.__init__() got an unexpected keyword argument 'discontinuous'
occurs when attempting to plot a function with discontinuities usingaxes.plot(..., discontinuous=True)
.Reason While
discontinuous
is a valid parameter for theAxes.plot()
method, it appears that in some Manim versions or contexts, this parameter is incorrectly propagated down to the underlyingParametricFunction
orVMobject
constructor (or their base classMobject
), which does not acceptdiscontinuous
as a keyword argument during initialization. This leads to theTypeError
.Correct Practice (Must Follow)
- If using
axes.plot(..., discontinuous=True)
results in aTypeError
related to thediscontinuous
keyword argument, you must remove thediscontinuous=True
parameter from theaxes.plot()
call. - To correctly represent a function with discontinuities (like
1/(x-2)
), you must manually plot the function over separatex_range
segments that exclude the point(s) of discontinuity. - For a function like
f(x) = 1/(x-2)
, the discontinuity is atx=2
. You would plot the function twice: once forx < 2
and once forx > 2
, using appropriatex_range
values for each segment.
- Correct Code Example
from manim import Axes, MathTex, VGroup, FadeIn, Create, Indicate, config, MY_BLUE, MY_BLACK, MY_HIGHLIGHT_RED # Necessary imports
import numpy as np # Needed for ranges
# Assume axes are defined and positioned correctly
# axes = Axes(...)
# --- Incorrect Code (Causes TypeError) ---
# graph_bad = axes.plot(lambda x: 1/(x-2), color=MY_BLUE, x_range=[-5, 5, 0.01], discontinuous=True) # Error here
# --- Correct Code ---
# Manually define ranges around the discontinuity at x=2
x_range_left = [-5, 2 - 1e-9, 0.01] # Range up to just before 2
x_range_right = [2 + 1e-9, 5, 0.01] # Range from just after 2
# Plot the function over the left segment
graph_left = axes.plot(lambda x: 1/(x-2), color=MY_BLUE, x_range=x_range_left)
# Plot the function over the right segment
graph_right = axes.plot(lambda x: 1/(x-2), color=MY_BLUE, x_range=x_range_right)
# Group the two segments to treat the whole graph as one object for animations/positioning
graph = VGroup(graph_left, graph_right)
# Example usage in a scene:
# self.play(Create(axes))
# self.play(Create(graph)) # Creates both segments
# self.wait()
【Manim Code Generation Rule: Safely Accessing Parts within a Text Mobject】
Problem Description A
TypeError: Mobject.__getattr__.<locals>.getter() takes 1 positional argument but 2 were given
occurs when attempting to callText.get_part_by_text()
orText.get_parts_by_text()
.Reason This error indicates an issue within Manim's internal mechanism for accessing parts of a
Text
object, potentially related to its internal structure or state after creation/addition to a group. Relying onget_part_by_text
orget_parts_by_text
forText
objects might be unstable or not fully supported in this environment, leading to unexpected argument passing errors internally.Correct Practice (Must Follow) To reliably access specific lines or parts of text within a
Text
Mobject, must avoid usingText.get_part_by_text()
orText.get_parts_by_text()
directly on theText
object itself if this error occurs. Instead, iterate through theText
object's submobjects (which are typically the individual characters or words) and perform text matching by checking the.text
attribute of each submobject.Correct Code Example
from manim import Text, VGroup, Indicate, FadeIn, FadeOut, AnimationGroup # Necessary imports
# Assume summary_vertex is a valid Text Mobject instance created earlier
summary_vertex = Text("• Vertex moves from (0,0) to (h,k).", font_size=28, color=MY_BLACK, width=config.frame_width - 2)
# --- Incorrect Code (Causes TypeError) ---
# h_part = summary_vertex.get_part_by_text("h")
# k_part = summary_vertex.get_part_by_text("k")
# --- Correct Code ---
# Initialize variables to hold the found Mobjects
h_part = None
k_part = None
# Iterate through the submobjects (characters/groups) of the Text object
# The submobjects of a Text object are typically the individual characters or words
for submob in summary_vertex.submobjects:
# Check the text content of the submobject using its .text attribute
if "h" in submob.text:
h_part = submob
if "k" in submob.text:
k_part = submob
# Now use the found Mobjects for animations or coloring
if h_part:
h_part.set_color(MY_ORANGE)
if k_part:
k_part.set_color(MY_BLUE)
# Example usage for animation:
# if h_part:
# self.play(Indicate(h_part))
# if k_part:
# self.play(Indicate(k_part))