A community-maintained Python framework for creating mathematical animations.
Refactored docstrings in mod:`manim.mobject.geometry` (#2560)
ad_chaos9e19f8c2d10f
diff --git a/docs/source/conf.py b/docs/source/conf.pyindex bc70e78d9..8d5ee6a2b 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -71,7 +71,7 @@ napoleon_custom_sections = ["Tests", ("Test", "Tests")]# This pattern also affects html_static_path and html_extra_path.html_extra_path = ["robots.txt"]-exclude_patterns: list = []+exclude_patterns: list[str] = []# -- Options for internationalization ----------------------------------------# Set the destination directory of the localized po filesdiff --git a/manim/mobject/geometry/arc.py b/manim/mobject/geometry/arc.pyindex c639d2d9b..bfc704f52 100644--- a/manim/mobject/geometry/arc.py+++ b/manim/mobject/geometry/arc.py@@ -2,7 +2,6 @@ r"""Mobjects that are curved.Examples---------.. manim:: UsefulAnnotations:save_last_frame:@@ -46,9 +45,10 @@ __all__ = [import itertoolsimport mathimport warnings-from typing import Sequence+from typing import TYPE_CHECKING, Sequenceimport numpy as np+from colour import Colorfrom manim.constants import *from manim.mobject.opengl.opengl_compatibility import ConvertToOpenGL@@ -63,10 +63,14 @@ from manim.utils.space_ops import (rotate_vector,)+if TYPE_CHECKING:+ from manim.mobject.mobject import Mobject+ from manim.mobject.text.tex_mobject import SingleStringMathTex, Tex+ from manim.mobject.text.text_mobject import Text+class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):- """- Meant for shared functionality between Arc and Line.+ """Meant for shared functionality between Arc and Line.Functionality can be classified broadly into these groups:* Adding, Creating, Modifying tips@@ -81,7 +85,6 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):* Getters- Straightforward accessors, returning information pertainingto the TipableVMobject instance's tip(s), its length etc-"""def __init__(@@ -99,8 +102,7 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):# Adding, Creating, Modifying tipsdef add_tip(self, tip=None, tip_shape=None, tip_length=None, at_start=False):- """- Adds a tip to the TipableVMobject instance, recognising+ """Adds a tip to the TipableVMobject instance, recognisingthat the endpoints might need to be switched if it'sa 'starting tip' or not."""@@ -114,8 +116,7 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):return selfdef create_tip(self, tip_shape=None, tip_length=None, at_start=False):- """- Stylises the tip, positions it spatially, and returns+ """Stylises the tip, positions it spatially, and returnsthe newly instantiated tip to the caller."""tip = self.get_unpositioned_tip(tip_shape, tip_length)@@ -123,8 +124,7 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):return tipdef get_unpositioned_tip(self, tip_shape=None, tip_length=None):- """- Returns a tip that has been stylistically configured,+ """Returns a tip that has been stylistically configured,but has not yet been given a position in space."""from manim.mobject.geometry.tips import ArrowTriangleFilledTip@@ -207,8 +207,7 @@ class TipableVMobject(VMobject, metaclass=ConvertToOpenGL):return resultdef get_tips(self):- """- Returns a VGroup (collection of VMobjects) containing+ """Returns a VGroup (collection of VMobjects) containingthe TipableVMObject instance's tips."""result = self.get_group_class()()@@ -351,8 +350,7 @@ class Arc(TipableVMobject):self.set_anchors_and_handles(anchors[:-1], handles1, handles2, anchors[1:])def get_arc_center(self, warning=True):- """- Looks at the normals to the first two+ """Looks at the normals to the first twoanchors, and finds their intersection points"""# First two anchors and handles@@ -386,11 +384,10 @@ class Arc(TipableVMobject):class ArcBetweenPoints(Arc):- """- Inherits from Arc and additionally takes 2 points between which the arc is spanned.+ """Inherits from Arc and additionally takes 2 points between which the arc is spanned.Example- --------------------+ -------.. manim:: ArcBetweenPointsExampleclass ArcBetweenPointsExample(Scene):@@ -460,14 +457,13 @@ class Circle(Arc):Parameters----------- color : :class:`~.Colors`, optional+ colorThe color of the shape.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Arc`Examples---------.. manim:: CircleExample:save_last_frame:@@ -483,8 +479,8 @@ class Circle(Arc):def __init__(self,- radius: float = None,- color=RED,+ radius: float | None = None,+ color: Color | str = RED,**kwargs,):super().__init__(@@ -495,22 +491,27 @@ class Circle(Arc):**kwargs,)- def surround(self, mobject, dim_to_match=0, stretch=False, buffer_factor=1.2):+ def surround(+ self,+ mobject: Mobject,+ dim_to_match: int = 0,+ stretch: bool = False,+ buffer_factor: float = 1.2,+ ):"""Modifies a circle so that it surrounds a given mobject.Parameters----------- mobject : :class:`~.Mobject`+ mobjectThe mobject that the circle will be surrounding.- dim_to_match : :class:`int`, optional- buffer_factor : :class:`float`, optional+ dim_to_match+ buffer_factorScales the circle with respect to the mobject. A `buffer_factor` < 1 makes the circle smaller than the mobject.- stretch : :class:`bool`, optional+ stretchStretches the circle to fit more tightly around the mobject. Note: Does not work with :class:`Line`Examples---------.. manim:: CircleSurround:save_last_frame:@@ -543,17 +544,21 @@ class Circle(Arc):self.width = np.sqrt(mobject.width**2 + mobject.height**2)return self.scale(buffer_factor)- def point_at_angle(self, angle):+ def point_at_angle(self, angle: float):"""Returns the position of a point on the circle.Parameters----------- angle : class: `float`+ angleThe angle of the point along the circle in radians.+ Returns+ -------+ :class:`numpy.ndarray`+ The location of the point along the circle's circumference.+Examples---------.. manim:: PointAtAngleExample:save_last_frame:@@ -567,10 +572,6 @@ class Circle(Arc):s2 = Square(side_length=0.25).move_to(p2)self.add(circle, s1, s2)- Returns- -------- :class:`numpy.ndarray`- The location of the point along the circle's circumference."""start_angle = angle_of_vector(self.points[0] - self.get_center())@@ -585,7 +586,6 @@ class Circle(Arc):Example--------.. manim:: CircleFromPointsExample:save_last_frame:@@ -612,22 +612,21 @@ class Dot(Circle):Parameters----------- point : Union[:class:`list`, :class:`numpy.ndarray`], optional+ pointThe location of the dot.- radius : Optional[:class:`float`]+ radiusThe radius of the dot.- stroke_width : :class:`float`, optional+ stroke_widthThe thickness of the outline of the dot.- fill_opacity : :class:`float`, optional+ fill_opacityThe opacity of the dot's fill_colour- color : :class:`~.Colors`, optional+ colorThe color of the dot.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Circle`Examples---------.. manim:: DotExample:save_last_frame:@@ -641,11 +640,11 @@ class Dot(Circle):def __init__(self,- point=ORIGIN,+ point: list | np.ndarray = ORIGIN,radius: float = DEFAULT_DOT_RADIUS,- stroke_width=0,- fill_opacity=1.0,- color=WHITE,+ stroke_width: float = 0,+ fill_opacity: float = 1.0,+ color: Color | str = WHITE,**kwargs,):super().__init__(@@ -659,9 +658,7 @@ class Dot(Circle):class AnnotationDot(Dot):- """- A dot with bigger radius and bold stroke to annotate scenes.- """+ """A dot with bigger radius and bold stroke to annotate scenes."""def __init__(self,@@ -685,19 +682,17 @@ class LabeledDot(Dot):Parameters----------- label : Union[:class:`str`, :class:`~.SingleStringMathTex`, :class:`~.Text`, :class:`~.Tex`]+ labelThe label of the :class:`Dot`. This is rendered as :class:`~.MathTex`by default (i.e., when passing a :class:`str`), but other classesrepresenting rendered strings like :class:`~.Text` or :class:`~.Tex`can be passed as well.-- radius : :class:`float`+ radiusThe radius of the :class:`Dot`. If ``None`` (the default), the radiusis calculated based on the size of the ``label``.Examples---------.. manim:: SeveralLabeledDots:save_last_frame:@@ -716,7 +711,12 @@ class LabeledDot(Dot):self.add(dot1, dot2, dot3, dot4)"""- def __init__(self, label, radius=None, **kwargs) -> None:+ def __init__(+ self,+ label: str | SingleStringMathTex | Text | Tex,+ radius: float | None = None,+ **kwargs,+ ) -> None:if isinstance(label, str):from manim import MathTex@@ -736,16 +736,15 @@ class Ellipse(Circle):Parameters----------- width : :class:`float`, optional+ widthThe horizontal width of the ellipse.- height : :class:`float`, optional+ heightThe vertical height of the ellipse.- kwargs : Any- Additional arguments to be passed to :class:`Circle`+ kwargs+ Additional arguments to be passed to :class:`Circle`.Examples---------.. manim:: EllipseExample:save_last_frame:@@ -757,7 +756,7 @@ class Ellipse(Circle):self.add(ellipse_group)"""- def __init__(self, width=2, height=1, **kwargs):+ def __init__(self, width: float = 2, height: float = 1, **kwargs):super().__init__(**kwargs)self.stretch_to_fit_width(width)self.stretch_to_fit_height(height)@@ -765,7 +764,6 @@ class Ellipse(Circle):class AnnularSector(Arc):"""-Parameters----------inner_radius@@ -806,8 +804,6 @@ class AnnularSector(Arc):s4 = AnnularSector(inner_radius=1, outer_radius=1.5, angle=-3 * PI / 2, color=GREEN).move_to(2 * DR)self.add(s1, s2, s3, s4)--"""def __init__(@@ -853,10 +849,8 @@ class AnnularSector(Arc):class Sector(AnnularSector):"""-Examples---------.. manim:: ExampleSector:save_last_frame:@@ -882,12 +876,11 @@ class Annulus(Circle):The radius of the inner :class:`Circle`.outer_radiusThe radius of the outer :class:`Circle`.- kwargs : Any+ kwargsAdditional arguments to be passed to :class:`Annulus`Examples---------.. manim:: AnnulusExample:save_last_frame:@@ -931,7 +924,6 @@ class CubicBezier(VMobject, metaclass=ConvertToOpenGL):"""Example--------.. manim:: BezierSplineExample:save_last_frame:@@ -964,32 +956,17 @@ class ArcPolygon(VMobject, metaclass=ConvertToOpenGL):use across all arcs, but to configure arcs individually an ``arc_config`` listhas to be passed with the syntax explained below.- .. tip::-- Two instances of :class:`ArcPolygon` can be transformed properly into one- another as well. Be advised that any arc initialized with ``angle=0``- will actually be a straight line, so if a straight section should seamlessly- transform into an arced section or vice versa, initialize the straight section- with a negligible angle instead (such as ``angle=0.0001``).-- There is an alternative version (:class:`ArcPolygonFromArcs`) that is instantiated- with pre-defined arcs.-- See Also- --------- :class:`ArcPolygonFromArcs`-Parameters----------- vertices : Union[:class:`list`, :class:`np.array`]+ verticesA list of vertices, start and end points for the arc segments.- angle : :class:`float`+ angleThe angle used for constructing the arcs. If no other parametersare set, this angle is used to construct all arcs.- radius : Optional[:class:`float`]+ radiusThe circle radius used to construct the arcs. If specified,overrides the specified ``angle``.- arc_config : Optional[Union[List[:class:`dict`]], :class:`dict`]+ arc_configWhen passing a ``dict``, its content will be passed as keywordarguments to :class:`~.ArcBetweenPoints`. Otherwise, a listof dictionaries containing values that are passed as keyword@@ -1008,9 +985,26 @@ class ArcPolygon(VMobject, metaclass=ConvertToOpenGL):>>> ap.arcs[ArcBetweenPoints, ArcBetweenPoints, ArcBetweenPoints]- Examples++ .. tip::++ Two instances of :class:`ArcPolygon` can be transformed properly into one+ another as well. Be advised that any arc initialized with ``angle=0``+ will actually be a straight line, so if a straight section should seamlessly+ transform into an arced section or vice versa, initialize the straight section+ with a negligible angle instead (such as ``angle=0.0001``).++ .. note::+ There is an alternative version (:class:`ArcPolygonFromArcs`) that is instantiated+ with pre-defined arcs.++ See Also--------+ :class:`ArcPolygonFromArcs`++ Examples+ --------.. manim:: SeveralArcPolygonsclass SeveralArcPolygons(Scene):@@ -1032,7 +1026,14 @@ class ArcPolygon(VMobject, metaclass=ConvertToOpenGL):For further examples see :class:`ArcPolygonFromArcs`."""- def __init__(self, *vertices, angle=PI / 4, radius=None, arc_config=None, **kwargs):+ def __init__(+ self,+ *vertices: list | np.ndarray,+ angle: float = PI / 4,+ radius: float | None = None,+ arc_config: list[dict] | None = None,+ **kwargs,+ ):n = len(vertices)point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)]@@ -1080,24 +1081,9 @@ class ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL):sections. Arcs can also be passed as straight lines such as an arcinitialized with ``angle=0``.- .. tip::-- Two instances of :class:`ArcPolygon` can be transformed properly into- one another as well. Be advised that any arc initialized with ``angle=0``- will actually be a straight line, so if a straight section should seamlessly- transform into an arced section or vice versa, initialize the straight- section with a negligible angle instead (such as ``angle=0.0001``).-- There is an alternative version (:class:`ArcPolygon`) that can be instantiated- with points.-- See Also- --------- :class:`ArcPolygon`-Parameters----------- arcs : Union[:class:`Arc`, :class:`ArcBetweenPoints`]+ arcsThese are the arcs from which the arcpolygon is assembled.kwargsKeyword arguments that are passed to the constructor of@@ -1106,7 +1092,7 @@ class ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL):Attributes----------- arcs : :class:`list`+ arcsThe arcs used to initialize the ArcPolygonFromArcs::>>> from manim import ArcPolygonFromArcs, Arc, ArcBetweenPoints@@ -1114,6 +1100,22 @@ class ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL):>>> ap.arcs[Arc, ArcBetweenPoints, Arc]++ .. tip::++ Two instances of :class:`ArcPolygon` can be transformed properly into+ one another as well. Be advised that any arc initialized with ``angle=0``+ will actually be a straight line, so if a straight section should seamlessly+ transform into an arced section or vice versa, initialize the straight+ section with a negligible angle instead (such as ``angle=0.0001``).++ .. note::+ There is an alternative version (:class:`ArcPolygon`) that can be instantiated+ with points.++ .. seealso::+ :class:`ArcPolygon`+Examples--------One example of an arcpolygon is the Reuleaux triangle.@@ -1167,10 +1169,9 @@ class ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL):reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf)self.play(FadeIn(reuleaux_tri))self.wait(2)-"""- def __init__(self, *arcs, **kwargs):+ def __init__(self, *arcs: Arc | ArcBetweenPoints, **kwargs):if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs):raise ValueError("All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints",diff --git a/manim/mobject/geometry/boolean_ops.py b/manim/mobject/geometry/boolean_ops.pyindex 32dfbfcf6..a7900339b 100644--- a/manim/mobject/geometry/boolean_ops.py+++ b/manim/mobject/geometry/boolean_ops.py@@ -33,23 +33,23 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL)::attr:`z_dim` as the z coordinate.Parameters- ==========+ ----------points:An iterable which has the coordinates.z_dim:The default value of z coordinate.+ Returns+ -------+ typing.List[np.ndarray]+ A list of array converted to 3d.+Example- =======+ ------->>> a = _BooleanOps()>>> p = [(1, 2), (3, 4)]>>> a._convert_2d_to_3d_array(p)[array([1., 2., 0.]), array([3., 4., 0.])]-- Returns- =======- typing.List[np.ndarray]- A list of array converted to 3d."""points = list(points)for i, point in enumerate(points):@@ -62,12 +62,12 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):cairo renderer because it treats the points as Cubic beizer curves.Parameters- ==========+ ----------vmobject:The :class:`~.VMobject` to convert from.Returns- =======+ -------SkiaPath:The converted path."""@@ -109,12 +109,12 @@ class _BooleanOps(VMobject, metaclass=ConvertToOpenGL):def _convert_skia_path_to_vmobject(self, path: SkiaPath) -> VMobject:"""Converts SkiaPath back to VMobject.Parameters- ==========+ ----------path:The SkiaPath to convert.Returns- =======+ -------VMobject:The converted VMobject."""@@ -149,18 +149,17 @@ class Union(_BooleanOps):the :class:`~VMobject` s.Parameters- ==========+ ----------vmobjectsThe :class:`~.VMobject` s to find the union of.Raises- ======+ ------ValueErrorIf less than 2 :class:`~.VMobject` s are passed.Example- =======-+ -------.. manim:: UnionExample:save_last_frame:@@ -192,14 +191,14 @@ class Difference(_BooleanOps):"""Subtracts one :class:`~.VMobject` from another one.Parameters- ==========+ ----------subjectThe 1st :class:`~.VMobject`.clipThe 2nd :class:`~.VMobject`Example- =======+ -------.. manim:: DifferenceExample:save_last_frame:@@ -231,17 +230,17 @@ class Intersection(_BooleanOps):This keeps the parts covered by both :class:`~.VMobject` s.Parameters- ==========+ ----------vmobjectsThe :class:`~.VMobject` to find the intersection.Raises- ======+ ------ValueErrorIf less the 2 :class:`~.VMobject` are passed.Example- =======+ -------.. manim:: IntersectionExample:save_last_frame:@@ -287,15 +286,14 @@ class Exclusion(_BooleanOps):covered by exactly one of them.Parameters- ==========+ ----------subjectThe 1st :class:`~.VMobject`.clipThe 2nd :class:`~.VMobject`Example- =======-+ -------.. manim:: IntersectionExample:save_last_frame:diff --git a/manim/mobject/geometry/line.py b/manim/mobject/geometry/line.pyindex 77f6eab09..76e17cc28 100644--- a/manim/mobject/geometry/line.py+++ b/manim/mobject/geometry/line.py@@ -14,7 +14,7 @@ __all__ = ["RightAngle",]-from typing import Sequence, Union+from typing import Sequenceimport numpy as npfrom colour import Color@@ -115,6 +115,7 @@ class Line(TipableVMobject):def put_start_and_end_on(self, start: Sequence[float], end: Sequence[float]):"""Sets starts and end coordinates of a line.+Examples--------.. manim:: LineExample@@ -159,7 +160,6 @@ class Line(TipableVMobject):----------pointThe point to which the line is projected.-"""start = self.get_start()@@ -199,6 +199,10 @@ class DashedLine(Line):kwargs : AnyAdditional arguments to be passed to :class:`Line`++ .. seealso::+ :class:`~.DashedVMobject`+Examples--------.. manim:: DashedLineExample@@ -213,10 +217,6 @@ class DashedLine(Line):# dashed_ratio decreaseddashed_3 = DashedLine(config.left_side, config.right_side, dashed_ratio=0.1).shift(DOWN*2)self.add(dashed_1, dashed_2, dashed_3)-- See Also- --------- :class:`~.DashedVMobject`"""def __init__(@@ -329,9 +329,12 @@ class TangentLine(Line):kwargs : AnyAdditional arguments to be passed to :class:`Line`++ .. seealso::+ :meth:`~.VMobject.point_from_proportion`+Examples---------.. manim:: TangentLineExample:save_last_frame:@@ -341,10 +344,6 @@ class TangentLine(Line):line_1 = TangentLine(circle, alpha=0.0, length=4, color=BLUE_D) # rightline_2 = TangentLine(circle, alpha=0.4, length=4, color=GREEN) # top leftself.add(circle, line_1, line_2)-- See Also- --------- :meth:`~.VMobject.point_from_proportion`"""def __init__(self, vmob, alpha, length=1, d_alpha=1e-6, **kwargs):@@ -371,9 +370,11 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):kwargs : AnyAdditional arguments to be passed to :class:`~.VMobject`+ .. seealso::+ :class:`RightAngle`+Examples---------.. manim:: ElbowExample:save_last_frame:@@ -385,10 +386,6 @@ class Elbow(VMobject, metaclass=ConvertToOpenGL):elbow_group = Group(elbow_1, elbow_2, elbow_3).arrange(buff=1)self.add(elbow_group)-- See Also- --------- :class:`RightAngle`"""def __init__(self, width=0.2, angle=0, **kwargs):@@ -417,9 +414,13 @@ class Arrow(Line):kwargs : AnyAdditional arguments to be passed to :class:`Line`.++ .. seealso::+ :class:`ArrowTip`+ :class:`CurvedArrow`+Examples---------.. manim:: ArrowExample:save_last_frame:@@ -481,12 +482,6 @@ class Arrow(Line):DR_group.move_to(4 * RIGHT + 2 * DOWN)self.add(left_group, middle_group, UR_group, DR_group)--- See Also- --------- :class:`ArrowTip`- :class:`CurvedArrow`"""def __init__(@@ -511,9 +506,9 @@ class Arrow(Line):def scale(self, factor, scale_tips=False, **kwargs):r"""Scale an arrow, but keep stroke width and arrow tip size fixed.- See Also- --------- :meth:`~.Mobject.scale`++ .. seealso::+ :meth:`~.Mobject.scale`Examples--------@@ -622,7 +617,6 @@ class Vector(Arrow):Examples---------.. manim:: VectorExample:save_last_frame:@@ -661,9 +655,13 @@ class Vector(Arrow):kwargsAdditional arguments to be passed to :class:`~.Matrix`.+ Returns+ -------+ :class:`~.Matrix`+ The label.+Examples---------.. manim:: VectorCoordinateLabel:save_last_frame:@@ -677,11 +675,6 @@ class Vector(Arrow):label_2 = vec_2.coordinate_label(color=YELLOW)self.add(plane, vec_1, vec_2, label_1, label_2)-- Returns- -------- :class:`~.Matrix`- The label."""# avoiding circular imports@@ -716,9 +709,13 @@ class DoubleArrow(Arrow):kwargs : AnyAdditional arguments to be passed to :class:`Arrow`++ .. seealso::+ :class:`.~ArrowTip`+ :class:`.~CurvedDoubleArrow`+Examples---------.. manim:: DoubleArrowExample:save_last_frame:@@ -745,11 +742,6 @@ class DoubleArrow(Arrow):d3 = DoubleArrow(p1, p2, buff=0, tip_length=0.4, color=BLUE)Group(d1, d2, d3).arrange(DOWN)self.add(box, d1, d2, d3)-- See Also- --------- :class:`ArrowTip`- :class:`CurvedDoubleArrow`"""def __init__(self, *args, **kwargs):@@ -1029,18 +1021,17 @@ class RightAngle(Angle):Parameters----------- line1 : :class:`Line`+ line1The first line.- line2 : :class:`Line`+ line2The second line.- length : :class:`float`+ lengthThe length of the arms.**kwargsFurther keyword arguments that are passed to the constructor of :class:`Angle`.Examples---------.. manim:: RightAngleExample:save_last_frame:@@ -1062,5 +1053,5 @@ class RightAngle(Angle):self.add(plots)"""- def __init__(self, line1, line2, length=None, **kwargs):+ def __init__(self, line1: Line, line2: Line, length: float | None = None, **kwargs):super().__init__(line1, line2, radius=length, elbow=True, **kwargs)