Skip to content

The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.

Python

Add coordinate systems and graph layouts

Sina Atalay67adac462186
diff --git a/src/manimgx/mobject.py b/src/manimgx/mobject.py
index 5bfb1afd..c1f7d391 100644
--- a/src/manimgx/mobject.py
+++ b/src/manimgx/mobject.py
@@ -1,3 +1,8 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
"Mutable scene objects: one family graph, shared geometry and paint, and path, point and mesh leaf rules."
import copy
@@ -26,6 +31,7 @@ from typing import (
cast,
overload,
)
+from warnings import deprecated
import numpy as np
import numpy.typing as npt
@@ -57,12 +63,12 @@ from manimgx.drawing.geometry import (
_NPPCC,
EMPTY,
Blend,
+ Lattice,
Path,
_pathops,
bezier,
bezier_remap,
get_smooth_cubic_bezier_handle_points,
- grid_triangles,
integer_interpolate,
interpolate,
linear_about,
@@ -607,6 +613,7 @@ def style_defaults(cls: "type[Mobject]") -> Style:
return cached
+@deprecated("use list(dict.fromkeys(items))", category=None)
def remove_list_redundancies[T](items: Sequence[T]) -> list[T]:
"""The items without repeats: each one once, where it last occurs.
@@ -653,8 +660,8 @@ def _family(roots: Iterable["Mobject"]) -> list["Mobject"]:
def _family_box(family: Iterable["Mobject"]) -> np.ndarray | None:
"""Combine the selected family's own geometry boxes without constructing a group."""
- # A member's box belongs to its geometry; paths use their curves' tight bounds.
- boxes = [m._geometry.box(m._curves) for m in family if m._geometry.n]
+ # A member's box is what it draws (`_box`); paths use their curves' tight bounds.
+ boxes = [b for m in family if m._geometry.n and (b := m._box()) is not None]
if len(boxes) < 2:
return boxes[0] if boxes else None
stacked = np.array(boxes)
@@ -665,7 +672,8 @@ class Mobject:
"""The object everything in a scene is made of: shapes, text, groups, trackers.
A mobject has points in scene coordinates (x to the right, y up, z out of the
- screen; the frame is 8 units tall and about 14.2 wide, centered on the origin);
+ screen; the frame is 8 units on its short side, about 14.2 × 8 at 16:9, centered
+ on the origin);
submobjects, a tree drawn and moved with it; a style: its fill, its stroke and their
colors; updaters, which change it as time passes; and a z-index, its place in the
drawing order. You make one through its subclasses — [`Circle`][manimgx.Circle],
@@ -687,9 +695,8 @@ class Mobject:
animation_overrides: ClassVar[
dict[type["Animation"], Callable[..., "Animation"]]
] = {}
- """The animations the class plays another in place of: each animation class, with
- the function that makes the one played instead (see
- [override_animation][manimgx.override_animation])."""
+ # The animations the class plays another in place of: each animation class, with the
+ # function that makes the one played instead (see `override_animation`).
defaults: ClassVar[Style] = {}
"""The style keywords whose defaults the class changes: a subclass lists only what
it changes (`defaults = {"color": BLUE}`), and takes the rest from its parents (see
@@ -786,6 +793,7 @@ class Mobject:
self.init_colors()
# ── kind hooks ─────────────────────────────────────────────────────────
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def generate_points(self) -> Self:
"""Build the mobject's points: its shape.
@@ -794,6 +802,7 @@ class Mobject:
"""
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def init_points(self) -> Self:
"""Build the mobject's points: the same as
[generate_points][manimgx.Mobject.generate_points], by another name.
@@ -802,6 +811,7 @@ class Mobject:
self.generate_points()
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def init_colors(self, propagate_colors: bool = True) -> Self:
"""Paint the mobject with its style.
@@ -886,6 +896,7 @@ class Mobject:
# its points are cubic curves' control points (a path): its box is its curves' tight box
_curves: ClassVar[bool] = False
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_points_defining_boundary(self) -> Point3D_Array:
"""The points [get_boundary_point][manimgx.Mobject.get_boundary_point] chooses
among: every point of the mobject's family — or, for a path, its members'
@@ -906,6 +917,7 @@ class Mobject:
]
return np.concatenate(arrays) if arrays else np.zeros((0, 3))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def align_points_with_larger(self, larger: "Mobject") -> Self:
"""Give the mobject as many points as `larger`, its shape unchanged, so the two
can be blended point by point.
@@ -919,6 +931,7 @@ class Mobject:
"""
raise NotImplementedError(f"{type(self).__name__} cannot align points")
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_point_mobject(self, center: Point3DLike | None = None) -> "Mobject":
"""The mobject shrunk to a point: what it grows from, or shrinks to, when a
transform makes it appear or disappear.
@@ -935,9 +948,12 @@ class Mobject:
c = self.get_center() if center is None else center
return Group(*(m.get_point_mobject(c) for m in self.submobjects))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def pointwise_become_partial(self, mobject: "Mobject", a: float, b: float) -> Self:
"""Become a part of another mobject: its points from proportion `a` of the way
- along it to proportion `b` (a path's, by its curves).
+ along it to proportion `b`, as a reveal over that stretch shows it: a path's
+ curves, cut where `a` and `b` fall; a cloud's points, a mesh's triangles and a
+ surface's faces whole, every one the stretch reaches into.
[get_pieces][manimgx.Mobject.get_pieces] calls it. Each kind implements it; a
mobject of no kind stays as it is.
@@ -949,6 +965,7 @@ class Mobject:
"""
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def reveal_pace(self) -> tuple[np.ndarray, np.ndarray] | None:
"""How a reveal ([Create][manimgx.Create], [Write][manimgx.Write], …) moves
through the mobject: evenly by its parts, or, for a path, by arc length, so it
@@ -957,8 +974,9 @@ class Mobject:
The reveal animations read it for each drawn member.
Returns:
- None for evenly by part (points in order, triangles in order); for a path,
- fractions of its length and the curve parameters where they are reached.
+ None for evenly by step (points, triangles, or a surface's faces, in order,
+ each whole with all it draws); for a path, fractions of its length and the
+ curve parameters where they are reached.
"""
return None
@@ -1015,6 +1033,7 @@ class Mobject:
self.points = np.array(points, dtype=float)
return self
+ @deprecated("get_points() is points: use it", category=None)
def get_points(self) -> Point3D_Array:
"""The mobject's own [points][manimgx.Mobject.points].
@@ -1027,10 +1046,12 @@ class Mobject:
"""Whether the mobject has points of its own (a group has none: its members do)."""
return self._geometry.n > 0
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def has_no_points(self) -> bool:
"""Whether the mobject has no points of its own."""
return self._geometry.n == 0
+ @deprecated("use len(mobject.points)", category=None)
def get_num_points(self) -> int:
"""How many points of its own the mobject has.
@@ -1039,6 +1060,7 @@ class Mobject:
"""
return self._geometry.n
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_all_points(self) -> Point3D_Array:
"""Every point of the mobject's family, member after member.
@@ -1070,6 +1092,7 @@ class Mobject:
self._require_points()
return np.array(self.points[-1])
+ @deprecated("use get_start() and get_end()", category=None)
def get_start_and_end(self) -> tuple[Point3D, Point3D]:
"""The mobject's first and last points.
@@ -1179,6 +1202,7 @@ class Mobject:
"""
return [m for m in self.get_family() if m.has_points()]
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def split(self) -> list["Mobject"]:
"""The mobject's parts: itself, if it has points of its own, then its
submobjects.
@@ -1191,6 +1215,7 @@ class Mobject:
"""
return list(self)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_group_class(self) -> type["Group"]:
"""The class of the groups the mobject's parts are gathered in: slicing it
(`mobject[1:3]`) makes one.
@@ -1312,8 +1337,7 @@ class Mobject:
"""Run each of the mobject's updaters once, now; nothing runs while its updating
is suspended.
- The scene brings updaters forward itself (see
- [advance][manimgx.Mobject.advance]): this runs them by hand.
+ The scene runs updaters itself, at every frame: this runs them by hand, now.
Args:
dt: The seconds handed to its time-based updaters.
@@ -1337,6 +1361,7 @@ class Mobject:
sub.update(dt, recursive)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def advance(
self,
t: Fraction,
@@ -1527,14 +1552,20 @@ class Mobject:
sub.clear_updaters()
return self
- def get_updaters(self) -> list[Updater[Self]]:
+ def get_updaters(self) -> tuple[Updater[Self], ...]:
"""The mobject's own updaters, in the order they run.
+ Change them with [add_updater][manimgx.Mobject.add_updater],
+ [remove_updater][manimgx.Mobject.remove_updater] and
+ [clear_updaters][manimgx.Mobject.clear_updaters], which keep their clocks with
+ them.
+
Returns:
- The list itself, so changing it changes the mobject's updaters.
+ A snapshot of them.
"""
- return self.updaters
+ return tuple(self.updaters)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_family_updaters(self) -> list[Updater[Never]]: # each of its own kind
"""Every updater of the mobject's family: its own, then its descendants', in
family order.
@@ -1544,10 +1575,12 @@ class Mobject:
"""
return [u for m in self.get_family() for u in m.updaters]
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def has_time_based_updater(self) -> bool:
"""Whether any of the mobject's own updaters is time-based: it takes `dt`."""
return not all(_per_frame(u) for u in self.updaters)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_time_based_updaters(self) -> list[Updater[Self]]:
"""The mobject's own time-based updaters: those that take `dt`.
@@ -1586,6 +1619,7 @@ class Mobject:
return Always(self)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def match_updaters(self, mobject: "Mobject") -> Self:
"""Give the mobject another's updaters in place of its own, and clear its
submobjects'.
@@ -1604,15 +1638,18 @@ class Mobject:
return self
def suspend_updating(self, recursive: bool = True) -> Self:
- """Stop the mobject's updaters from running, until
- [resume_updating][manimgx.Mobject.resume_updating].
+ """Stop the mobject's updaters from running, and its family's beneath it, until
+ [resume_updating][manimgx.Mobject.resume_updating]: nothing updated through a
+ suspended mobject runs.
An animation suspends the updating of the mobject it plays while it plays, and
runs the updaters beneath it instead (see
[add_updater][manimgx.Mobject.add_updater]).
Args:
- recursive: Whether its whole family's updaters stop too.
+ recursive: Whether each member of its family is suspended too, so that it stays
+ stopped where it is updated apart from the mobject (a member the scene
+ also holds by itself), and when the mobject alone resumes.
"""
self.updating_suspended = True
if recursive:
@@ -1629,7 +1666,9 @@ class Mobject:
else at the next one, such as the next frame.
Args:
- recursive: Whether its whole family's updaters resume too.
+ recursive: Whether its whole family's updaters resume too: resumed alone, the
+ mobject runs again, and the members beneath it that are not suspended
+ themselves.
"""
# not run here as well: the instant's own pass runs them, and a per-frame
# updater would run twice at one instant
@@ -1641,6 +1680,7 @@ class Mobject:
return self
# ── the one transform primitive ────────────────────────────────────────
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def apply_points_function_about_point(
self,
func: PointsFunc,
@@ -1832,9 +1872,13 @@ class Mobject:
for mob in self.get_family():
mob.paint = mob.paint.but(sheen_direction=rot @ mob.paint.sheen_direction)
+ @deprecated(
+ "rotate_about_origin(angle, axis) is rotate(angle, axis, about_point=ORIGIN)",
+ category=None,
+ )
def rotate_about_origin(self, angle: float, axis: Vector3DLike = OUT) -> Self:
"""Rotate the mobject and its whole family by an angle, about an axis through
- the origin.
+ the origin: `rotate(angle, axis, about_point=ORIGIN)`.
Args:
angle: The angle, in radians: counterclockwise as seen from where `axis`
@@ -1879,6 +1923,10 @@ class Mobject:
TAU / 2, axis, about_point=about_point, about_edge=about_edge
)
+ @deprecated(
+ "stretch_about_point(factor, dim, point) is stretch(factor, dim, about_point=point): use it",
+ category=None,
+ )
def stretch_about_point(self, factor: float, dim: int, point: Point3DLike) -> Self:
"""Stretch the mobject and its whole family along one axis, keeping a point
fixed (see [stretch][manimgx.Mobject.stretch]).
@@ -2070,6 +2118,7 @@ class Mobject:
return self.apply_function(r3, **kwargs)
+ @deprecated("use move_to(function(mobject.get_center()))", category=None)
def apply_function_to_position(
self, function: Callable[[Point3D], Point3D]
) -> Self:
@@ -2082,6 +2131,7 @@ class Mobject:
"""
return self.move_to(function(self.get_center()))
+ @deprecated("use move_to(function(mobject.get_center()))", category=None)
def apply_function_to_submobject_positions(
self, function: Callable[[Point3D], Point3D]
) -> Self:
@@ -2096,6 +2146,7 @@ class Mobject:
sub.apply_function_to_position(function)
return self
+ @deprecated("use reverse_direction", category=None)
def reverse_points(self) -> Self:
"""Reverse the order of the points of each drawn member of the family: a path
then runs the other way, from its end to its start.
@@ -2105,6 +2156,7 @@ class Mobject:
return self
# ── bounds: one box, what the family draws ───────────────────────────────
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def length_over_dim(self, dim: int) -> float:
"""The mobject's extent along one axis, in scene units: its
[bounding box][manimgx.Mobject.boundary_box]'s, from its lowest coordinate to
@@ -2120,6 +2172,7 @@ class Mobject:
box = self.boundary_box()
return 0 if box is None else float(box[1, dim] - box[0, dim])
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_extremum_along_dim(
self, points: Point3D_Array | None = None, dim: int = 0, key: float = 0
) -> float:
@@ -2142,6 +2195,11 @@ class Mobject:
lo, hi = np.min(points[:, dim]), np.max(points[:, dim])
return float(lo if key < 0 else hi if key > 0 else (lo + hi) / 2)
+ def _box(self) -> np.ndarray | None:
+ """The (2, 3) box of what this member draws, alone: its geometry's (a path's,
+ its curves' tight box); None when it draws nothing."""
+ return self._geometry.box(self._curves)
+
def boundary_box(self) -> np.ndarray | None:
"""The mobject's bounding box: the smallest box, aligned with the axes, around
what its family draws.
@@ -2188,10 +2246,16 @@ class Mobject:
]
)
- get_edge_center = get_critical_point
- """The middle of an edge of the mobject's bounding box, named by a direction
- (`get_edge_center(UP)`): another name for
- [get_critical_point][manimgx.Mobject.get_critical_point]."""
+ @deprecated(
+ "get_edge_center is get_critical_point: use it, or get_top, get_bottom,"
+ " get_left and get_right",
+ category=None,
+ )
+ def get_edge_center(self, direction: Vector3DLike) -> Point3D:
+ """The middle of an edge of the mobject's bounding box, named by a direction:
+ [get_critical_point][manimgx.Mobject.get_critical_point], by another name."""
+ return self.get_critical_point(direction)
+
get_corner = get_critical_point
"""A corner of the mobject's bounding box, named by a direction (`get_corner(UR)`):
another name for [get_critical_point][manimgx.Mobject.get_critical_point]."""
@@ -2204,6 +2268,7 @@ class Mobject:
"""
return self.get_critical_point(np.zeros(self.dim))
+ @deprecated("use get_center", category=None)
def get_center_of_mass(self) -> Point3D:
"""The mean of all the points of the mobject's family: every control point of a
path, its handles too.
@@ -2214,9 +2279,8 @@ class Mobject:
return np.mean(self.get_all_points(), axis=0)
def get_boundary_point(self, direction: Vector3DLike) -> Point3D:
- """The point of the mobject farthest in a direction: of its
- [boundary points][manimgx.Mobject.get_points_defining_boundary], the one
- farthest along `direction`.
+ """The point of the mobject farthest in a direction: of the points it is drawn
+ through, the one farthest along `direction`.
Unlike [get_critical_point][manimgx.Mobject.get_critical_point], it is one of
those points (for a path, an end of one of its curves), not a point of the
@@ -2234,7 +2298,7 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(UP)
+ return self.get_critical_point(UP)
def get_bottom(self) -> Point3D:
"""The middle of the bottom edge of the mobject's bounding box.
@@ -2242,7 +2306,7 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(DOWN)
+ return self.get_critical_point(DOWN)
def get_right(self) -> Point3D:
"""The middle of the right edge of the mobject's bounding box.
@@ -2250,7 +2314,7 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(RIGHT)
+ return self.get_critical_point(RIGHT)
def get_left(self) -> Point3D:
"""The middle of the left edge of the mobject's bounding box.
@@ -2258,8 +2322,9 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(LEFT)
+ return self.get_critical_point(LEFT)
+ @deprecated("use get_critical_point(OUT), or get_critical_point(IN)", category=None)
def get_zenith(self) -> Point3D:
"""The middle of the face of the mobject's bounding box farthest out of the
screen (toward OUT: its highest z).
@@ -2267,8 +2332,9 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(OUT)
+ return self.get_critical_point(OUT)
+ @deprecated("use get_critical_point(OUT), or get_critical_point(IN)", category=None)
def get_nadir(self) -> Point3D:
"""The middle of the face of the mobject's bounding box farthest into the screen
(toward IN: its lowest z).
@@ -2276,8 +2342,9 @@ class Mobject:
Returns:
The point, in scene coordinates.
"""
- return self.get_edge_center(IN)
+ return self.get_critical_point(IN)
+ @deprecated("use get_x, get_y or get_z", category=None)
def get_coord(self, dim: int, direction: Vector3DLike = ORIGIN) -> float:
"""One coordinate of a point of the mobject's bounding box: along axis `dim`,
its lowest, middle or highest, as `direction`'s coordinate there is negative, 0
@@ -2365,6 +2432,7 @@ class Mobject:
def height(self, value: float) -> None:
self.scale_to_fit_height(value)
+ @deprecated("get_width() is width: use it", category=None)
def get_width(self) -> float:
"""The mobject's [width][manimgx.Mobject.width].
@@ -2470,8 +2538,9 @@ class Mobject:
self.add(square, right, up, down, dot)
```
"""
- d, edge = np.asarray(direction, dtype=float), np.asarray(
- aligned_edge, dtype=float
+ d, edge = (
+ np.asarray(direction, dtype=float),
+ np.asarray(aligned_edge, dtype=float),
)
if isinstance(mobject_or_point, Mobject):
target_aligner = (
@@ -2491,6 +2560,7 @@ class Mobject:
point_to_align = aligner.get_critical_point(edge - d)
return self.shift((target - point_to_align + buff * d) * np.asarray(coor_mask))
+ @deprecated("use to_edge or to_corner", category=None)
def align_on_border(
self, direction: Vector3DLike, buff: float = DEFAULT_MOBJECT_TO_EDGE_BUFFER
) -> Self:
@@ -2595,7 +2665,7 @@ class Mobject:
radii = (config.frame_x_radius, config.frame_y_radius)
for vect in (UP, DOWN, LEFT, RIGHT):
dim = int(np.argmax(np.abs(vect)))
- if np.dot(self.get_edge_center(vect), vect) > radii[dim] - buff:
+ if np.dot(self.get_critical_point(vect), vect) > radii[dim] - buff:
self.to_edge(vect, buff=buff)
return self
@@ -2688,6 +2758,7 @@ class Mobject:
self.set_coord(point[dim], dim, direction)
return self
+ @deprecated("use set_x, set_y or set_z", category=None)
def set_coord(
self, value: float, dim: int, direction: Vector3DLike = ORIGIN
) -> Self:
@@ -2738,6 +2809,7 @@ class Mobject:
"""
return self.set_coord(z, 2, direction)
+ @deprecated("use scale_to_fit_width or scale_to_fit_height", category=None)
def rescale_to_fit(
self, length: float, dim: int, stretch: bool = False, **kwargs: Unpack[Pivot]
) -> Self:
@@ -2804,6 +2876,7 @@ class Mobject:
"""
return self.rescale_to_fit(height, 1, stretch=True, **kwargs)
+ @deprecated("use match_width or match_height", category=None)
def match_dim_size(
self, mobject: "Mobject", dim: int, **kwargs: Unpack[Pivot]
) -> Self:
@@ -2837,6 +2910,7 @@ class Mobject:
"""
return self.match_dim_size(mobject, 1, **kwargs)
+ @deprecated("use scale", category=None)
def match_depth(self, mobject: "Mobject", **kwargs: Unpack[Pivot]) -> Self:
"""Scale the mobject in proportion to another's depth, its extent along z.
@@ -2847,6 +2921,7 @@ class Mobject:
"""
return self.match_dim_size(mobject, 2, **kwargs)
+ @deprecated("use match_x, match_y or match_z", category=None)
def match_coord(
self, mobject: "Mobject", dim: int, direction: Vector3DLike = ORIGIN
) -> Self:
@@ -2975,8 +3050,16 @@ class Mobject:
m2.next_to(m1, direction, buff, **kwargs)
return self.center() if center else self
- arrange_submobjects = arrange
- """Another name for [arrange][manimgx.Mobject.arrange]."""
+ @deprecated("arrange_submobjects is arrange: use it", category=None)
+ def arrange_submobjects(
+ self,
+ direction: Vector3DLike = RIGHT,
+ buff: float = DEFAULT_MOBJECT_TO_MOBJECT_BUFFER,
+ center: bool = True,
+ **kwargs: Unpack[Beside],
+ ) -> Self:
+ """[arrange][manimgx.Mobject.arrange], by another name."""
+ return self.arrange(direction, buff, center, **kwargs)
def arrange_in_grid(
self,
@@ -3053,12 +3136,16 @@ class Mobject:
cols = cols or (
len(col_alignments)
if col_alignments
- else len(widths_in) if widths_in else None
+ else len(widths_in)
+ if widths_in
+ else None
)
rows = rows or (
len(row_alignments)
if row_alignments
- else len(heights_in) if heights_in else None
+ else len(heights_in)
+ if heights_in
+ else None
)
if rows is None:
cols = math.ceil(math.sqrt(len(mobs))) if cols is None else cols
@@ -3107,8 +3194,9 @@ class Mobject:
x = 0.0
for c in range(cols):
if grid[r][c] is not placeholder:
- lo, hi = np.array([x, y, 0.0]), np.array(
- [x + widths[c], y + heights[r], 0.0]
+ lo, hi = (
+ np.array([x, y, 0.0]),
+ np.array([x + widths[c], y + heights[r], 0.0]),
)
align = rdirs[r] + cdirs[c]
corner = np.where(
@@ -3166,6 +3254,7 @@ class Mobject:
self.submobjects.reverse()
return self
+ @deprecated("use arrange, with buff", category=None)
def space_out_submobjects(
self, factor: float = 1.5, **kwargs: Unpack[Pivot]
) -> Self:
@@ -3376,11 +3465,20 @@ class Mobject:
class MobjectSetMaterialExample(m.ThreeDScene):
def construct(self) -> None:
- self.set_camera_orientation(phi=65 * m.DEGREES, theta=-50 * m.DEGREES)
- self.add(m.SunLight(4 * m.LEFT + 6 * m.OUT), m.AmbientLight(intensity=0.15))
+ self.set_camera_orientation(
+ phi=65 * m.DEGREES, theta=-50 * m.DEGREES
+ )
+ self.add(
+ m.SunLight(4 * m.LEFT + 6 * m.OUT),
+ m.AmbientLight(intensity=0.15),
+ )
torus = m.Torus(resolution=(48, 24)).set_color(m.TEAL)
self.add(torus.set_material(m.Material(roughness=0.25)))
- self.play(torus.animate.set_material(m.Material(metallic=1, roughness=0.6)))
+ self.play(
+ torus.animate.set_material(
+ m.Material(metallic=1, roughness=0.6)
+ )
+ )
```
"""
for mob in self.get_family() if family else [self]:
@@ -3508,6 +3606,7 @@ class Mobject:
mob.paint = mob.paint.but(sheen_direction=direction)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_stroke_rgbas(self, background: bool = False) -> np.ndarray:
"""The mobject's own stroke colors, one row per gradient stop.
@@ -3519,10 +3618,12 @@ class Mobject:
"""
return self.paint.background if background else self.paint.stroke
+ @deprecated("get_fill_color() is fill_color: use it", category=None)
def get_fill_color(self) -> ManimColor:
"""The mobject's own fill color (for a gradient, its first)."""
return ManimColor(self.paint.fill[0, :3])
+ @deprecated("get_fill_opacity() is fill_opacity: use it", category=None)
def get_fill_opacity(self) -> float:
"""The opacity of the mobject's own fill (for a gradient, its first color's).
@@ -3531,6 +3632,7 @@ class Mobject:
"""
return float(self.paint.fill[0, 3])
+ @deprecated("get_stroke_color() is stroke_color: use it", category=None)
def get_stroke_color(self, background: bool = False) -> ManimColor:
"""The mobject's own stroke color (for a gradient, its first).
@@ -3539,6 +3641,7 @@ class Mobject:
"""
return ManimColor(self.get_stroke_rgbas(background)[0, :3])
+ @deprecated("get_stroke_width() is stroke_width: use it", category=None)
def get_stroke_width(self, background: bool = False) -> float:
"""The width of the mobject's own stroke.
@@ -3552,6 +3655,7 @@ class Mobject:
0.0, self.paint.background_width if background else self.paint.stroke_width
)
+ @deprecated("get_stroke_opacity() is stroke_opacity: use it", category=None)
def get_stroke_opacity(self, background: bool = False) -> float:
"""The opacity of the mobject's own stroke (for a gradient, its first color's).
@@ -3563,6 +3667,7 @@ class Mobject:
"""
return float(self.get_stroke_rgbas(background)[0, 3])
+ @deprecated("get_color() is color: use it", category=None)
def get_color(self) -> ManimColor:
"""The mobject's own color: its fill's, or its stroke's if it has no fill (its
fill wholly transparent).
@@ -3620,8 +3725,8 @@ class Mobject:
return self
def match_color(self, mobject: "Mobject") -> Self:
- """Color the mobject and its whole family with another's color (see
- [get_color][manimgx.Mobject.get_color]).
+ """Color the mobject and its whole family with another's
+ [color][manimgx.Mobject.color].
Args:
mobject: The mobject whose color to take.
@@ -3680,6 +3785,7 @@ class Mobject:
)
return self
+ @deprecated("sort_submobjects is sort: use it", category=None)
def sort_submobjects(
self,
point_to_num_func: Callable[[Point3D], float] = lambda p: p[0],
@@ -3695,10 +3801,12 @@ class Mobject:
"""
return self.sort(point_to_num_func, submob_func)
+ @deprecated("use set_color(mobject.color)", category=None)
def to_original_color(self) -> Self:
"""Color the whole family with the mobject's own [color][manimgx.Mobject.color]."""
return self.set_color(self.color)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def apply_to_family(self, func: Callable[["Mobject"], object]) -> None:
"""Call a function on each drawn member of the family, in family order.
@@ -3708,6 +3816,10 @@ class Mobject:
for mob in self.family_members_with_points():
func(mob)
+ @deprecated(
+ "set_submobject_colors_by_gradient is set_color_by_gradient: use it",
+ category=None,
+ )
def set_submobject_colors_by_gradient(self, *colors: ParsableManimColor) -> Self:
"""Color the drawn members of the family along a gradient: the same as
[set_color_by_gradient][manimgx.Mobject.set_color_by_gradient].
@@ -3773,6 +3885,7 @@ class Mobject:
return self
# ── structural alignment + interpolation (the Transform engine) ─────────
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def align_data(
self, mobject: "Mobject", skip_point_alignment: bool = False
) -> Self:
@@ -3797,6 +3910,7 @@ class Mobject:
m1.align_data(m2, skip_point_alignment)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def align_points(self, mobject: "Mobject") -> Self:
"""Give this mobject and another the same number of points of their own, and of
color rows: the one with fewer is refined, its shape and look unchanged (see
@@ -3813,6 +3927,7 @@ class Mobject:
mobject.align_points_with_larger(self)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def align_submobjects(self, mobject: "Mobject") -> Self:
"""Give this mobject and another the same number of submobjects.
@@ -3835,6 +3950,7 @@ class Mobject:
)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def null_point_align(self, mobject: "Mobject") -> Self:
"""If one of this mobject and another has no points of its own and the other
has, move the other's points into a submobject of its own, so the two families
@@ -3849,6 +3965,7 @@ class Mobject:
m2.push_self_into_submobjects()
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def push_self_into_submobjects(self) -> Self:
"""Move the mobject's own points into a new submobject, added last: a copy of it
without submobjects. The mobject keeps its submobjects, and has no points of its
@@ -3859,6 +3976,7 @@ class Mobject:
self.reset_points()
return self.add(clone)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def add_n_more_submobjects(self, n: int) -> Self:
"""Add `n` submobjects, for a transform that splits parts: a mobject with none
gets `n` points of itself, at its center (see
@@ -3888,6 +4006,7 @@ class Mobject:
self.submobjects = new
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def interpolate(
self,
mobject1: "Mobject",
@@ -3919,6 +4038,7 @@ class Mobject:
self.paint = self.paint.mixed(mobject1.paint, mobject2.paint, alpha)
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def interpolate_color(
self, mobject1: "Mobject", mobject2: "Mobject", alpha: float
) -> Self:
@@ -3945,8 +4065,7 @@ class Mobject:
"""Make the mobject look like another, at once, while staying itself: the same
object in the scene, with its updaters.
- The two families are first given the same structure (see
- [align_data][manimgx.Mobject.align_data]); then each member takes its
+ The two families are first given the same structure; then each member takes its
counterpart's points and its colors, opacities, stroke widths, sheen and
texture (its joint and cap styles and 3D shading stay its own, unless they are
the same). With a `match_*` flag or `stretch`, a copy of `mobject` is first
@@ -4020,6 +4139,7 @@ class Mobject:
shape is more than points — a mesh's triangles — takes that too)."""
@classmethod
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def add_animation_override(
cls,
animation_class: type["Animation"],
@@ -4058,25 +4178,30 @@ class Mobject:
mobjects keep their state; later construction reads the current defaults.
Repeated calls replace this class's keyword defaults. Reset restores its
- original constructor descriptor, or normal inheritance if it had no
- constructor of its own. A new override uses the current inherited defaults.
+ original constructor, or normal inheritance if it had no constructor of its own.
+ The defaults are applied when a mobject is made, to the constructor then in
+ force: the class's own, or the next one in the made mobject's class's order (so a
+ parent's later defaults reach a configured child, and a configured mixin calls the
+ class after it in a subclass's order).
Args:
**kwargs: Keywords of the class's constructor, with their new defaults.
"""
- # The constructor checks the keywords when it runs: a partial
- # application of a signature has no static type
- from functools import partialmethod
-
if kwargs:
- configured = "_original__init__" in cls.__dict__
original = cls.__dict__.get(
"_original__init__", cls.__dict__.get("__init__")
)
- init = original
- if original is None and (configured or "__init__" not in cls.__dict__):
- init = super(cls, cls).__init__
- init = partialmethod(init, **kwargs)
+ defaults = dict(kwargs)
+
+ # The constructor checks the keywords when it runs: defaults applied to a
+ # signature have no static type
+ def init(self: Mobject, *args: object, **given: object) -> None:
+ merged = defaults | given
+ if original is not None:
+ original(self, *args, **merged)
+ else:
+ super(cls, self).__init__(*args, **merged)
+
setattr(cls, "_original__init__", original) # noqa: B010
setattr(cls, "__init__", init) # noqa: B010
elif "_original__init__" in cls.__dict__:
@@ -4088,6 +4213,7 @@ class Mobject:
setattr(cls, "__init__", original) # noqa: B010
caches.clear()
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_pieces(self, n_pieces: int) -> "Group":
"""Split the mobject into pieces: copies of it, each an equal part of it in
turn, from its start to its end (a path's, by its curves).
@@ -4125,17 +4251,15 @@ class Mobject:
square turns about its center where the shift left it. When the animation
finishes, the calls are carried out on the mobject itself.
- The motion follows the calls: a turn among them (`rotate`, `flip`,
- `rotate_about_origin`) turns the mobject rigidly about its pivot, through its
- whole angle (`rotate(TAU)` is a full turn); every other call moves its center
+ The motion follows the calls: a turn among them (`rotate`, `flip`) turns the
+ mobject rigidly about its pivot, through its whole angle (`rotate(TAU)` is a full turn); every other call moves its center
straight; and the rest of the change (a size, a color, a new shape) blends along
the way. Call `animate` with options before any method —
`square.animate(run_time=2, rate_func=linear).shift(UP)` — to set the
animation's [Transform options][manimgx.animation.transform.TransformOptions]; a
`path_arc` or a `path_func` among them replaces the motion. Call it with a
function — `square.animate(lambda s: s.shift(UP))` — to record that function as
- a call. A method decorated with [override_animate][manimgx.override_animate]
- plays the animation it makes instead, and cannot be chained.
+ a call.
Examples:
```python
@@ -4156,6 +4280,7 @@ class Mobject:
return Animate(self)
@classmethod
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def animation_override_for(
cls, animation_class: type["Animation"]
) -> Callable[..., "Animation"] | None:
@@ -4208,8 +4333,7 @@ class Group[T: Mobject = Mobject](Mobject):
A group has no points of its own: its members are its submobjects, and whatever is
done to the group — moving, scaling, styling, animating — is done to them all.
- [VGroup][manimgx.VGroup] and [PGroup][manimgx.PGroup] are other names for it. A
- group can be indexed (`group[0]`), sliced (`group[1:3]` is a new group of those
+ [VGroup][manimgx.VGroup] is another name for it. A group can be indexed (`group[0]`), sliced (`group[1:3]` is a new group of those
members) and iterated over, and `group + mobject`, `group - mobject`, `+=` and `-=`
add and remove members.
@@ -4305,6 +4429,10 @@ class Group[T: Mobject = Mobject](Mobject):
return cast("Group[T]", Group(*members))
+@deprecated(
+ "Manim CE's way to change the animation a class plays: manimgx doesn't document it",
+ category=None,
+)
def override_animate[F: Callable[..., "Animation"]](
method: Callable[..., object],
) -> Callable[[F], F]:
@@ -4356,6 +4484,10 @@ def override_animate[F: Callable[..., "Animation"]](
return decorator
+@deprecated(
+ "Manim CE's way to change the animation a class plays: manimgx doesn't document it",
+ category=None,
+)
def override_animation[F: Callable[..., "Animation"]](
animation_class: type["Animation"],
) -> Callable[[F], F]:
@@ -4444,9 +4576,7 @@ class ValueTracker[V: (float, complex) = float](Mobject):
def get_value(self) -> V:
"""The number the tracker holds."""
- return float(
- self.points[0, 0]
- ) # pyright: ignore[reportReturnType] # V is float here
+ return float(self.points[0, 0]) # pyright: ignore[reportReturnType] # V is float here
def set_value(self, value: V) -> Self:
"""Set the number the tracker holds; through
@@ -4625,7 +4755,7 @@ class VMobject(Mobject):
Args:
value: Whether the light shades them.
z_index_as_group: Whether each member of the family also takes the path as
- its [z_index_group][manimgx.Mobject.z_index_group], which is kept for
+ its z-index group, which is kept for
Manim compatibility (the renderer draws a three-dimensional scene by
depth).
"""
@@ -4635,6 +4765,7 @@ class VMobject(Mobject):
mob.z_index_group = self
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_sheen_direction(self) -> np.ndarray:
"""The direction the path's own colors lighten toward, which its gradients run
along too (see [set_sheen][manimgx.Mobject.set_sheen]).
@@ -4648,6 +4779,7 @@ class VMobject(Mobject):
"""The mobject whose bounding box the path's color gradients span; None for the
path's own. Parts that share one show a single gradient across them all."""
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_gradient_start_and_end_points(self) -> tuple[Point3D, Point3D]:
"""Where the path's color gradients start and end: a gradient spans its
[bounding box][manimgx.Mobject.boundary_box], along its sheen direction.
@@ -4670,6 +4802,7 @@ class VMobject(Mobject):
return center - offset, center + offset
# ── path building ─────────────────────────────────────────────────────
+ @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
def set_anchors_and_handles(
self,
anchors1: Point3D_Array,
@@ -4696,6 +4829,7 @@ class VMobject(Mobject):
self.points = points
return self
+ @deprecated("clear_points is reset_points: use it", category=None)
def clear_points(self) -> Self:
"""Remove the path's own points: the same as
[reset_points][manimgx.Mobject.reset_points].
@@ -4862,8 +4996,8 @@ class VMobject(Mobject):
stairs = m.VMobject(color=m.BLUE, stroke_width=8)
stairs.start_new_path([-5, -3, 0])
for _ in range(5):
- stairs.add_line_to(stairs.get_last_point() + 1.2 * m.UP)
- stairs.add_line_to(stairs.get_last_point() + 2 * m.RIGHT)
+ stairs.add_line_to(stairs.get_end() + 1.2 * m.UP)
+ stairs.add_line_to(stairs.get_end() + 2 * m.RIGHT)
self.play(m.Create(stairs, run_time=3))
```
"""
@@ -4919,6 +5053,7 @@ class VMobject(Mobject):
handle2 = new_anchor + tangent - 2 * (tangent @ chord) * chord
return self.append_points([last_a2, handle1, handle2, new_anchor])
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def has_new_path_started(self) -> bool:
"""Whether the path ends in a subpath just started: a point that begins no curve
yet, where the next curve added starts.
@@ -4929,6 +5064,7 @@ class VMobject(Mobject):
"""
return self._geometry.n % _NPPCC == 1
+ @deprecated("use get_end", category=None)
def get_last_point(self) -> Point3D:
"""The path's last point: where it ends, and where the next curve added begins.
@@ -4939,9 +5075,7 @@ class VMobject(Mobject):
def is_closed(self) -> bool:
"""Whether the path ends where it starts: its first and last points coincide,
- within its
- [tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
- """
+ within a millionth of a unit."""
return self.consider_points_equals(
self._geometry.point(0), self._geometry.point(-1)
)
@@ -5081,6 +5215,7 @@ class VMobject(Mobject):
self.set_points_as_corners(points)
return self.make_smooth()
+ @deprecated("use make_smooth or make_jagged", category=None)
def change_anchor_mode(self, mode: Literal["jagged", "smooth"]) -> Self:
"""Set anew the handles of every subpath in the family, for a smooth curve
through its anchors or straight lines between them; the anchors stay.
@@ -5099,8 +5234,9 @@ class VMobject(Mobject):
if mode == "smooth":
h1, h2 = get_smooth_cubic_bezier_handle_points(anchors)
else:
- h1, h2 = interpolate(anchors[:-1], anchors[1:], 1 / 3), interpolate(
- anchors[:-1], anchors[1:], 2 / 3
+ h1, h2 = (
+ interpolate(anchors[:-1], anchors[1:], 1 / 3),
+ interpolate(anchors[:-1], anchors[1:], 2 / 3),
)
new = np.array(subpath)
new[1::_NPPCC], new[2::_NPPCC] = h1, h2
@@ -5200,6 +5336,7 @@ class VMobject(Mobject):
if self.make_smooth_after_applying_functions:
self.make_smooth()
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def scale_handle_to_anchor_distances(self, factor: float) -> Self:
"""Move the handles of every path in the family toward their anchors, or away
from them, scaling their distances by a factor.
@@ -5221,6 +5358,7 @@ class VMobject(Mobject):
return self
# ── curves and subpaths ───────────────────────────────────────────────
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def consider_points_equals(self, p0: Point3DLike, p1: Point3DLike) -> bool:
"""Whether two points count as one: equal within
[tolerance_for_point_equality][manimgx.VMobject.tolerance_for_point_equality].
@@ -5231,6 +5369,7 @@ class VMobject(Mobject):
"""
return bool(np.allclose(p0, p1, atol=self.tolerance_for_point_equality))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_cubic_bezier_tuples_from_points(self, points: Point3D_Array) -> np.ndarray:
"""Split control points into curves, four points each; an unfinished last curve
is left out.
@@ -5246,6 +5385,7 @@ class VMobject(Mobject):
-1, _NPPCC, points.shape[1] if len(points) else 3
)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_cubic_bezier_tuples(self) -> np.ndarray:
"""The path's curves, by their control points.
@@ -5255,6 +5395,7 @@ class VMobject(Mobject):
"""
return self.get_cubic_bezier_tuples_from_points(self.points)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_subpaths_from_points(self, points: Point3D_Array) -> list[Point3D_Array]:
"""Split control points into subpaths: a subpath starts wherever a curve does
not begin where the one before it ends.
@@ -5270,6 +5411,7 @@ class VMobject(Mobject):
for a, b, _ in subpath_ranges(points, self.tolerance_for_point_equality)
]
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def consider_points_equals_2d(self, p0: Point3DLike, p1: Point3DLike) -> bool:
"""Whether two points count as one seen along the z axis: their x and y
coordinates equal within
@@ -5287,6 +5429,7 @@ class VMobject(Mobject):
)
)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def gen_cubic_bezier_tuples_from_points(
self, points: Point3D_Array
) -> tuple[Point3D_Array, ...]:
@@ -5302,6 +5445,7 @@ class VMobject(Mobject):
n = len(points) - len(points) % _NPPCC
return tuple(points[i : i + _NPPCC] for i in range(0, n, _NPPCC))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def gen_subpaths_from_points_2d(
self, points: Point3D_Array
) -> Iterator[Point3D_Array]:
@@ -5330,6 +5474,7 @@ class VMobject(Mobject):
"""
return self.get_subpaths_from_points(self.points)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_nth_curve_points(self, n: int) -> Point3D_Array:
"""The control points of one of the path's curves.
@@ -5341,6 +5486,7 @@ class VMobject(Mobject):
"""
return self.points[_NPPCC * n : _NPPCC * (n + 1)]
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_nth_curve_function(self, n: int) -> Callable[[float], Point3D]:
"""One of the path's curves, as a function from 0, its start, to 1, its end.
@@ -5352,6 +5498,7 @@ class VMobject(Mobject):
"""
return bezier(self.get_nth_curve_points(n))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_nth_curve_length_pieces(
self, n: int, sample_points: int | None = None
) -> np.ndarray:
@@ -5372,6 +5519,7 @@ class VMobject(Mobject):
pts = np.array([curve(a) for a in np.linspace(0, 1, sample_points)])
return np.linalg.norm(np.diff(pts, axis=0), axis=1)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_nth_curve_length(self, n: int, sample_points: int | None = None) -> float:
"""The length of one of the path's curves, measured along straight pieces
between points on it.
@@ -5394,6 +5542,7 @@ class VMobject(Mobject):
"""
return self._geometry.n // _NPPCC
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_curve_functions_with_lengths(
self, sample_points: int | None = None
) -> Iterator[tuple[Callable[[float], Point3D], float]]:
@@ -5409,8 +5558,9 @@ class VMobject(Mobject):
units.
"""
for n in range(self.get_num_curves()):
- yield self.get_nth_curve_function(n), self.get_nth_curve_length(
- n, sample_points
+ yield (
+ self.get_nth_curve_function(n),
+ self.get_nth_curve_length(n, sample_points),
)
def point_from_proportion(self, alpha: float) -> Point3D:
@@ -5477,6 +5627,7 @@ class VMobject(Mobject):
)
)
+ @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
def get_anchors_and_handles(self) -> list[Point3D_Array]:
"""The path's control points, kind by kind: its curves' first anchors, first
handles, second handles and second anchors.
@@ -5488,6 +5639,7 @@ class VMobject(Mobject):
"""
return [self.points[i::_NPPCC] for i in range(_NPPCC)]
+ @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
def get_start_anchors(self) -> Point3D_Array:
"""Where each of the path's curves starts.
@@ -5496,6 +5648,7 @@ class VMobject(Mobject):
"""
return self.points[::_NPPCC]
+ @deprecated("use add_cubic_bezier_curve, and get_anchors", category=None)
def get_end_anchors(self) -> Point3D_Array:
"""Where each of the path's curves ends.
@@ -5591,6 +5744,7 @@ class VMobject(Mobject):
self.append_points([new_path_point])
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def insert_n_curves_to_point_list(
self, n: int, points: Point3D_Array
) -> Point3D_Array:
@@ -5674,7 +5828,7 @@ class VMobject(Mobject):
def get_direction(self) -> str:
"""Which way the path turns: "CW" (clockwise) or "CCW" (counterclockwise), by
- the sign of [shoelace][manimgx.shoelace] over its curves' start anchors.
+ the sign of the area its curves' start anchors enclose.
Returns:
"CW" or "CCW".
@@ -5685,9 +5839,8 @@ class VMobject(Mobject):
"""Reverse the order of the path's own points, so it runs the other way: from
its end to its start.
- Its submobjects stay as they are (see
- [reverse_points][manimgx.Mobject.reverse_points] for the whole family). A
- drawing animation then draws it the other way, and a subpath inside another cuts
+ Its submobjects stay as they are. A drawing animation then draws it the other
+ way, and a subpath inside another cuts
a hole in the fill only if the two run opposite ways.
Examples:
@@ -5725,6 +5878,7 @@ class VMobject(Mobject):
def get_style(self, simple: Literal[True]) -> SimpleStyle: ...
@overload
def get_style(self, simple: Literal[False] = False) -> StyleSnapshot: ...
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_style(self, simple: bool = False) -> SimpleStyle | StyleSnapshot:
"""The path's own style, as keywords: `set_style(**style)` gives it back.
@@ -5760,6 +5914,7 @@ class VMobject(Mobject):
)
@staticmethod
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_mobject_type_class() -> type[Mobject]:
"""The class of the paths' kind: `VMobject`, whatever a path's own class.
@@ -5884,6 +6039,7 @@ class VectorizedPoint(VMobject):
def height(self, value: float) -> None:
self.artificial_height = value
+ @deprecated("use get_center", category=None)
def get_location(self) -> Point3D:
"""Where the point is.
@@ -5892,6 +6048,7 @@ class VectorizedPoint(VMobject):
"""
return np.array(self.points[0])
+ @deprecated("use move_to", category=None)
def set_location(self, new_loc: Point3DLike) -> Self:
"""Move the point.
@@ -5974,8 +6131,7 @@ class VDict[T: Mobject = Mobject](Mobject):
) -> Self:
"""Add members by key, after the group's.
- Each is added as [add_key_value_pair][manimgx.VDict.add_key_value_pair] adds it,
- labeled with its key if the group shows its keys. A key the group has already
+ Each is labeled with its key if the group shows its keys. A key the group has already
is given the new mobject, but the old one stays in the group: to replace a
member, set it (`vdict[key] = mobject`).
@@ -6000,9 +6156,7 @@ class VDict[T: Mobject = Mobject](Mobject):
super().remove(self.submob_dict.pop(key))
return self
- def __getitem__(
- self, key: Hashable
- ) -> T: # ty: ignore[invalid-method-override] # CE's: by key
+ def __getitem__(self, key: Hashable) -> T: # ty: ignore[invalid-method-override] # CE's: by key
return self.submob_dict[key]
def __setitem__(self, key: Hashable, value: T) -> None:
@@ -6010,6 +6164,7 @@ class VDict[T: Mobject = Mobject](Mobject):
self.remove(key)
self.add([(key, value)])
+ @deprecated("use add({key: value})", category=None)
def add_key_value_pair(self, key: Hashable, value: T) -> Self:
"""Add a member with a key, after the group's.
@@ -6030,6 +6185,7 @@ class VDict[T: Mobject = Mobject](Mobject):
Mobject.add(self, value)
return self
+ @deprecated("use the group's submobjects", category=None)
def get_all_submobjects(self) -> list[T]:
"""The members, in the order of their keys.
@@ -6043,8 +6199,9 @@ class PMobject(Mobject):
"""A point cloud: a mobject drawn as points, each a dot of its own color.
Points are added with [add_points][manimgx.PMobject.add_points], each with a color;
- the style methods color them all. Each point is a disk `stroke_width` / 135 scene
- units across: at the default width, 4, about 3 pixels of a 720p frame.
+ the style methods color them all. Each point is a disk as wide as a stroke of its
+ `stroke_width`, a hundredth of a scene unit for each unit of width: at the default
+ width, 4, about 4 pixels of a 720p frame.
Args:
**kwargs: [Style keywords][manimgx.drawing.paint.Style]: `color` colors the points
@@ -6114,6 +6271,7 @@ class PMobject(Mobject):
self.paint = self.paint.but(fill=np.append(self.paint.fill, rgbas, axis=0))
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_all_rgbas(self) -> RGBA_Array:
"""The colors of every point of the cloud's family, member after member.
@@ -6125,6 +6283,7 @@ class PMobject(Mobject):
or [np.zeros((0, 4))]
)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def match_colors(self, mobject: Mobject) -> Self:
"""Give the cloud another cloud's colors, point for point.
@@ -6147,8 +6306,9 @@ class PMobject(Mobject):
if factor < 1:
raise ValueError("factor must be positive")
for mob in self.family_members_with_points():
- mob.points, mob.paint = mob.points[::factor], mob.paint.but(
- fill=mob.paint.fill[::factor].copy()
+ mob.points, mob.paint = (
+ mob.points[::factor],
+ mob.paint.but(fill=mob.paint.fill[::factor].copy()),
)
return self
@@ -6163,12 +6323,17 @@ class PMobject(Mobject):
return Point(self.get_center() if center is None else center)
def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
- lo, hi = (int(x * mobject.get_num_points()) for x in (a, b))
+ # every point the stretch reaches into, as a reveal over it shows them
+ n = mobject.get_num_points()
+ lo = min(max(math.floor(a * n), 0), n)
+ hi = min(max(math.ceil(b * n), lo), n)
+ fill = mobject.paint.fill
self.points = mobject.points[lo:hi]
- self.paint = self.paint.but(fill=mobject.paint.fill[lo:hi])
+ self.paint = self.paint.but(fill=fill[lo:hi] if len(fill) == n else fill)
return self
+@deprecated("Manim CE's base of point clouds along lines: use PMobject", category=None)
class Mobject1D(PMobject):
"""A point cloud of lines: points evenly spaced along each, `density` to a unit.
@@ -6228,10 +6393,18 @@ class Mobject1D(PMobject):
return self.add_points(points, color=color)
-PGroup = Group # a group is a group: kinds belong to leaves
-"""Another name for [Group][manimgx.Group], which holds mobjects of any kind."""
+if TYPE_CHECKING:
+ @deprecated("PGroup is Group: use Group, or VGroup", category=None)
+ class PGroup[T: Mobject = Mobject](Group[T]):
+ """Manim CE's group of point clouds: [Group][manimgx.Group], which holds
+ mobjects of any kind."""
+else:
+ PGroup = Group # a group is a group: kinds belong to leaves
+
+
+@deprecated("Manim CE's one-point cloud: use VectorizedPoint, or Dot", category=None)
class Point(PMobject):
"""A point cloud of one point, black unless colored: unseen on the default black
background.
@@ -6264,7 +6437,7 @@ class Point(PMobject):
color: Colors | None = None,
**kwargs: Unpack[StyleBase],
) -> None:
- self.location = location
+ self.location = np.array(location, dtype=float) # its own, as it was given
super().__init__(
**(Style(**kwargs) if color is None else Style(**kwargs, color=color))
)
@@ -6344,31 +6517,33 @@ class MeshMobject(Mobject):
texture: "np.ndarray | Camera | None" = None,
**kwargs: Unpack[Style],
) -> None:
- self._init_mesh = (vertices, triangles, uvs)
- self._vertex_colors = vertex_colors
- self._texture = texture
+ # values, as they are given: regenerated, the mesh is what it was made of
+ self._init_mesh = (
+ None if vertices is None else np.array(vertices),
+ None if triangles is None else np.array(triangles),
+ None if uvs is None else np.array(uvs),
+ )
+ self._vertex_colors = None if vertex_colors is None else np.array(vertex_colors)
+ self._texture = _value(texture) if isinstance(texture, np.ndarray) else texture
super().__init__(**kwargs)
@property
def triangles(self) -> np.ndarray:
- """The mesh's readonly (m, 3) triangle indices; for a lattice these are its
- coarse cell triangles.
+ """The mesh's readonly (m, 3) triangle indices; for a lattice these are the
+ coarse triangles of the faces it draws, two each.
Equal assignment is a no-op. Ordinary meshes snapshot replacement indices;
a sampled lattice requires constructing an explicit MeshMobject instead.
"""
- return (
- grid_triangles(*self._topology)
- if isinstance(self._topology, tuple)
- else self._topology
- )
+ topology = self._topology
+ return topology.triangles() if isinstance(topology, Lattice) else topology
@triangles.setter
def triangles(self, value: npt.ArrayLike) -> None:
array = np.asarray(value, dtype=np.int64)
array = array if array.shape[1:] == (3,) else array.reshape(-1, 3)
held = self.__dict__.get("_topology")
- if isinstance(held, tuple):
+ if isinstance(held, Lattice):
if np.array_equal(array, self.triangles):
return
raise ValueError(
@@ -6398,9 +6573,11 @@ class MeshMobject(Mobject):
A (u, v) lattice has (u + 1) * (v + 1) samples. Its fill rows belong to cells
and UVs to samples; ordinary mesh fill rows belong to vertices. match_points
- adopts this domain while retaining its recipient's style.
+ adopts this domain while retaining its recipient's style. A part of a surface
+ has its whole lattice, and draws some of its faces.
"""
- return self._topology if isinstance(self._topology, tuple) else None
+ topology = self._topology
+ return (topology.u, topology.v) if isinstance(topology, Lattice) else None
def generate_points(self) -> Self:
vertices, triangles, uvs = self._init_mesh
@@ -6433,11 +6610,12 @@ class MeshMobject(Mobject):
index, np.arange(len(index))
):
return
- grid = self.grid
- if grid is not None:
- if len(self.paint.fill) > 1:
- cells = stretch_array(self.paint.fill, grid[0] * grid[1])
- self.paint = self.paint.but(fill=np.repeat(cells, 6, axis=0))
+ topology = self._topology
+ if isinstance(topology, Lattice):
+ if len(self.paint.fill) > 1: # its faces' rows, one per corner of each
+ cells = stretch_array(self.paint.fill, topology.u * topology.v)
+ drawn = cells[topology.first : topology.end]
+ self.paint = self.paint.but(fill=np.repeat(drawn, 6, axis=0))
elif len(self.paint.fill) == len(self.points) > 1:
self.paint = self.paint.but(fill=self.paint.fill[index])
self.points = self.points[index]
@@ -6491,22 +6669,49 @@ class MeshMobject(Mobject):
point.paint = self.paint
return point
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def pointwise_become_partial(self, mobject: Mobject, a: float, b: float) -> Self:
- """Take a source's geometry and paint, then select a fraction of its triangles.
+ """Take a source's geometry and paint, then keep the steps a reveal over the
+ stretch shows, whole: a surface's faces, or a mesh's triangles.
- A whole interval retains lattice topology; an actual subset uses explicit
- triangles with each corner's paint and UV. Repeated calls restart from source.
+ A surface's part is a surface: its whole lattice, drawing those faces, as smooth
+ and with the edges they have in it. A mesh's part is its triangles alone, each
+ corner with its paint and UV. Repeated calls restart from source.
"""
if isinstance(mobject, MeshMobject):
self._geometry = mobject._geometry
self._take_shape(mobject)
self.paint = mobject.paint
- if not (a <= 0 and b >= 1):
- self._as_soup()
- t = len(self.triangles)
- self._topology = self.triangles[int(a * t) : int(np.ceil(b * t))]
+ topology = self._topology
+ lattice = isinstance(topology, Lattice)
+ n = topology.end - topology.first if lattice else len(topology)
+ lo = min(max(math.floor(a * n), 0), n)
+ hi = min(max(math.ceil(b * n), lo), n)
+ if (lo, hi) == (0, n):
+ return self
+ if isinstance(topology, Lattice):
+ first = topology.first
+ self._topology = topology._replace(first=first + lo, end=first + hi)
+ return self
+ self._as_soup() # three corners a triangle, in order: keep the part's own
+ self.points = self.points[3 * lo : 3 * hi]
+ if len(self.paint.fill) == 3 * n > 1:
+ self.paint = self.paint.but(fill=self.paint.fill[3 * lo : 3 * hi])
+ if self.uvs is not None:
+ self.uvs = self.uvs[3 * lo : 3 * hi]
+ self._topology = _value(np.arange(3 * (hi - lo)).reshape(-1, 3))
return self
+ def _box(self) -> np.ndarray | None:
+ # a part of a surface keeps its whole lattice: its box is its drawn faces'
+ topology = self._topology
+ if not isinstance(topology, Lattice) or topology.end - topology.first == (
+ topology.u * topology.v
+ ):
+ return super()._box()
+ drawn = self.points[np.unique(topology.triangles())]
+ return np.array([drawn.min(axis=0), drawn.max(axis=0)]) if len(drawn) else None
+
def interpolate(
self,
mobject1: Mobject,
diff --git a/src/manimgx/mobjects/graph.py b/src/manimgx/mobjects/graph.py
new file mode 100644
index 00000000..9b5534d0
--- /dev/null
+++ b/src/manimgx/mobjects/graph.py
@@ -0,0 +1,1035 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
+"""Ported from Manim CE 0.21 (MIT)."""
+
+from __future__ import annotations
+
+__all__ = ["DiGraph", "Graph"]
+import itertools as it
+from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence
+from collections.abc import Set as AbstractSet
+from copy import copy
+from typing import (
+ TYPE_CHECKING,
+ Concatenate,
+ Literal,
+ Protocol,
+ Self,
+ TypedDict,
+ TypeIs,
+ Unpack,
+ cast,
+ get_args,
+)
+
+import numpy as np
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from manimgx.typing import Point3D, Point3DLike
+
+ type NxGraph = nx.classes.graph.Graph | nx.classes.digraph.DiGraph
+from manimgx.drawing.paint import BLACK, ParsableManimColor
+from manimgx.mobject import Group, Mobject, VMobject
+from manimgx.mobjects.annotations import LabeledDot
+from manimgx.mobjects.shapes import ArrowTip, Dot, Line
+from manimgx.mobjects.text import MathTex
+
+type Edge[V] = tuple[V, V]
+"""An edge: the pair of its vertices, from the first to the second."""
+type Maker = Callable[
+ ..., Mobject
+] # a vertex or edge class: its keywords come from the configs
+"""What makes a vertex or an edge: a class, as [Dot][manimgx.Dot] or
+[Line][manimgx.Line], called with the keywords of its config."""
+type Config = dict[
+ str, object
+] # keywords for a vertex's or an edge's class (checked by it)
+type NxLayout = Callable[
+ ..., Mapping[Hashable, np.ndarray]
+] # networkx's layouts, given our layout configs
+
+
+def _nx_layout(
+ layout: NxLayout, graph: NxGraph, **kwargs: object
+) -> dict[Hashable, Point3D]:
+ """A networkx layout with our layout config (networkx checks the keywords)."""
+ return {k: np.asarray(p, dtype=float) for k, p in layout(graph, **kwargs).items()}
+
+
+def _make(maker: Maker, config_: Config) -> Mobject:
+ """A vertex or edge from its class and its config (the class checks the keywords)."""
+ return maker(**config_)
+
+
+class TipConfig(TypedDict, total=False):
+ """The tip of a [DiGraph][manimgx.DiGraph]'s edge, given as `"tip_config"` in its
+ `edge_config`: for every edge, or an edge's own (see
+ [add_tip][manimgx.TipableVMobject.add_tip])."""
+
+ tip_shape: type[ArrowTip] | None
+ """The class of the tip (default None:
+ [ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip])."""
+ tip_length: float | None
+ """The tip's length, in scene units (default None: the edge's default)."""
+ tip_width: float | None
+ """The tip's width, in scene units, for the default filled triangle (default None:
+ its length)."""
+
+
+class Positions[V](Protocol):
+ """Where vertices go: anything a vertex looks its point up in (a dict, a layout's result)."""
+
+ def __getitem__(self, vertex: V, /) -> Point3DLike: ...
+
+
+# A layout: the networkx graph, `scale` and the layout config's keywords, to positions.
+type LayoutFunction[V] = Callable[Concatenate[NxGraph, ...], Positions[V]]
+"""A layout of one's own: a function of the graph (a NetworkX graph), called with its
+`scale` and the keywords of the layout config, that returns each vertex's position.
+Each call receives a fresh graph of the current vertices and edges. Changes to that
+graph affect only this call; keep any persistent layout state in the function itself."""
+
+
+def _partite_layout(
+ nx_graph: NxGraph,
+ scale: float = 2,
+ partitions: Sequence[Sequence[Hashable]] | None = None,
+ **kwargs: object,
+) -> dict[Hashable, Point3D]:
+ import networkx as nx
+
+ if partitions is None or len(partitions) == 0:
+ raise ValueError(
+ "The partite layout requires partitions parameter to contain the partition"
+ " of the vertices"
+ )
+ partition_count = len(partitions)
+ for i in range(partition_count):
+ for v in partitions[i]:
+ if nx_graph.nodes[v] is None:
+ raise ValueError(
+ "The partition must contain arrays of vertices in the graph"
+ )
+ nx_graph.nodes[v]["subset"] = i
+ for v in nx_graph.nodes:
+ if "subset" not in nx_graph.nodes[v]:
+ nx_graph.nodes[v]["subset"] = partition_count
+ return _nx_layout(nx.layout.multipartite_layout, nx_graph, scale=scale, **kwargs)
+
+
+def _tree_layout(
+ T: NxGraph,
+ root_vertex: Hashable | None = None,
+ scale: float | tuple[float | None, float | None] | None = 2,
+ vertex_spacing: tuple[float, float] | None = None,
+ orientation: str = "down",
+) -> dict[Hashable, Point3D]:
+ import networkx as nx
+
+ if root_vertex is None:
+ raise ValueError("The tree layout requires the root_vertex parameter")
+ if not nx.is_tree(T):
+ raise ValueError("The tree layout must be used with trees")
+ children = {root_vertex: list(T.neighbors(root_vertex))}
+ stack = [list(children[root_vertex]).copy()]
+ stick = [root_vertex]
+ parent = dict.fromkeys(children[root_vertex], root_vertex)
+ pos: dict[Hashable, tuple[float, int]] = {}
+ obstruction = [0.0] * len(T)
+ o = -1 if orientation == "down" else 1
+
+ def slide(v: Hashable, dx: float) -> None:
+ level = [v]
+ while level:
+ nextlevel = []
+ for u in level:
+ x, y = pos[u]
+ x += dx
+ obstruction[y] = max(x + 1, obstruction[y])
+ pos[u] = (x, y)
+ nextlevel += children[u]
+ level = nextlevel
+
+ while stack:
+ C = stack[-1]
+ if not C:
+ p = stick.pop()
+ stack.pop()
+ cp = children[p]
+ y = o * len(stack)
+ if not cp:
+ x = obstruction[y]
+ pos[p] = (x, y)
+ else:
+ x = sum(pos[c][0] for c in cp) / float(len(cp))
+ pos[p] = (x, y)
+ ox = obstruction[y]
+ if x < ox:
+ slide(p, ox - x)
+ x = ox
+ obstruction[y] = x + 1
+ continue
+ t = C.pop()
+ pt = parent[t]
+ ct = [u for u in list(T.neighbors(t)) if u != pt]
+ for c in ct:
+ parent[c] = t
+ children[t] = copy(ct)
+ stack.append(ct)
+ stick.append(t)
+ x_min = min(pos.values(), key=lambda t: t[0])[0]
+ x_max = max(pos.values(), key=lambda t: t[0])[0]
+ y_min = min(pos.values(), key=lambda t: t[1])[1]
+ y_max = max(pos.values(), key=lambda t: t[1])[1]
+ center = np.array([x_min + x_max, y_min + y_max, 0]) / 2
+ height = y_max - y_min
+ width = x_max - x_min
+ if vertex_spacing is None:
+ sf: float | np.ndarray
+ if isinstance(scale, (float, int)) and (width > 0 or height > 0):
+ sf = 2 * scale / max(width, height)
+ elif isinstance(scale, tuple):
+ sw = 2 * scale[0] / width if scale[0] is not None and width > 0 else 1
+ sh = 2 * scale[1] / height if scale[1] is not None and height > 0 else 1
+ sf = np.array([sw, sh, 0])
+ else:
+ sf = 1
+ else:
+ sx, sy = vertex_spacing
+ sf = np.array([sx, sy, 0])
+ return {v: (np.array([x, y, 0]) - center) * sf for v, (x, y) in pos.items()}
+
+
+def _kamada_kawai_layout(
+ graph: nx.Graph,
+ dist: dict[Hashable, dict[Hashable, float]] | None = None,
+ pos: Mapping[Hashable, Point3DLike] | None = None,
+ weight: str = "weight",
+ scale: float = 1,
+ center: Point3DLike | None = None,
+ dim: int = 2,
+) -> dict[Hashable, np.ndarray]:
+ """networkx's Kamada–Kawai layout without scipy: the same energy from the same circular
+ start, minimized by stress majorization (monotone, deterministic) instead of L-BFGS.
+ """
+ import networkx as nx
+
+ nodes = list(graph)
+ n = len(nodes)
+ if n == 0:
+ return {}
+ if dist is None:
+ dist = {
+ a: dict(row) for a, row in nx.shortest_path_length(graph, weight=weight)
+ }
+ d = np.full((n, n), 1e6)
+ for i, a in enumerate(nodes):
+ for j, b in enumerate(nodes):
+ if b in dist.get(a, {}):
+ d[i, j] = dist[a][b]
+ np.fill_diagonal(d, 0.0)
+ start = nx.circular_layout(graph, dim=2) if pos is None else pos
+ x = np.array([np.resize(np.asarray(start[v], dtype=float), dim) for v in nodes])
+ w = np.where(d > 0, 1.0 / np.maximum(d, 1e-12) ** 2, 0.0)
+ v_plus = np.linalg.pinv(np.diag(w.sum(axis=1)) - w)
+ stress = np.inf
+ for _ in range(3000):
+ gaps = np.linalg.norm(x[:, None] - x[None], axis=2)
+ b = -w * d / np.where(gaps > 1e-12, gaps, np.inf)
+ np.fill_diagonal(b, -b.sum(axis=1))
+ x = v_plus @ b @ x
+ new = float(np.sum(w * (np.linalg.norm(x[:, None] - x[None], axis=2) - d) ** 2))
+ if stress - new < 1e-12 * max(stress, 1.0):
+ break
+ stress = new
+ x -= x.mean(axis=0)
+ if (limit := np.abs(x).max()) > 0:
+ x *= scale / limit
+ if center is not None:
+ x += np.asarray(center, dtype=float)[:dim]
+ return dict(zip(nodes, x, strict=True))
+
+
+LayoutName = Literal[
+ "circular",
+ "kamada_kawai",
+ "partite",
+ "planar",
+ "shell",
+ "spectral",
+ "spiral",
+ "spring",
+ "tree",
+]
+"""The names of the layouts a graph is laid out by (see
+[GenericGraph][manimgx.mobjects.graph.GenericGraph]): NetworkX's, and `"partite"` and
+`"tree"` of their own."""
+
+
+def _layout(name: LayoutName) -> LayoutFunction[Hashable]:
+ import networkx as nx
+
+ return {
+ "circular": nx.layout.circular_layout,
+ "kamada_kawai": _kamada_kawai_layout,
+ "partite": _partite_layout,
+ "planar": nx.layout.planar_layout,
+ "shell": nx.layout.shell_layout,
+ "spectral": nx.layout.spectral_layout,
+ "spiral": nx.layout.spiral_layout,
+ "spring": nx.layout.spring_layout,
+ "tree": _tree_layout,
+ }[name]
+
+
+type Layout[V] = LayoutName | str | Positions[V] | LayoutFunction[
+ V
+] # a layout's name, checked when used
+"""Where a graph's vertices go: a layout's name, the vertices' positions (a dictionary
+from each vertex to its point), or a layout function."""
+
+
+def _is_function[V](layout: Layout[V]) -> TypeIs[LayoutFunction[V]]:
+ return callable(layout)
+
+
+def _is_name(layout: object) -> TypeIs[LayoutName]:
+ return isinstance(layout, str) and layout in get_args(LayoutName)
+
+
+class VertexOptions[V: Hashable](TypedDict, total=False):
+ """[add_vertices][manimgx.mobjects.graph.GenericGraph.add_vertices]' keywords, for
+ the methods that pass them on: where the new vertices go, their labels, their kind
+ and their keywords."""
+
+ positions: Mapping[V, Point3DLike] | None
+ """Where new vertices go, by vertex (default None: at the graph's center)."""
+ labels: bool | Mapping[V, bool | Mobject]
+ """Whether each new vertex is labeled with its name, typeset as math: True for
+ all, or by vertex, True or a label of one's own (default False)."""
+ label_fill_color: ParsableManimColor
+ """The color of the labels made from names (default black)."""
+ vertex_type: Maker
+ """The class of the new vertices (default [Dot][manimgx.Dot]; a labeled one is a
+ [LabeledDot][manimgx.LabeledDot])."""
+ vertex_config: Configs | None
+ """Keywords for the new vertices, over the graph's: for all of them, and a vertex's
+ own under its name, in place of those for all (default None: none)."""
+ vertex_mobjects: Mapping[V, Mobject] | None
+ """Mobjects to be vertices themselves, by vertex (default None: none)."""
+
+
+class EdgeOptions[V: Hashable](VertexOptions[V], total=False):
+ """[add_edges][manimgx.mobjects.graph.GenericGraph.add_edges]' keywords: the new
+ edges' kind and keywords, with the vertices' keywords for the vertices they add."""
+
+ edge_type: Maker
+ """The class of the new edges (default [Line][manimgx.Line])."""
+ edge_config: Configs | None
+ """Keywords for the new edges, over the graph's: for all of them, and an edge's own
+ under its pair of vertices, in place of those for all (default None: none)."""
+
+
+class GraphOptions[V: Hashable](TypedDict, total=False):
+ """A graph's keywords but its vertices and edges, for the methods that pass them on
+ ([from_networkx][manimgx.mobjects.graph.GenericGraph.from_networkx], a
+ [Polyhedron][manimgx.Polyhedron]'s `graph_config`): its labels, layout, and the
+ kinds and keywords of its vertices and edges."""
+
+ labels: bool | Mapping[V, Mobject]
+ """Whether each vertex is labeled with its name, typeset as math, or a label for
+ each (default False)."""
+ label_fill_color: ParsableManimColor
+ """The color of the labels made from names (default black)."""
+ layout: Layout[V]
+ """Where the vertices go: a layout's name, their positions, or a layout function
+ (default `"spring"`)."""
+ layout_scale: float | tuple[float, float, float]
+ """How far the layout reaches from the center, in scene units (default 2)."""
+ layout_config: Mapping[str, object] | None
+ """Keywords for the layout function: a `"spring"` layout's `seed`, … (default None:
+ none)."""
+ vertex_type: Maker
+ """The class of the vertices (default [Dot][manimgx.Dot]; a labeled one is a
+ [LabeledDot][manimgx.LabeledDot])."""
+ vertex_config: Configs | None
+ """Keywords for the vertices: for all of them, and a vertex's own under its name, in
+ place of those for all (default None: none)."""
+ vertex_mobjects: Mapping[V, Mobject] | None
+ """Mobjects to be vertices themselves, by vertex (default None: none)."""
+ edge_type: Maker
+ """The class of the edges (default [Line][manimgx.Line])."""
+ partitions: Sequence[Sequence[V]] | None
+ """For the `"partite"` layout: the vertices of each column, in order (default None:
+ none)."""
+ root_vertex: V | None
+ """For the `"tree"` layout: the vertex at its top (default None: none)."""
+ edge_config: Configs | None
+ """Keywords for the edges: for all of them, and an edge's own under its pair of
+ vertices, in place of those for all (default None: none)."""
+
+
+class Configs(Protocol):
+ """Keywords for vertices (or edges): a dictionary of keywords for all of them, and
+ of a vertex's own keywords under its name (an edge's under its pair of vertices)."""
+
+ # any key type: a Mapping's key type is invariant
+
+ def items(self) -> AbstractSet[tuple[object, object]]: ...
+
+
+def _split[K: Hashable](
+ configs: Configs | None, items: Iterable[K]
+) -> tuple[Config, dict[K, Config]]:
+ """The keywords for all, and each item's own (given under the item)."""
+ given: dict[object, object] = dict(configs.items()) if configs is not None else {}
+ names = set(items)
+ shared: Config = {
+ k: v for k, v in given.items() if isinstance(k, str) and k not in names
+ }
+ return shared, {
+ k: dict(cast("Mapping[str, object]", given[k])) for k in names if k in given
+ }
+
+
+class GenericGraph[V: Hashable = Hashable](VMobject):
+ """What [Graph][manimgx.Graph] and [DiGraph][manimgx.DiGraph] have in common:
+ vertices and edges, laid out and kept together; white dots and lines unless
+ styled.
+
+ The vertices are any hashable values (numbers, strings, …): each is made a mobject,
+ a [Dot][manimgx.Dot] by default, and `graph[v]` is the mobject of vertex `v`. The
+ edges are pairs of vertices: each is made a mobject, a [Line][manimgx.Line] by
+ default, drawn behind the vertices (z-index -1), and `graph[(u, v)]` is the mobject
+ of edge `(u, v)`. An updater keeps the edges on their vertices: move a vertex (or
+ animate it) and its edges follow. Vertices and edges can be added and removed, and
+ the whole graph laid out anew.
+
+ The layout places the vertices: by a name — NetworkX's `"circular"`,
+ `"kamada_kawai"`, `"planar"`, `"shell"`, `"spectral"`, `"spiral"` and `"spring"`
+ (random unless given a `seed` in `layout_config`), or `"partite"` (in columns, by
+ `partitions`) and `"tree"` (down from `root_vertex`) — by a dictionary of positions,
+ or by a function of one's own. It spans about `layout_scale` from the center, the
+ center at the scene's origin; points of two coordinates lie in the plane z = 0.
+
+ Construction places vertices before creating edges, without calling an overridden
+ `change_layout`. The `_empty_networkx_graph` factory runs after vertex creation for
+ named or custom layouts; a position mapping does not call it.
+
+ Args:
+ vertices: The vertices: hashable values, each a vertex's name.
+ edges: The edges, each a pair of vertices.
+ labels: Whether each vertex is labeled with its name, typeset as math (a
+ vertex that is a [Dot][manimgx.Dot] becomes a
+ [LabeledDot][manimgx.LabeledDot]); or a label for each, by vertex.
+ label_fill_color: The color of the labels made from names.
+ layout: Where the vertices go: a layout's name, their positions (a dictionary
+ from each vertex to its point), or a layout function, called with the
+ NetworkX graph, `scale` and the keywords of `layout_config`.
+ layout_scale: How far the layout reaches from the center, in scene units.
+ layout_config: Keywords for the layout function; None for none.
+ vertex_type: The class of the vertices, called with each vertex's keywords.
+ vertex_config: Keywords for the vertices: for all of them, and a vertex's own
+ under its name, in place of those for all, as in
+ `{"radius": 0.2, 3: {"color": RED}}`; None for none.
+ vertex_mobjects: Mobjects to be vertices themselves, by vertex; None for none.
+ edge_type: The class of the edges, called with each edge's ends and keywords.
+ partitions: For the `"partite"` layout: the vertices of each column, in order
+ (those of none make a last column); None for none.
+ root_vertex: For the `"tree"` layout: the vertex at its top; None for none.
+ edge_config: Keywords for the edges: for all of them, and an edge's own under
+ its pair of vertices, in place of those for all; a DiGraph's tips under
+ `"tip_config"`. None for none.
+ """
+
+ edges: dict[Edge[V], Mobject]
+ """The edges' mobjects, by pair of vertices."""
+
+ def __init__(
+ self,
+ vertices: Sequence[V],
+ edges: Sequence[Edge[V]],
+ labels: bool | Mapping[V, Mobject] = False,
+ label_fill_color: ParsableManimColor = BLACK,
+ layout: Layout[V] = "spring",
+ layout_scale: float | tuple[float, float, float] = 2,
+ layout_config: Mapping[str, object] | None = None,
+ vertex_type: Maker = Dot,
+ vertex_config: Configs | None = None,
+ vertex_mobjects: Mapping[V, Mobject] | None = None,
+ edge_type: Maker = Line,
+ partitions: Sequence[Sequence[V]] | None = None,
+ root_vertex: V | None = None,
+ edge_config: Configs | None = None,
+ ) -> None:
+ super().__init__()
+ if isinstance(labels, Mapping):
+ labels_by_vertex: dict[V, Mobject] = dict(labels)
+ else:
+ labels_by_vertex = (
+ {v: MathTex(str(v), color=label_fill_color) for v in vertices}
+ if labels
+ else {}
+ )
+ if labels_by_vertex and vertex_type is Dot:
+ vertex_type = LabeledDot
+ self.default_vertex_config, own = _split(vertex_config, vertices)
+ vertex_configs: dict[V, Config] = {
+ v: own.get(v, copy(self.default_vertex_config)) for v in vertices
+ }
+ for v, label in labels_by_vertex.items():
+ vertex_configs[v]["label"] = label
+ self.vertices: dict[V, Mobject] = {
+ v: _make(vertex_type, vertex_configs[v]) for v in vertices
+ }
+ """The vertices' mobjects, by vertex."""
+ self.vertices.update(vertex_mobjects or {})
+ self._place_vertices(
+ edges,
+ layout=layout,
+ layout_scale=layout_scale,
+ layout_config=layout_config,
+ partitions=partitions,
+ root_vertex=root_vertex,
+ )
+ edge_settings: dict[object, object] = (
+ dict(edge_config.items()) if edge_config is not None else {}
+ )
+ default_tip_config = cast("Config", edge_settings.pop("tip_config", {}))
+ self.default_edge_config, own_edges = _split(edge_settings, edges)
+ self._edge_config: dict[Edge[V], Config] = {}
+ self._tip_config: dict[Edge[V], Config] = {}
+ for e in edges:
+ config_ = own_edges.get(e, copy(self.default_edge_config))
+ self._tip_config[e] = cast(
+ "Config", config_.pop("tip_config", copy(default_tip_config))
+ )
+ self._edge_config[e] = config_
+ self._populate_edge_dict(edges, edge_type)
+ self.add(*self.vertices.values())
+ self.add(*self.edges.values())
+ self.add_updater(self.update_edges)
+
+ @staticmethod
+ def _empty_networkx_graph() -> NxGraph:
+ raise NotImplementedError("To be implemented in concrete subclasses")
+
+ def _make_edge(self, edge_type: Maker, u: V, v: V, config_: Config) -> Mobject:
+ raise NotImplementedError("To be implemented in concrete subclasses")
+
+ def update_edges(self, graph: Mobject) -> Self:
+ """Put each edge back on its vertices, where they are now: the updater a graph
+ runs every frame, so that its edges follow its vertices.
+
+ Each kind of graph sets its edges' ends its own way: an undirected graph's from
+ center to center, a directed graph's from outline to outline, with its tip.
+ Only edges that are lines ([Line][manimgx.Line] and its kinds) follow.
+
+ Args:
+ graph: The mobject the updater runs for (the graph); unused.
+ """
+ raise NotImplementedError("To be implemented in concrete subclasses")
+
+ def _populate_edge_dict(self, edges: Iterable[Edge[V]], edge_type: Maker) -> None:
+ self.edges = {
+ (u, v): self._make_edge(edge_type, u, v, self._edge_config[u, v])
+ for u, v in edges
+ }
+
+ def __getitem__( # pyright: ignore[reportIncompatibleMethodOverride] # ty: ignore[invalid-method-override] # CE: a graph is indexed by vertex and edge, not position
+ self, k: V | Edge[V]
+ ) -> Mobject:
+ if k in self.vertices:
+ return self.vertices[cast("V", k)]
+ if k in self.edges:
+ return self.edges[cast("Edge[V]", k)]
+ raise ValueError(f"Could not find {k} in vertices or edges")
+
+ def _create_vertex(
+ self,
+ vertex: V,
+ position: Point3DLike | None = None,
+ label: bool | Mobject = False,
+ label_fill_color: ParsableManimColor = BLACK,
+ vertex_type: Maker = Dot,
+ vertex_config: Config | None = None,
+ vertex_mobject: Mobject | None = None,
+ ) -> tuple[V, Point3D, Mobject]:
+ np_position: Point3D = (
+ self.get_center() if position is None else np.asarray(position, dtype=float)
+ )
+ if vertex in self.vertices:
+ raise ValueError(
+ f"Vertex identifier '{vertex}' is already used for a vertex in this"
+ " graph."
+ )
+ if label is True:
+ label_mob: Mobject | None = MathTex(str(vertex), color=label_fill_color)
+ else:
+ label_mob = label if isinstance(label, Mobject) else None
+ config_ = copy(self.default_vertex_config) | (vertex_config or {})
+ if label_mob is not None:
+ config_["label"] = label_mob
+ if vertex_type is Dot:
+ vertex_type = LabeledDot
+ mob = (
+ vertex_mobject
+ if vertex_mobject is not None
+ else _make(vertex_type, config_)
+ )
+ mob.move_to(np_position)
+ return vertex, np_position, mob
+
+ def _add_created_vertex(
+ self,
+ vertex: V,
+ position: Point3DLike,
+ vertex_mobject: Mobject,
+ ) -> Mobject:
+ if vertex in self.vertices:
+ raise ValueError(
+ f"Vertex identifier '{vertex}' is already used for a vertex in this"
+ " graph."
+ )
+ self.vertices[vertex] = vertex_mobject
+ vertex_mobject.move_to(position)
+ self.add(vertex_mobject)
+ return vertex_mobject
+
+ def _create_vertices(
+ self,
+ *vertices: V,
+ positions: Mapping[V, Point3DLike] | None = None,
+ labels: bool | Mapping[V, bool | Mobject] = False,
+ label_fill_color: ParsableManimColor = BLACK,
+ vertex_type: Maker = Dot,
+ vertex_config: Configs | None = None,
+ vertex_mobjects: Mapping[V, Mobject] | None = None,
+ ) -> list[tuple[V, Point3D, Mobject]]:
+ graph_center = self.get_center()
+ places = {v: (positions or {}).get(v, graph_center) for v in vertices}
+ marks = {
+ v: labels if isinstance(labels, bool) else labels.get(v, False)
+ for v in vertices
+ }
+ shared, own = _split(vertex_config, vertices)
+ base = copy(self.default_vertex_config) | shared
+ return [
+ self._create_vertex(
+ v,
+ position=places[v],
+ label=marks[v],
+ label_fill_color=label_fill_color,
+ vertex_type=vertex_type,
+ vertex_config=own.get(v, copy(base)),
+ vertex_mobject=(vertex_mobjects or {}).get(v),
+ )
+ for v in vertices
+ ]
+
+ def add_vertices(self, *vertices: V, **kwargs: Unpack[VertexOptions[V]]) -> Group:
+ """Add vertices to the graph, without edges.
+
+ Each is made as the graph makes its vertices, with the keywords given over the
+ graph's own, and placed at its position, or at the graph's center. A vertex
+ already in the graph raises a ValueError.
+
+ Args:
+ *vertices: The new vertices: hashable values, each a vertex's name.
+ **kwargs: [Vertex keywords][manimgx.mobjects.graph.VertexOptions]:
+ `positions`, `labels`, `vertex_type`, `vertex_config`, ….
+
+ Returns:
+ A new group of the new vertices' mobjects.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class GraphAddVerticesExample(m.Scene):
+ def construct(self) -> None:
+ graph = m.Graph(
+ [1, 2, 3],
+ [(1, 2), (2, 3)],
+ layout={1: [-4, -1, 0], 2: [0, -2, 0], 3: [4, -1, 0]},
+ vertex_config={"radius": 0.15},
+ )
+ self.add(graph)
+ top = graph.add_vertices(
+ 4, positions={4: [0, 2.5, 0]}, vertex_config={"color": m.YELLOW}
+ )
+ self.play(m.FadeIn(top, scale=3))
+ self.play(m.Create(graph.add_edges((1, 4), (3, 4))))
+ ```
+ """
+ return Group(
+ *(
+ self._add_created_vertex(*v)
+ for v in self._create_vertices(*vertices, **kwargs)
+ )
+ )
+
+ def _remove_vertex(self, vertex: V) -> Group:
+ if vertex not in self.vertices:
+ raise ValueError(
+ f"The graph does not contain a vertex with identifier '{vertex}'"
+ )
+ edge_tuples = [e for e in self.edges if vertex in e]
+ for e in edge_tuples:
+ self._edge_config.pop(e)
+ to_remove = [self.edges.pop(e) for e in edge_tuples]
+ to_remove.append(self.vertices.pop(vertex))
+ self.remove(*to_remove)
+ return Group(*to_remove)
+
+ def remove_vertices(self, *vertices: V) -> Group:
+ """Remove vertices from the graph, and the edges that touch them.
+
+ A vertex not in the graph raises a ValueError.
+
+ Args:
+ *vertices: The vertices to remove.
+
+ Returns:
+ A new group of the removed mobjects (for each vertex, its edges, then the
+ vertex), to fade out, for instance.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class GraphRemoveVerticesExample(m.Scene):
+ def construct(self) -> None:
+ graph = m.Graph(
+ [1, 2, 3, 4, 5],
+ [(1, 2), (2, 3), (3, 4), (4, 5), (5, 1), (1, 3)],
+ layout="circular",
+ layout_scale=3,
+ )
+ self.add(graph)
+ self.play(m.FadeOut(graph.remove_vertices(3)))
+ ```
+ """
+ return Group(*(m for v in vertices for m in self._remove_vertex(v).submobjects))
+
+ def _add_edge(
+ self, edge: Edge[V], edge_type: Maker = Line, edge_config: Config | None = None
+ ) -> Group:
+ u, v = edge
+ config_ = self.default_edge_config.copy() | (edge_config or {})
+ self._edge_config[u, v] = config_
+ edge_mobject = self._make_edge(edge_type, u, v, config_)
+ self.edges[u, v] = edge_mobject
+ self.add(edge_mobject)
+ return Group(edge_mobject)
+
+ def add_edges(self, *edges: Edge[V], **kwargs: Unpack[EdgeOptions[V]]) -> Group:
+ """Add edges to the graph, and the vertices they name that it lacks.
+
+ The missing vertices are added first, as
+ [add_vertices][manimgx.mobjects.graph.GenericGraph.add_vertices] adds them, with
+ the vertex keywords given; each edge is then made as the graph makes its edges,
+ with the edge keywords given over the graph's own.
+
+ Args:
+ *edges: The new edges, each a pair of vertices.
+ **kwargs: [Edge keywords][manimgx.mobjects.graph.EdgeOptions]: `edge_type`
+ (a [Line][manimgx.Line] unless given), `edge_config`, and the vertex
+ keywords for the new vertices.
+
+ Returns:
+ A new group of the new mobjects, the vertices added and then the edges.
+ """
+ edge_type = kwargs.pop("edge_type", Line)
+ shared, own = _split(kwargs.pop("edge_config", None), edges)
+ base = self.default_edge_config.copy() | shared
+ new_vertices = [
+ v for v in dict.fromkeys(it.chain(*edges)) if v not in self.vertices
+ ]
+ added = list(self.add_vertices(*new_vertices, **kwargs))
+ for edge in edges:
+ added.extend(
+ self._add_edge(
+ edge, edge_type=edge_type, edge_config=base | own.get(edge, {})
+ )
+ )
+ return Group(*added)
+
+ def _remove_edge(self, edge: Edge[V]) -> Mobject:
+ if edge not in self.edges:
+ raise ValueError(f"The graph does not contain a edge '{edge}'")
+ edge_mobject = self.edges.pop(edge)
+ self._edge_config.pop(edge, None)
+ self.remove(edge_mobject)
+ return edge_mobject
+
+ def remove_edges(self, *edges: Edge[V]) -> Group:
+ """Remove edges from the graph, keeping their vertices.
+
+ An edge not in the graph raises a ValueError.
+
+ Args:
+ *edges: The edges to remove, each a pair of vertices.
+
+ Returns:
+ A new group of the removed edges' mobjects.
+ """
+ return Group(*(self._remove_edge(edge) for edge in edges))
+
+ @classmethod
+ def from_networkx(cls, nxgraph: NxGraph, **kwargs: Unpack[GraphOptions[V]]) -> Self:
+ """Make a graph of a [NetworkX](https://networkx.org) graph's nodes and edges.
+
+ Args:
+ nxgraph: The NetworkX graph (a `Graph`, or a `DiGraph`).
+ **kwargs: [Graph keywords][manimgx.mobjects.graph.GraphOptions]: `layout`,
+ `labels`, `vertex_config`, ….
+
+ Returns:
+ A new graph.
+
+ Examples:
+ ```python
+ import networkx as nx
+
+ import manimgx as m
+
+
+ class GraphFromNetworkxExample(m.Scene):
+ def construct(self) -> None:
+ petersen = nx.petersen_graph()
+ graph = m.Graph.from_networkx(
+ petersen,
+ layout="shell",
+ layout_scale=3,
+ layout_config={"nlist": [range(5, 10), range(5)]},
+ )
+ self.play(m.Create(graph), run_time=2)
+ ```
+ """
+ return cls(list(nxgraph.nodes), list(nxgraph.edges), **kwargs)
+
+ def change_layout(
+ self,
+ layout: Layout[V] = "spring",
+ layout_scale: float | tuple[float, float, float] = 2,
+ layout_config: Mapping[str, object] | None = None,
+ partitions: Sequence[Sequence[V]] | None = None,
+ root_vertex: V | None = None,
+ ) -> Self:
+ """Lay the graph out anew: move each vertex to its place in a layout.
+
+ The vertices move at once, and the edges follow them at the next frame, as the
+ graph's updater moves them. To animate the change, animate each vertex to its
+ place in a changed copy (as below): the edges follow all the way.
+
+ A layout function gets a fresh NetworkX graph of the current vertices and edges.
+ Its node, edge and graph attributes belong to that call, not to later layouts.
+
+ Args:
+ layout: Where the vertices go: a layout's name, their positions, or a
+ layout function (see
+ [GenericGraph][manimgx.mobjects.graph.GenericGraph]).
+ layout_scale: How far the layout reaches from the center, in scene units.
+ layout_config: Keywords for the layout function; None for none.
+ partitions: For the `"partite"` layout: the vertices of each column; None
+ for none.
+ root_vertex: For the `"tree"` layout: the vertex at its top; None for none.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class GraphChangeLayoutExample(m.Scene):
+ def construct(self) -> None:
+ graph = m.Graph(
+ [1, 2, 3, 4, 5, 6],
+ [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1), (1, 4)],
+ layout={v: [2 * v - 7, 0, 0] for v in range(1, 7)},
+ )
+ circle = graph.copy().change_layout("circular", layout_scale=3)
+ self.add(graph)
+ self.play(
+ *(graph[v].animate.move_to(circle[v]) for v in graph.vertices)
+ )
+ ```
+ """
+ return self._place_vertices(
+ self.edges,
+ layout=layout,
+ layout_scale=layout_scale,
+ layout_config=layout_config,
+ partitions=partitions,
+ root_vertex=root_vertex,
+ )
+
+ def _place_vertices(
+ self,
+ edges: Iterable[Edge[V]],
+ layout: Layout[V] = "spring",
+ layout_scale: float | tuple[float, float, float] = 2,
+ layout_config: Mapping[str, object] | None = None,
+ partitions: Sequence[Sequence[V]] | None = None,
+ root_vertex: V | None = None,
+ ) -> Self:
+ """Place vertices from the edge keys: supplied before edges are made, otherwise
+ the keys of the graph's edges. A computed layout owns its temporary topology."""
+ config_ = dict(layout_config or {})
+ if partitions is not None:
+ config_.setdefault("partitions", partitions)
+ if root_vertex is not None:
+ config_.setdefault("root_vertex", root_vertex)
+ positions: Positions[V]
+ if _is_function(layout):
+ place = layout
+ elif _is_name(layout):
+ place = _layout(layout)
+ elif isinstance(layout, str):
+ raise ValueError(
+ f"The layout '{layout}' is neither a recognized layout, a layout"
+ " function, nor a vertex placement dictionary."
+ )
+ else:
+ place = None
+ positions = layout
+ if place is not None:
+ graph = self._empty_networkx_graph()
+ graph.add_nodes_from(self.vertices)
+ graph.add_edges_from(edges)
+ positions = place(graph, scale=layout_scale, **config_)
+ points = {v: np.asarray(positions[v], dtype=float) for v in self.vertices}
+ padded = {v: np.pad(p, (0, 3 - p.size)) for v, p in points.items()}
+ for v in self.vertices:
+ self[v].move_to(padded[v])
+ return self
+
+ def _edge_ends(self, edge: Edge[V]) -> tuple[float, float]:
+ """An edge's buffer and bend, as its config sets them (CE read them from the wrong
+ dictionary, so edges lost both at the first update)."""
+ config_ = self._edge_config.get(edge, {})
+ buff, path_arc = config_.get("buff", 0), config_.get("path_arc", 0)
+ return (buff if isinstance(buff, (int, float)) else 0), (
+ path_arc if isinstance(path_arc, (int, float)) else 0
+ )
+
+
+class Graph[V: Hashable = Hashable](GenericGraph[V]):
+ """An undirected graph: vertices joined by edges, laid out automatically or by hand;
+ white dots and lines unless styled.
+
+ Each edge runs from the center of one vertex to the center of the other, behind
+ them, and follows them as they move. It takes the arguments of a
+ [GenericGraph][manimgx.mobjects.graph.GenericGraph], which lists what a graph can do.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class GraphExample(m.Scene):
+ def construct(self) -> None:
+ vertices = [1, 2, 3, 4, 5, 6]
+ edges = [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1), (1, 4), (2, 5)]
+ graph = m.Graph(
+ vertices,
+ edges,
+ layout="circular",
+ layout_scale=3,
+ labels=True,
+ vertex_config={1: {"fill_color": m.RED}},
+ edge_config={(1, 4): {"stroke_color": m.YELLOW}},
+ )
+ self.play(m.Create(graph))
+ self.play(graph[3].animate.move_to([0, 0, 0]))
+ ```
+ """
+
+ @staticmethod
+ def _empty_networkx_graph() -> NxGraph:
+ import networkx as nx
+
+ return nx.Graph()
+
+ def _make_edge(self, edge_type: Maker, u: V, v: V, config_: Config) -> Mobject:
+ return edge_type(
+ start=self[u].get_center(), end=self[v].get_center(), z_index=-1, **config_
+ )
+
+ def update_edges(self, graph: Mobject) -> Self:
+ for (u, v), edge in self.edges.items():
+ if isinstance(edge, Line):
+ buff, path_arc = self._edge_ends((u, v))
+ edge.set_points_by_ends(
+ self[u].get_center(),
+ self[v].get_center(),
+ buff=buff,
+ path_arc=path_arc,
+ )
+ return self
+
+
+class DiGraph[V: Hashable = Hashable](GenericGraph[V]):
+ """A directed graph: vertices joined by arrows, from the first vertex of each edge
+ to the second; white dots and arrows unless styled.
+
+ Each edge runs from the outline of one vertex to the outline of the other and ends
+ in a tip, which the `"tip_config"` of `edge_config` shapes (see
+ [TipConfig][manimgx.mobjects.graph.TipConfig]), for every edge or an edge's own; it
+ follows its vertices as they move. It takes the arguments of a
+ [GenericGraph][manimgx.mobjects.graph.GenericGraph], which lists what a graph can do.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DiGraphExample(m.Scene):
+ def construct(self) -> None:
+ edge_config = {
+ "stroke_width": 3,
+ "tip_config": {"tip_length": 0.2, "tip_width": 0.2},
+ (3, 4): {
+ "color": m.RED,
+ "tip_config": {"tip_shape": m.ArrowSquareTip},
+ },
+ }
+ graph = m.DiGraph(
+ [0, 1, 2, 3, 4],
+ [(0, 1), (1, 2), (3, 2), (3, 4), (4, 0)],
+ labels=True,
+ layout="circular",
+ layout_scale=3,
+ edge_config=edge_config,
+ )
+ self.play(m.Create(graph))
+ ```
+ """
+
+ @staticmethod
+ def _empty_networkx_graph() -> NxGraph:
+ import networkx as nx
+
+ return nx.DiGraph()
+
+ def _make_edge(self, edge_type: Maker, u: V, v: V, config_: Config) -> Mobject:
+ edge = edge_type(start=self[u], end=self[v], z_index=-1, **config_)
+ if isinstance(edge, Line):
+ edge.add_tip(**cast("TipConfig", self._tip_config.get((u, v), {})))
+ return edge
+
+ def update_edges(self, graph: Mobject) -> Self:
+ for (u, v), edge in self.edges.items():
+ if isinstance(edge, Line):
+ tip = edge.pop_tips()[0]
+ buff, path_arc = self._edge_ends((u, v))
+ edge.set_points_by_ends(self[u], self[v], buff=buff, path_arc=path_arc)
+ edge.add_tip(tip)
+ return self
diff --git a/src/manimgx/mobjects/grid.py b/src/manimgx/mobjects/grid.py
new file mode 100644
index 00000000..72ea5a08
--- /dev/null
+++ b/src/manimgx/mobjects/grid.py
@@ -0,0 +1,1155 @@
+# SPDX-FileCopyrightText: 2026 Academa, Inc.
+# SPDX-FileCopyrightText: 2024 the Manim Community Developers
+# SPDX-FileCopyrightText: 2018 3Blue1Brown LLC
+# SPDX-License-Identifier: MIT
+
+"Rows and columns of entries: matrices place them between brackets; tables fit cells and rules."
+
+from __future__ import annotations
+
+import itertools as it
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from typing import ClassVar, Self, Unpack
+
+import numpy as np
+
+from manimgx.animation.motion import Create, FadeIn, Write
+from manimgx.animation.timeline import Animation, AnimationGroup, AnimationOptions
+from manimgx.constants import DOWN, DR, LEFT, MED_SMALL_BUFF, RIGHT, UP
+from manimgx.drawing.paint import (
+ BLACK,
+ PURE_YELLOW,
+ Colors,
+ ManimColor,
+ ParsableManimColor,
+ Style,
+)
+from manimgx.mobject import (
+ GridArrangement,
+ Mobject,
+ VGroup,
+ VMobject,
+ _family,
+ _family_box,
+)
+from manimgx.mobjects.annotations import BackgroundRectangle, FrameOptions
+from manimgx.mobjects.numbers import DecimalNumber, Integer
+from manimgx.mobjects.shapes import Line, LineOptions, Polygon
+from manimgx.mobjects.text import MathTex, MathTexOptions, Paragraph
+from manimgx.typing import Vector2DLike, Vector3DLike
+
+__all__ = [
+ "DecimalMatrix",
+ "DecimalTable",
+ "IntegerMatrix",
+ "IntegerTable",
+ "MathTable",
+ "Matrix",
+ "MobjectMatrix",
+ "MobjectTable",
+ "Table",
+]
+
+type Entries = Iterable[Iterable[object]] | Iterable[Vector2DLike]
+"""A matrix's entries, row by row: each row an iterable of entries, as its
+`element_to_mobject` takes them."""
+type ElementFactory = Callable[..., Mobject]
+"""What makes the mobject of a matrix's or a table's entry: called with the entry, and
+with the keywords of `element_to_mobject_config` (a class, as
+[MathTex][manimgx.MathTex], or any function)."""
+
+
+class MatrixOptions(Style, total=False):
+ """A [Matrix][manimgx.Matrix]'s keywords but its entries, for the methods that pass
+ them on (a [vector's coordinate label][manimgx.Vector.coordinate_label]): its
+ entries' kind, with its layout, brackets and style."""
+
+ v_buff: float
+ """The distance between rows, in scene units, from one row's entries' alignment
+ corners to the next's (default 0.8)."""
+ h_buff: float
+ """The distance between columns, in scene units, likewise (default 1.3)."""
+ bracket_h_buff: float
+ """The gap between the entries and each bracket, in scene units (default 0.25)."""
+ bracket_v_buff: float
+ """How far the brackets reach above and below the entries, in scene units, when
+ stretched (default 0.25)."""
+ add_background_rectangles_to_entries: bool
+ """Whether each entry gets a background rectangle (default False)."""
+ include_background_rectangle: bool
+ """Whether the matrix gets a background rectangle (default False)."""
+ element_alignment_corner: Vector3DLike
+ """The corner of each entry put on the grid, named by a direction: DR aligns the
+ entries of a column on their right, UL on their left (default DR)."""
+ left_bracket: str
+ r"""The left bracket, as a LaTeX delimiter: `"["`, `"("`, `"\{"`, `"\langle"`,
+ `"|"`, … (default `"["`)."""
+ right_bracket: str
+ """The right bracket, as a LaTeX delimiter (default `"]"`)."""
+ stretch_brackets: bool
+ """Whether the brackets are stretched to the entries' height, and `bracket_v_buff`
+ beyond (default True)."""
+ bracket_config: MathTexOptions | None
+ """[Math keywords][manimgx.mobjects.text.MathTexOptions] for the
+ brackets: their `color`, … (default None: none)."""
+
+ element_to_mobject: ElementFactory
+ """The function that makes each entry's mobject, called with the entry and the
+ keywords of `element_to_mobject_config` (default: the matrix class's own,
+ [MathTex][manimgx.MathTex] for a [Matrix][manimgx.Matrix])."""
+ element_to_mobject_config: Mapping[str, object] | None
+ """Keywords for `element_to_mobject` (default None: the matrix class's own, none
+ for a [Matrix][manimgx.Matrix])."""
+
+
+def _same(entry: Mobject) -> Mobject:
+ return entry
+
+
+class _Grid:
+ """Entries in rows and columns (`cells`), each made from its item by the class's `entry` with
+ its `entry_config`, unless the constructor is given others."""
+
+ entry: ClassVar[ElementFactory] = MathTex
+ """The function that makes each entry's mobject when the constructor is given no
+ `element_to_mobject`: a class, as [MathTex][manimgx.MathTex], or any function. A
+ subclass sets its own ([IntegerMatrix][manimgx.IntegerMatrix]'s is
+ [Integer][manimgx.Integer])."""
+ entry_config: ClassVar[Mapping[str, object]] = {}
+ """The keywords `entry` is called with when the constructor is given no
+ `element_to_mobject_config` (none, unless a subclass sets them)."""
+ cells: list[list[Mobject]]
+ """The entries' mobjects, as a list of rows from the top down, each a list of its
+ mobjects from left to right (a table's labels included)."""
+
+ def _make_cells(
+ self,
+ data: Iterable[Iterable[object]],
+ factory: ElementFactory | None,
+ config: Mapping[str, object] | None,
+ ) -> list[list[Mobject]]:
+ make = factory or type(self).entry
+ options = type(self).entry_config if config is None else config
+ return [[make(item, **options) for item in row] for row in data]
+
+ def get_rows(self) -> VGroup:
+ """The rows, from the top down, each a group of its entries from left to right
+ (a table's labels included).
+
+ Returns:
+ A new group of the rows.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MatrixGetRowsExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).scale(1.5)
+ row = m.SurroundingRectangle(matrix.get_rows()[1])
+ self.add(matrix)
+ self.play(m.Create(row))
+ ```
+ """
+ return VGroup(*(VGroup(*row) for row in self.cells))
+
+ def get_columns(self) -> VGroup:
+ """The columns, from left to right, each a group of its entries from the top
+ down (a table's labels included).
+
+ Returns:
+ A new group of the columns.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetColumnsExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ column = m.SurroundingRectangle(table.get_columns()[1])
+ self.add(table)
+ self.play(m.Create(column))
+ ```
+ """
+ return VGroup(*(VGroup(*column) for column in zip(*self.cells, strict=False)))
+
+ def set_row_colors(self, *colors: Colors) -> Self:
+ """Color the rows, from the top down: each one color, or several for a gradient
+ (as [set_color][manimgx.Mobject.set_color] makes one); rows past the last
+ color keep theirs.
+
+ Args:
+ *colors: The rows' colors, in order: a color each, or a list of colors.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MatrixSetRowColorsExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]).scale(1.5)
+ self.add(matrix.set_row_colors(m.RED, [m.YELLOW, m.GREEN]))
+ ```
+ """
+ for color, row in zip(colors, self.get_rows(), strict=False):
+ row.set_color(color)
+ return self
+
+ def set_column_colors(self, *colors: Colors) -> Self:
+ """Color the columns, from left to right: each one color, or several for a
+ gradient (as [set_color][manimgx.Mobject.set_color] makes one); columns past
+ the last color keep theirs.
+
+ Args:
+ *colors: The columns' colors, in order: a color each, or a list of colors.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableSetColumnColorsExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ self.add(table.set_column_colors(m.YELLOW, m.BLUE, m.GREEN))
+ ```
+ """
+ for color, column in zip(colors, self.get_columns(), strict=False):
+ column.set_color(color)
+ return self
+
+
+class Matrix(_Grid, VMobject):
+ r"""A matrix: entries in rows and columns between brackets; white unless styled.
+
+ Each entry is made into a mobject by `element_to_mobject` — by default typeset as
+ math, with [MathTex][manimgx.MathTex] — and put on a grid, rows `v_buff` apart and
+ columns `h_buff` apart, by its bottom right corner (`element_alignment_corner`): the
+ entries of a column are aligned on their right. Brackets, typeset as LaTeX
+ delimiters, stand on either side, stretched to the entries' height; the matrix is
+ centered on the scene's origin. Its [entries][manimgx.Matrix.get_entries] and
+ [brackets][manimgx.Matrix.get_brackets] can be reached, colored and animated, and
+ so can its rows and columns: `get_rows()` and `get_columns()` give them as groups,
+ `set_row_colors(...)` and `set_column_colors(...)` color them.
+
+ Layout and bracket options are used during construction; the resulting cells and
+ brackets hold the matrix's state.
+
+ Args:
+ matrix: The entries, row by row: numbers, strings of math or mobjects, as
+ `element_to_mobject` takes them.
+ v_buff: The distance between rows, in scene units, from one row's entries'
+ alignment corners to the next's.
+ h_buff: The distance between columns, in scene units, likewise.
+ bracket_h_buff: The gap between the entries and each bracket, in scene units.
+ bracket_v_buff: How far the brackets reach above and below the entries, in
+ scene units, when stretched.
+ add_background_rectangles_to_entries: Whether each entry gets a background
+ rectangle, in the scene's background color (see
+ [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
+ include_background_rectangle: Whether the matrix gets a background rectangle
+ (see [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
+ element_to_mobject: The function that makes each entry's mobject, called with
+ the entry and the keywords of `element_to_mobject_config`: a class, as
+ [DecimalNumber][manimgx.DecimalNumber], or any function; None for the
+ class's own (MathTex, for a Matrix).
+ element_to_mobject_config: Keywords for `element_to_mobject`; None for the
+ class's own (none, for a Matrix).
+ element_alignment_corner: The corner of each entry put on the grid, named by a
+ direction: DR aligns the entries of a column on their right, UL on their
+ left.
+ left_bracket: The left bracket, as a LaTeX delimiter: `"["`, `"("`, `"\{"`,
+ `"\langle"`, `"|"`, ….
+ right_bracket: The right bracket, as a LaTeX delimiter.
+ stretch_brackets: Whether the brackets are stretched to the entries' height,
+ and `bracket_v_buff` beyond.
+ bracket_config: [Math keywords][manimgx.mobjects.text.MathTexOptions]
+ for the brackets: their `color`, …; None for none.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the matrix itself: as it
+ has no points, they do not restyle its entries or its brackets.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MatrixExample(m.Scene):
+ def construct(self) -> None:
+ matrices = m.VGroup(
+ m.Matrix([[2, 0], [-1, 1]]),
+ m.Matrix(
+ [[r"\cos t", r"-\sin t"], [r"\sin t", r"\cos t"]],
+ h_buff=2,
+ left_bracket="(",
+ right_bracket=")",
+ ),
+ m.Matrix(
+ [[10, 2, 300], [4, 50, 6]],
+ element_alignment_corner=m.UL,
+ bracket_config={"color": m.BLUE},
+ ),
+ ).arrange(buff=1)
+ self.add(matrices)
+ ```
+ """
+
+ def __init__(
+ self,
+ matrix: Entries,
+ v_buff: float = 0.8,
+ h_buff: float = 1.3,
+ bracket_h_buff: float = MED_SMALL_BUFF,
+ bracket_v_buff: float = MED_SMALL_BUFF,
+ add_background_rectangles_to_entries: bool = False,
+ include_background_rectangle: bool = False,
+ element_to_mobject: ElementFactory | None = None,
+ element_to_mobject_config: Mapping[str, object] | None = None,
+ element_alignment_corner: Vector3DLike = DR,
+ left_bracket: str = "[",
+ right_bracket: str = "]",
+ stretch_brackets: bool = True,
+ bracket_config: MathTexOptions | None = None,
+ **kwargs: Unpack[Style],
+ ):
+ if bracket_config is None:
+ bracket_config = {}
+ super().__init__(**kwargs)
+ self.cells = self._make_cells(
+ matrix, element_to_mobject, element_to_mobject_config
+ )
+ cells = self.cells
+ for i, row in enumerate(cells):
+ for j, _ in enumerate(row):
+ mob = cells[i][j]
+ mob.move_to(
+ i * v_buff * DOWN + j * h_buff * RIGHT,
+ element_alignment_corner,
+ )
+ self.elements = VGroup(*it.chain(*self.cells))
+ """The entries, row by row: a group, added to the matrix."""
+ self.add(self.elements)
+ bracket_config = {**bracket_config}
+ BRACKET_HEIGHT = 0.5977
+ n = int(self.height / BRACKET_HEIGHT) + 1
+ empty_tex_array = "".join(
+ ["\\begin{array}{c}", *n * ["\\quad \\\\"], "\\end{array}"]
+ )
+ tex_left = "".join(["\\left" + left_bracket, empty_tex_array, "\\right."])
+ tex_right = "".join(["\\left.", empty_tex_array, "\\right" + right_bracket])
+ l_bracket = MathTex(tex_left, **bracket_config)
+ r_bracket = MathTex(tex_right, **bracket_config)
+ bracket_pair = VGroup(l_bracket, r_bracket)
+ if stretch_brackets:
+ bracket_pair.stretch_to_fit_height(self.height + 2 * bracket_v_buff)
+ l_bracket.next_to(self, LEFT, bracket_h_buff)
+ r_bracket.next_to(self, RIGHT, bracket_h_buff)
+ self.brackets = bracket_pair
+ self.add(l_bracket, r_bracket)
+ self.center()
+ if add_background_rectangles_to_entries:
+ for mob in self.elements:
+ mob.add_background_rectangle()
+ if include_background_rectangle:
+ self.add_background_rectangle()
+
+ def get_entries(self) -> VGroup:
+ """The matrix's entries, row by row.
+
+ Returns:
+ The group of the entries; `get_entries()[1]` is the second entry of the
+ first row.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MatrixGetEntriesExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.Matrix([[2, 3], [1, 5]]).scale(1.5)
+ entries = matrix.get_entries()
+ self.add(matrix)
+ self.play(entries[0].animate.set_color(m.YELLOW))
+ self.play(m.Swap(entries[1], entries[2]))
+ ```
+ """
+ return self.elements
+
+ def get_brackets(self) -> VGroup:
+ r"""The matrix's brackets, the left one first.
+
+ Returns:
+ The group of the two brackets.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MatrixGetBracketsExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.Matrix([[r"\pi", 3], [1, 5]]).scale(1.5)
+ left, right = matrix.get_brackets()
+ self.add(matrix)
+ self.play(
+ left.animate.set_color(m.BLUE), right.animate.set_color(m.GREEN)
+ )
+ ```
+ """
+ return self.brackets
+
+
+class DecimalMatrix(Matrix):
+ r"""A matrix of decimal numbers: each entry written as a
+ [DecimalNumber][manimgx.DecimalNumber], with one decimal place unless configured.
+
+ It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are numbers, and its
+ `element_to_mobject_config` gives the numbers'
+ [keywords][manimgx.mobjects.numbers.DecimalNumberOptions], in place of
+ `{"num_decimal_places": 1}`.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class DecimalMatrixExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.DecimalMatrix(
+ [[3.456, 2.122], [33.2244, 12]],
+ h_buff=2,
+ element_to_mobject_config={"num_decimal_places": 2},
+ left_bracket=r"\{",
+ right_bracket=r"\}",
+ )
+ self.add(matrix.scale(1.5))
+ ```
+ """
+
+ entry = DecimalNumber
+ entry_config: ClassVar[Mapping[str, object]] = {"num_decimal_places": 1}
+
+
+class IntegerMatrix(Matrix):
+ """A matrix of integers: each entry written as an [Integer][manimgx.Integer], its
+ number rounded to a whole number.
+
+ It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are numbers, and its
+ `element_to_mobject_config` gives the numbers'
+ [keywords][manimgx.mobjects.numbers.DecimalNumberOptions].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class IntegerMatrixExample(m.Scene):
+ def construct(self) -> None:
+ matrix = m.IntegerMatrix(
+ [[3.7, 2], [42.2, 12]], left_bracket="(", right_bracket=")"
+ )
+ self.add(matrix.scale(1.5))
+ ```
+ """
+
+ entry = Integer
+
+
+class MobjectMatrix(Matrix):
+ r"""A matrix of mobjects: each entry a mobject, placed as it is.
+
+ It takes a [Matrix][manimgx.Matrix]'s arguments; its entries are mobjects, used
+ themselves (not copied).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectMatrixExample(m.Scene):
+ def construct(self) -> None:
+ circle = m.Circle(radius=0.3, color=m.BLUE)
+ triangle = m.Triangle(radius=0.35, color=m.GREEN)
+ matrix = m.MobjectMatrix(
+ [[circle, m.Square(0.6)], [triangle, m.Star(outer_radius=0.35)]],
+ left_bracket=r"\langle",
+ right_bracket=r"\rangle",
+ )
+ self.add(matrix.scale(1.5))
+ ```
+ """
+
+ entry = staticmethod(_same)
+
+
+class Table(_Grid, VGroup):
+ """A table: entries in rows and columns, with lines between them, and labels for
+ the rows and the columns if given; white unless styled.
+
+ Each entry is made into a mobject by `element_to_mobject` — by default a
+ [Paragraph][manimgx.Paragraph] of its text — and the cells are laid out in a grid,
+ each entry centered in its cell (see
+ [arrange_in_grid][manimgx.Mobject.arrange_in_grid]); the table is centered on the
+ scene's origin. Row labels make a first column, column labels a first row, and
+ `top_left_entry` fills the corner between them. The lines run through the middle of
+ the gaps between rows and between columns, and half a gap beyond the entries. Its
+ rows and columns can be reached as groups, `get_rows()` and `get_columns()`, and
+ colored, `set_row_colors(...)` and `set_column_colors(...)`, labels included.
+
+ A cell is addressed by its position, `(row, column)`, counted from 1 at the top
+ left, labels included: in a table with row and column labels, (1, 1) is the corner
+ and the first entry is at (2, 2).
+
+ Grid, line and background options are consumed during construction; cells, labels,
+ line groups and gaps hold the table's state.
+
+ Args:
+ table: The entries, row by row, every row as long: strings, for the default
+ [Paragraph][manimgx.Paragraph]; numbers or mobjects, as another
+ `element_to_mobject` takes them.
+ row_labels: A label for each row, left of it; None for none.
+ col_labels: A label for each column, above it; None for none.
+ top_left_entry: A mobject for the corner above the row labels and left of the
+ column labels, when there are both; None to leave it empty.
+ v_buff: The gap between rows, in scene units.
+ h_buff: The gap between columns, in scene units.
+ include_outer_lines: Whether lines frame the table.
+ include_inner_lines: Whether lines separate its rows and its columns.
+ add_background_rectangles_to_entries: Whether each entry, labels included,
+ gets a background rectangle (see
+ [add_background_to_entries][manimgx.Table.add_background_to_entries]).
+ entries_background_color: The color of the entries' background rectangles.
+ include_background_rectangle: Whether the table gets a background rectangle
+ (see [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
+ background_rectangle_color: The color of the table's background rectangle.
+ element_to_mobject: The function that makes each entry's mobject, called with
+ the entry and the keywords of `element_to_mobject_config`: a class, as
+ [MathTex][manimgx.MathTex], or any function; None for the class's own
+ (Paragraph, for a Table).
+ element_to_mobject_config: Keywords for `element_to_mobject`; None for the
+ class's own (none, for a Table).
+ arrange_in_grid_config: [Grid keywords][manimgx.mobject.GridArrangement]
+ for laying out the cells, over the table's own rows, columns and gaps:
+ `cell_alignment`, `col_alignments`, …; None for none.
+ line_config: [Line keywords][manimgx.mobjects.shapes.LineOptions] for the
+ lines: their `color`, `stroke_width`, …; None for none.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style] of the table itself: as it
+ has no points, they do not restyle its entries or its lines.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["1", "2", "3"], ["2", "4", "6"], ["3", "6", "9"]],
+ row_labels=[m.Text("1"), m.Text("2"), m.Text("3")],
+ col_labels=[m.Text("1"), m.Text("2"), m.Text("3")],
+ top_left_entry=m.Text("×"),
+ include_outer_lines=True,
+ line_config={"color": m.BLUE},
+ )
+ self.add(table)
+ ```
+ """
+
+ entry = Paragraph
+
+ def __init__(
+ self,
+ table: Iterable[Iterable[float | str | Mobject]],
+ row_labels: Iterable[Mobject] | None = None,
+ col_labels: Iterable[Mobject] | None = None,
+ top_left_entry: Mobject | None = None,
+ v_buff: float = 0.8,
+ h_buff: float = 1.3,
+ include_outer_lines: bool = False,
+ include_inner_lines: bool = True,
+ add_background_rectangles_to_entries: bool = False,
+ entries_background_color: ParsableManimColor = BLACK,
+ include_background_rectangle: bool = False,
+ background_rectangle_color: ParsableManimColor = BLACK,
+ element_to_mobject: ElementFactory | None = None,
+ element_to_mobject_config: Mapping[str, object] | None = None,
+ arrange_in_grid_config: GridArrangement | None = None,
+ line_config: LineOptions | None = None,
+ **kwargs: Unpack[Style],
+ ):
+ if line_config is None:
+ line_config = {}
+ if arrange_in_grid_config is None:
+ arrange_in_grid_config = {}
+ table_data = [list(row) for row in table]
+ row_label_data = list(row_labels) if row_labels is not None else []
+ col_label_data = list(col_labels) if col_labels is not None else []
+ self.row_labels = row_label_data or None
+ """The row labels, top to bottom; None if there are none."""
+ self.col_labels = col_label_data or None
+ """The column labels, left to right; None if there are none."""
+ self.top_left_entry = top_left_entry
+ """The mobject in the corner between the labels; None if there is none."""
+ self.row_dim = len(table_data)
+ """How many rows of entries the table has, labels not counted."""
+ self.col_dim = len(table_data[0])
+ """How many columns of entries the table has, labels not counted."""
+ self.v_buff = v_buff
+ """The gap between rows, in scene units, as the table was made: scaling the
+ table leaves it as it is."""
+ self.h_buff = h_buff
+ """The gap between columns, in scene units, as the table was made: scaling the
+ table leaves it as it is."""
+ entries_background_color = ManimColor(entries_background_color)
+ background_rectangle_color = ManimColor(background_rectangle_color)
+ if any(len(row) != len(table_data[0]) for row in table_data):
+ raise ValueError("Not all rows in table have the same length.")
+ super().__init__(**kwargs)
+ cells = self._make_cells(
+ table_data, element_to_mobject, element_to_mobject_config
+ )
+ self.elements_without_labels = VGroup(*it.chain(*cells))
+ """The entries but the labels, row by row."""
+ if self.row_labels is not None:
+ for k in range(len(self.row_labels)):
+ cells[k] = [self.row_labels[k]] + cells[k]
+ if self.col_labels is not None:
+ if self.row_labels is not None:
+ if self.top_left_entry is not None:
+ col_labels = [self.top_left_entry] + self.col_labels
+ cells.insert(0, col_labels)
+ else:
+ dummy_mobject = VMobject()
+ col_labels = [dummy_mobject] + self.col_labels
+ cells.insert(0, col_labels)
+ else:
+ cells.insert(0, self.col_labels)
+ self.cells = cells
+ self.elements = VGroup(*it.chain(*self.cells))
+ """Every entry of the table, labels included, row by row: a group, added to the
+ table."""
+ layout = GridArrangement(
+ rows=len(self.cells), cols=len(self.cells[0]), buff=(h_buff, v_buff)
+ )
+ self.elements.arrange_in_grid(**(layout | arrange_in_grid_config))
+ if len(self.elements[0].get_all_points()) == 0:
+ self.elements.remove(self.elements[0])
+ self.add(self.elements)
+ self.center()
+ for axis in (0, 1):
+ divisions = self.get_rows() if axis == 0 else self.get_columns()
+ along, across = (RIGHT, UP) if axis == 0 else (DOWN, LEFT)
+ near = [float(part.get_corner(across) @ across) for part in divisions]
+ far = [float(part.get_corner(-across) @ across) for part in divisions]
+ gap = (self.v_buff, self.h_buff)[axis] / 2
+ pad = (self.h_buff, self.v_buff)[axis] / 2
+ start = float(self.elements.get_corner(-along) @ along) - pad
+ end = float(self.elements.get_corner(along) @ along) + pad
+ anchors: list[tuple[float, bool]] = []
+ if include_outer_lines:
+ anchors.extend(((near[0] + gap, False), (far[-1] - gap, False)))
+ if include_inner_lines:
+ anchors.extend(
+ (b + 0.5 * (a - b), axis == 1) for a, b in zip(far[:-1], near[1:])
+ )
+ lines = VGroup()
+ parts: list[Line] = []
+ for anchor, reverse in anchors:
+ offset = anchor * across
+ ends = (start * along + offset, end * along + offset)
+ parts.append(Line(*(ends[::-1] if reverse else ends), **line_config))
+ lines.add(*parts)
+ self.add(*lines)
+ if axis == 0:
+ self.horizontal_lines = lines
+ else:
+ self.vertical_lines = lines
+ if add_background_rectangles_to_entries:
+ self.add_background_to_entries(color=entries_background_color)
+ if include_background_rectangle:
+ self.add_background_rectangle(color=background_rectangle_color)
+
+ def get_horizontal_lines(self) -> VGroup:
+ """The table's horizontal lines: the outer ones first, top then bottom, if it
+ has them, then those between its rows, from the top down.
+
+ Returns:
+ The group of the lines.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetHorizontalLinesExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ include_outer_lines=True,
+ )
+ self.add(table)
+ self.play(table.get_horizontal_lines().animate.set_color(m.RED))
+ ```
+ """
+ return self.horizontal_lines
+
+ def get_vertical_lines(self) -> VGroup:
+ """The table's vertical lines: the outer ones first, left then right, if it has
+ them, then those between its columns, from left to right.
+
+ Returns:
+ The group of the lines.
+ """
+ return self.vertical_lines
+
+ def get_entries(self, pos: Sequence[int] | None = None) -> Mobject:
+ """The table's entries, labels included, or the one at a position.
+
+ Args:
+ pos: The position, `(row, column)`, counted from 1 at the top left, labels
+ included; None for every entry.
+
+ Returns:
+ The entry; or every entry, row by row, in a group.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetEntriesExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ self.add(table)
+ self.play(table.get_entries((2, 3)).animate.set_color(m.YELLOW))
+ self.play(m.Rotate(table.get_entries((3, 2)), m.PI))
+ ```
+ """
+ if pos is not None:
+ if (
+ self.row_labels is not None
+ and self.col_labels is not None
+ and (self.top_left_entry is None)
+ ):
+ index = len(self.cells[0]) * (pos[0] - 1) + pos[1] - 2
+ return self.elements[index]
+ else:
+ index = len(self.cells[0]) * (pos[0] - 1) + pos[1] - 1
+ return self.elements[index]
+ else:
+ return self.elements
+
+ def get_entries_without_labels(self, pos: Sequence[int] | None = None) -> Mobject:
+ """The table's entries but its labels, or the one at a position among them.
+
+ Args:
+ pos: The position, `(row, column)`, counted from 1 at the top left entry
+ that is not a label; None for every such entry.
+
+ Returns:
+ The entry; or every entry but the labels, row by row, in a group.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetEntriesWithoutLabelsExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ entries = table.get_entries_without_labels()
+ colors = [m.BLUE, m.GREEN, m.YELLOW, m.RED]
+ for entry, color in zip(entries, colors):
+ entry.set_color(color)
+ self.add(table)
+ ```
+ """
+ if pos is not None:
+ index = self.col_dim * (pos[0] - 1) + pos[1] - 1
+ return self.elements_without_labels[index]
+ else:
+ return self.elements_without_labels
+
+ def get_row_labels(self) -> VGroup:
+ """The table's row labels, from the top down.
+
+ Returns:
+ A new group of the labels; empty if there are none.
+ """
+ if self.row_labels is not None:
+ return VGroup(*self.row_labels)
+ return VGroup()
+
+ def get_col_labels(self) -> VGroup:
+ """The table's column labels, from left to right.
+
+ Returns:
+ A new group of the labels; empty if there are none.
+ """
+ if self.col_labels is not None:
+ return VGroup(*self.col_labels)
+ return VGroup()
+
+ def get_labels(self) -> VGroup:
+ """The table's labels: its top left entry, if it has one, then its column
+ labels, then its row labels.
+
+ Returns:
+ A new group of the labels; empty if there are none.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetLabelsExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ self.add(table)
+ self.play(table.get_labels().animate.set_color(m.YELLOW))
+ ```
+ """
+ label_group = VGroup()
+ if self.top_left_entry is not None:
+ label_group.add(self.top_left_entry)
+ for label in (self.col_labels, self.row_labels):
+ if label is not None:
+ label_group.add(*label)
+ return label_group
+
+ def add_background_to_entries(self, color: ParsableManimColor = BLACK) -> Self:
+ """Put a background rectangle behind each entry, labels included (see
+ [add_background_rectangle][manimgx.Mobject.add_background_rectangle]).
+
+ The rectangles are the entries' `background_rectangle`s:
+ [create][manimgx.Table.create] fades in those of the entries but the labels.
+
+ Args:
+ color: The rectangles' color.
+ """
+ for mob in self.get_entries():
+ mob.add_background_rectangle(color=ManimColor(color))
+ return self
+
+ def get_cell(self, pos: Sequence[int] = (1, 1), **kwargs: Unpack[Style]) -> Polygon:
+ """Make the rectangle of a cell: its row's height and its column's width,
+ reaching half a gap beyond them on every side, so that it meets the lines;
+ blue unless styled.
+
+ The gaps are `v_buff` and `h_buff`, as the table was made: on a table scaled
+ since, the rectangle reaches as far beyond the entries as before.
+
+ Args:
+ pos: The cell's position, `(row, column)`, counted from 1 at the top left,
+ labels included.
+ **kwargs: [Style keywords][manimgx.drawing.paint.Style].
+
+ Returns:
+ A new [Polygon][manimgx.Polygon], not added to the table.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableGetCellExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ self.add(table)
+ self.play(m.Create(table.get_cell((2, 2), color=m.RED)))
+ ```
+ """
+ row = list(self.cells[pos[0] - 1])
+ col = [row[pos[1] - 1] for row in self.cells]
+ box = _family_box(_family(col))
+ left = (np.float64(0) if box is None else box[0, 0]) - self.h_buff / 2
+ box = _family_box(_family(col))
+ right = (np.float64(0) if box is None else box[1, 0]) + self.h_buff / 2
+ box = _family_box(_family(row))
+ bottom = (np.float64(0) if box is None else box[0, 1]) - self.v_buff / 2
+ box = _family_box(_family(row))
+ top = (np.float64(0) if box is None else box[1, 1]) + self.v_buff / 2
+ return Polygon(
+ [left, top, 0],
+ [right, top, 0],
+ [right, bottom, 0],
+ [left, bottom, 0],
+ **kwargs,
+ )
+
+ def get_highlighted_cell(
+ self,
+ pos: Sequence[int] = (1, 1),
+ **kwargs: Unpack[FrameOptions],
+ ) -> BackgroundRectangle:
+ """Make a highlight for a cell: a
+ [BackgroundRectangle][manimgx.BackgroundRectangle] over the
+ [cell's rectangle][manimgx.Table.get_cell], bright yellow (`PURE_YELLOW`) unless
+ given a color.
+
+ It is not added to the table: put it behind the entries, as
+ [add_highlighted_cell][manimgx.Table.add_highlighted_cell] does.
+
+ Args:
+ pos: The cell's position, `(row, column)`, counted from 1 at the top left,
+ labels included.
+ **kwargs: [Frame keywords][manimgx.mobjects.annotations.FrameOptions]:
+ its `color`, `buff`, `fill_opacity`, ….
+
+ Returns:
+ A new background rectangle.
+ """
+ if kwargs.get("color") is None: # not given, None too
+ kwargs["color"] = PURE_YELLOW
+ bg_cell = BackgroundRectangle(self.get_cell(pos), **kwargs)
+ return bg_cell
+
+ def add_highlighted_cell(
+ self,
+ pos: Sequence[int] = (1, 1),
+ **kwargs: Unpack[FrameOptions],
+ ) -> Self:
+ """Highlight a cell: put a [highlight][manimgx.Table.get_highlighted_cell]
+ behind everything in the table.
+
+ The highlight is the `background_rectangle` of the entry at `pos`:
+ [create][manimgx.Table.create] fades it in, unless the entry is a label.
+
+ Args:
+ pos: The cell's position, `(row, column)`, counted from 1 at the top left,
+ labels included.
+ **kwargs: [Frame keywords][manimgx.mobjects.annotations.FrameOptions]:
+ its `color`, `buff`, `fill_opacity`, ….
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableAddHighlightedCellExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ )
+ table.add_highlighted_cell((2, 2), color=m.GREEN)
+ self.add(table)
+ ```
+ """
+ bg_cell = self.get_highlighted_cell(pos, **kwargs)
+ self.add_to_back(bg_cell)
+ entry = self.get_entries(pos)
+ entry.background_rectangle = bg_cell
+ return self
+
+ def create(
+ self,
+ line_animation: Callable[..., Animation] = Create,
+ label_animation: Callable[..., Animation] = Write,
+ element_animation: Callable[..., Animation] = Create,
+ entry_animation: Callable[..., Animation] = FadeIn,
+ **kwargs: Unpack[AnimationOptions],
+ ) -> AnimationGroup:
+ """Make an animation that builds the table: its lines, then its entries, then
+ its labels, then each entry's background rectangle, one after another.
+
+ Each part is its own animation, made with the options given; the parts follow
+ one another by `lag_ratio`, 1 unless given. The entries but the labels are
+ moved to a z-index of 2, over backgrounds and highlights.
+
+ Args:
+ line_animation: The animation that draws the lines.
+ label_animation: The animation that draws the labels.
+ element_animation: The animation that draws the entries but the labels.
+ entry_animation: The animation that brings in each entry's background
+ rectangle (the highlights of
+ [add_highlighted_cell][manimgx.Table.add_highlighted_cell]).
+ **kwargs: [Animation options][manimgx.animation.timeline.AnimationOptions]
+ for each part (`run_time` is each part's), and `lag_ratio` for the
+ whole: 1 plays the parts one after another, 0 all at once.
+
+ Returns:
+ A new animation group.
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class TableCreateExample(m.Scene):
+ def construct(self) -> None:
+ table = m.Table(
+ [["First", "Second"], ["Third", "Fourth"]],
+ row_labels=[m.Text("R1"), m.Text("R2")],
+ col_labels=[m.Text("C1"), m.Text("C2")],
+ include_outer_lines=True,
+ )
+ table.add_highlighted_cell((2, 2), color=m.GREEN)
+ self.play(table.create())
+ ```
+ """
+ # the parts: lines, entries, labels (if any), then the entries' backgrounds;
+ # the other options go to each part
+ lag_ratio = kwargs.pop("lag_ratio", 1)
+ animations: list[Animation] = [
+ line_animation(
+ VGroup(self.vertical_lines, self.horizontal_lines), **kwargs
+ ),
+ element_animation(self.elements_without_labels.set_z_index(2), **kwargs),
+ ]
+ if self.get_labels():
+ animations += [label_animation(self.get_labels(), **kwargs)]
+ if self.get_entries():
+ for entry in self.elements_without_labels:
+ if entry.background_rectangle is not None:
+ animations.append(
+ entry_animation(entry.background_rectangle, **kwargs)
+ )
+ return AnimationGroup(*animations, lag_ratio=lag_ratio)
+
+
+class MathTable(Table):
+ """A table of math: each entry typeset as math, with [MathTex][manimgx.MathTex].
+
+ It takes a [Table][manimgx.Table]'s arguments; its entries are strings of math, or
+ numbers, and its `element_to_mobject_config` gives their
+ [math keywords][manimgx.mobjects.text.MathTexOptions].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MathTableExample(m.Scene):
+ def construct(self) -> None:
+ table = m.MathTable(
+ [["+", 0, 5, 10], [0, 0, 5, 10], [2, 2, 7, 12], [4, 4, 9, 14]],
+ include_outer_lines=True,
+ )
+ self.add(table)
+ ```
+ """
+
+ entry = MathTex
+
+
+class MobjectTable(Table):
+ """A table of mobjects: each entry a mobject, placed as it is.
+
+ It takes a [Table][manimgx.Table]'s arguments; its entries are mobjects, used
+ themselves (not copied).
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class MobjectTableExample(m.Scene):
+ def construct(self) -> None:
+ def o() -> m.Circle:
+ return m.Circle(radius=0.45, color=m.RED)
+
+ def x() -> m.VGroup:
+ cross = m.VGroup(m.Line(m.UL, m.DR), m.Line(m.UR, m.DL))
+ return cross.scale(0.45).set_color(m.BLUE)
+
+ table = m.MobjectTable(
+ [[o(), x(), o()], [x(), o(), o()], [o(), x(), x()]]
+ )
+ self.add(table)
+ ```
+ """
+
+ entry = staticmethod(_same)
+
+
+class IntegerTable(Table):
+ r"""A table of integers: each entry written as an [Integer][manimgx.Integer], its
+ number rounded to a whole number.
+
+ It takes a [Table][manimgx.Table]'s arguments; its entries are numbers, and its
+ `element_to_mobject_config` gives their
+ [number keywords][manimgx.mobjects.numbers.DecimalNumberOptions].
+
+ Examples:
+ ```python
+ import manimgx as m
+
+
+ class IntegerTableExample(m.Scene):
+ def construct(self) -> None:
+ table = m.IntegerTable(
+ [[0, 30, 45, 60, 90], [90, 60, 45, 30, 0]],
+ row_labels=[m.MathTex(r"\alpha"), m.MathTex(r"90^\circ - \alpha")],
+ h_buff=1,
+ element_to_mobject_config={"unit": r"^\circ"},
+ )
+ self.add(table)
+ ```
+ """
+
+ entry = Integer
+
+
+class DecimalTable(Table):
+ """A table of decimal numbers: each entry written as a
+ [DecimalNumber][manimgx.DecimalNumber], with one decimal place unless configured.
+
+ It takes a [Table][manimgx.Table]'s arguments; its entries are numbers, and its
+ `element_to_mobject_config` gives their
+ [number keywords][manimgx.mobjects.numbers.DecimalNumberOptions], in place of
+ `{"num_decimal_places": 1}`.
+
+ Examples:
+ ```python
+ import numpy as np
+
+ import manimgx as m
+
+
+ class DecimalTableExample(m.Scene):
+ def construct(self) -> None:
+ xs = [-2, -1, 0, 1, 2]
+ table = m.DecimalTable(
+ [xs, np.exp(xs)],
+ row_labels=[m.MathTex("x"), m.MathTex("e^x")],
+ h_buff=1,
+ element_to_mobject_config={"num_decimal_places": 2},
+ )
+ self.add(table)
+ ```
+ """
+
+ entry = DecimalNumber
+ entry_config: ClassVar[Mapping[str, object]] = {"num_decimal_places": 1}
diff --git a/src/manimgx/mobjects/shapes.py b/src/manimgx/mobjects/shapes.py
index e257dfbf..3656ad71 100644
--- a/src/manimgx/mobjects/shapes.py
+++ b/src/manimgx/mobjects/shapes.py
@@ -13,6 +13,7 @@ from collections.abc import Iterator, Sequence
from functools import reduce
from math import ceil
from typing import TYPE_CHECKING, ClassVar, Literal, Self, Unpack, cast
+from warnings import deprecated
import numpy as np
@@ -248,9 +249,7 @@ class TipableVMobject(VMobject):
tip_length: The length of the tips [add_tip][manimgx.TipableVMobject.add_tip]
makes, in scene units (default 0.35).
normal_vector: The normal of the plane the path lies in. Accepted for Manim
- compatibility; ignored and not retained as an instance attribute. An
- [Arrow.reset_normal_vector][manimgx.Arrow.reset_normal_vector] call can
- explicitly record its tip's current normal.
+ compatibility; ignored.
tip_style: Style keywords for the tips the path makes; a tip's `fill_color` and
`stroke_color` are the path's color unless given here.
"""
@@ -296,7 +295,7 @@ class TipableVMobject(VMobject):
subclass; None for
[ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
tip_length: The length of the tip to make, in scene units; None for the
- path's [default][manimgx.TipableVMobject.get_default_tip_length].
+ path's `tip_length`.
tip_width: The width of the tip to make, if it is the default filled
triangle, in scene units; None for the default length. Other shapes take
no width: they are made at `tip_length` alone.
@@ -327,6 +326,7 @@ class TipableVMobject(VMobject):
self.add(tip)
return self
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def create_tip(
self,
tip_shape: type[ArrowTip] | None = None,
@@ -353,6 +353,7 @@ class TipableVMobject(VMobject):
self.position_tip(tip, at_start)
return tip
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def get_unpositioned_tip(
self,
tip_shape: type[ArrowTip] | None = None,
@@ -397,6 +398,7 @@ class TipableVMobject(VMobject):
unit = ArrowTriangleFilledTip(length=1.0, width=width / length, **style)
return unit.scale(length)
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def position_tip(self, tip: ArrowTip, at_start: bool = False) -> ArrowTip:
"""Turn and move a tip onto the path's end, or its start: pointing along the
path there, its point on the end.
@@ -429,6 +431,7 @@ class TipableVMobject(VMobject):
tip._rotate_direction_state(turn)
return tip
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def reset_endpoints_based_on_tip(self, tip: ArrowTip, at_start: bool) -> Self:
"""Fit the path to stop at a tip's base: scale and turn it about its other end,
which stays.
@@ -455,6 +458,7 @@ class TipableVMobject(VMobject):
self._rotate_direction_state(turn)
return self
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def assign_tip_attr(self, tip: ArrowTip, at_start: bool) -> Self:
"""Name a tip as the path's [tip][manimgx.TipableVMobject.tip], or its
[start_tip][manimgx.TipableVMobject.start_tip]; the tip is not added.
@@ -536,6 +540,7 @@ class TipableVMobject(VMobject):
raise Exception("tip not found")
return tips[0]
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def get_default_tip_length(self) -> float:
"""The length of the tips the path makes unless given one: its `tip_length`.
@@ -544,6 +549,7 @@ class TipableVMobject(VMobject):
"""
return self.tip_length
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def get_first_handle(self) -> Point3D:
"""The path's first handle: the control point after its first point, toward
which it leaves its start.
@@ -566,6 +572,7 @@ class TipableVMobject(VMobject):
return point
return curve[1]
+ @deprecated("Manim CE's machinery: add_tip calls it", category=None)
def get_last_handle(self) -> Point3D:
"""The path's last handle: the control point before its last point, from which
it comes into its end.
@@ -822,7 +829,7 @@ class CurvedArrow(ArcBetweenPoints):
tip_shape: The class of its tip; None for
[ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
**kwargs:
- [ArcBetweenPoints keywords][manimgx.mobjects.shapes.ArcBetweenOptions]:
+ [ArcBetweenPoints keywords][manimgx.ArcBetweenPoints]:
its angle (a quarter turn unless given) or its radius, style and tips.
Examples:
@@ -870,7 +877,7 @@ class CurvedDoubleArrow(CurvedArrow):
tip_shape_end: The class of the tip at its end; None for
[ArrowTriangleFilledTip][manimgx.ArrowTriangleFilledTip].
**kwargs:
- [ArcBetweenPoints keywords][manimgx.mobjects.shapes.ArcBetweenOptions]:
+ [ArcBetweenPoints keywords][manimgx.ArcBetweenPoints]:
its angle (a quarter turn unless given) or its radius, style and tips.
Examples:
@@ -1351,7 +1358,7 @@ class ArcPolygon(VMobject):
radius: The radius of every arc, in scene units, in place of `angle`, unless
`arc_config` is given; None (or 0) to use `angle`.
arc_config: The arcs' [ArcBetweenPoints
- keywords][manimgx.mobjects.shapes.ArcBetweenOptions], in place of
+ keywords][manimgx.ArcBetweenPoints], in place of
`angle` and `radius`: one set for every arc, or a list of one per side, the
first vertex's side first.
@@ -1471,9 +1478,8 @@ class Polygram(VMobject):
fill counts how many times its paths wind around each point: a group inside another
that runs the other way around is a hole.
- Vertices are copied before the corner hook runs. `add_points_as_corners` receives
- one owned array per group, including the closing vertex; edits to the input vertices
- do not change the finished shape.
+ The vertices are taken as they are given: changing their arrays afterwards changes
+ no shape.
Args:
*vertex_groups: The groups of vertices, each in order around its path.
@@ -2689,6 +2695,7 @@ class Line(TipableVMobject):
)
return self
+ @deprecated("use put_start_and_end_on", category=None)
def set_points_by_ends(
self,
start: Point3DLike | Mobject,
@@ -3078,8 +3085,9 @@ class DashedLine(Line):
The dashes are the line's stroke drawn in pieces: a whole number of them, at least
two, spread evenly from end to end, each about `dash_length` long, each ended as
the line's `cap_style` says. It stays one path, placed, bent and tipped as a
- [Line][manimgx.Line] is: its start, end and handles are the line's. Its dashes are
- counted when it is made, and scale with it.
+ [Line][manimgx.Line] is, and starts and ends where the line does; its handles are
+ its dashes', the first dash's and the last's. Its dashes are counted when it is
+ made, and scale with it.
Args:
start: Where the line starts: a point, or a mobject (see [Line][manimgx.Line]).
@@ -3133,6 +3141,41 @@ class DashedLine(Line):
2, int(np.ceil(self.get_length() / self.dash_length * self.dashed_ratio))
)
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
+ def get_first_handle(self) -> Point3D:
+ """The line's first handle: its first dash's, the control point after the
+ line's start toward which that dash leaves it (a third of the way into the
+ dash, on a straight line).
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ start, handle = self.points[:2]
+ return start + self._dash_cut() * (handle - start)
+
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
+ def get_last_handle(self) -> Point3D:
+ """The line's last handle: its last dash's, the control point before the
+ line's end from which that dash comes into it (a third of the way back into
+ the dash, on a straight line).
+
+ Returns:
+ The point, in scene coordinates.
+ """
+ handle, end = self.points[-2:]
+ return end + self._dash_cut() * (handle - end)
+
+ def _dash_cut(self) -> float:
+ """How far into the curve at each end of the line the dash there reaches, in
+ that curve's parameter from the end: the dash is the curve cut there, which
+ keeps the end and brings its handle in by as much (de Casteljau). The first
+ dash starts the line and the last ends it, each period × duty of its parameter;
+ drawn solid, the line is one piece, each end curve whole."""
+ if self.paint.dash is None:
+ return 1.0
+ period, duty, _ = self.paint.dash
+ return min(1.0, period * duty * self.get_num_curves())
+
class TangentLine(Line):
"""A line tangent to a path at a point along it, `length` long and centered on the
@@ -3346,6 +3389,7 @@ class Arrow(Line):
self.submobjects.sort(key=lambda m: place.get(id(m), len(order)))
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_normal_vector(self) -> Vector3D:
"""The normal of the plane the arrow's tip lies in, from its first three
anchors.
@@ -3356,6 +3400,7 @@ class Arrow(Line):
p0, p1, p2 = self.tip.get_start_anchors()[:3]
return normalize(np.cross(p2 - p1, p1 - p0))
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def reset_normal_vector(self) -> Self:
"""Set the arrow's `normal_vector` to its
[tip's normal][manimgx.Arrow.get_normal_vector].
@@ -3365,6 +3410,7 @@ class Arrow(Line):
self.normal_vector = self.get_normal_vector()
return self
+ @deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def get_default_tip_length(self) -> float:
"""The length of the tips the arrow makes unless given one: its `tip_length`,
or `max_tip_length_to_length_ratio` times its length if that is shorter.
@@ -3824,6 +3870,7 @@ class RightAngle(Angle):
super().__init__(line1, line2, radius=length, elbow=True, **kwargs)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def adjacent_n_tuples[T](objects: Sequence[T], n: int) -> Iterator[tuple[T, ...]]:
"""Each run of `n` items in a row, wrapping around at the end: for `[a, b, c]` and
2, `(a, b)`, `(b, c)` and `(c, a)`.
@@ -3838,6 +3885,7 @@ def adjacent_n_tuples[T](objects: Sequence[T], n: int) -> Iterator[tuple[T, ...]
return zip(*(list(objects[k:]) + list(objects[:k]) for k in range(n)), strict=True)
+@deprecated("Manim CE's machinery: manimgx calls it itself", category=None)
def adjacent_pairs[T](objects: Sequence[T]) -> Iterator[tuple[T, ...]]:
"""Each item with the next, wrapping around at the end (see
[adjacent_n_tuples][manimgx.adjacent_n_tuples]).
diff --git a/src/manimgx/mobjects/svg.py b/src/manimgx/mobjects/svg.py
index 6803c0ad..8d1df343 100644
--- a/src/manimgx/mobjects/svg.py
+++ b/src/manimgx/mobjects/svg.py
@@ -14,6 +14,7 @@ import os
from collections.abc import Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Self, Unpack
+from warnings import deprecated
from xml.etree import ElementTree as ET
import numpy as np
@@ -45,8 +46,7 @@ def _point(point: se.Point | None) -> np.ndarray:
class PathOptions(Style, total=False):
"""How an SVG path becomes curves: an [SVGMobject][manimgx.SVGMobject]'s
- `path_string_config`, the keywords of each
- [VMobjectFromSVGPath][manimgx.VMobjectFromSVGPath] it makes.
+ `path_string_config`, the keywords of each path it reads.
Beyond these, they take the [style keywords][manimgx.drawing.paint.Style].
"""
@@ -146,6 +146,7 @@ class SVGMobject(VMobject):
)
self.move_into_position()
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def init_svg_mobject(self, use_svg_cache: bool) -> Self:
"""Build the drawing, reusing parsed parts when caching is enabled."""
self.use_svg_cache = use_svg_cache
@@ -153,6 +154,7 @@ class SVGMobject(VMobject):
return self
@property
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def hash_seed(self) -> tuple[object, ...]:
"""The class and path settings that interpret the SVG content. Subclasses can
extend this tuple with other inputs their conversion uses."""
@@ -161,6 +163,7 @@ class SVGMobject(VMobject):
key_of(sorted(self.path_string_config.items())),
)
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def generate_mobject(self) -> Self:
"""Read the file and add its shapes as parts, flipped so that y points up (SVG's
points down). Existing geometry turns with the newly read shapes.
@@ -195,6 +198,7 @@ class SVGMobject(VMobject):
self.id_to_vgroup_dict = mobject_dict
return self
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def get_file_path(self) -> Path:
"""Find the SVG file; a mobject made without one raises ValueError.
@@ -205,6 +209,7 @@ class SVGMobject(VMobject):
raise ValueError("Must specify file for SVGMobject")
return self.file_name
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def modify_xml_tree(
self, element_tree: ET.ElementTree[ET.Element]
) -> ET.ElementTree[ET.Element]:
@@ -232,6 +237,7 @@ class SVGMobject(VMobject):
ET.SubElement(config_style, "g", root_style).extend(root)
return ET.ElementTree(new_root)
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def generate_config_style_dict(self) -> dict[str, str]:
"""The SVG attributes `svg_default` sets: `fill`, `fill-opacity`, `stroke`,
`stroke-opacity` and `stroke-width`.
@@ -254,6 +260,7 @@ class SVGMobject(VMobject):
result[svg_key] = str(value)
return result
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def get_mobjects_from(
self, svg: se.SVG
) -> tuple[list[VMobject], dict[str, VGroup]]:
@@ -307,6 +314,7 @@ class SVGMobject(VMobject):
logger.error(f"Exception occurred in 'get_mobjects_from'. Details: {e}")
return (result, vgroups)
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def get_mob_from_shape_element(self, shape: se.SVGElement) -> VMobject | None:
"""Make a part of a shape of the drawing, painted and transformed as the file
says.
@@ -349,6 +357,7 @@ class SVGMobject(VMobject):
return mob
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def handle_transform(mob: VMobject, matrix: se.Matrix) -> VMobject:
"""Apply an SVG transform to a part: its matrix, then its translation.
@@ -366,6 +375,7 @@ class SVGMobject(VMobject):
return mob
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def apply_style_to_mobject(mob: VMobject, shape: se.GraphicObject) -> VMobject:
"""Paint a part as the file paints its shape: its fill, its stroke, their
opacities and the stroke's width.
@@ -387,6 +397,7 @@ class SVGMobject(VMobject):
)
return mob
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def path_to_mobject(self, path: se.Path) -> VMobjectFromSVGPath:
"""Make a part of a path, with `path_string_config`.
@@ -399,6 +410,7 @@ class SVGMobject(VMobject):
return VMobjectFromSVGPath(path, **self.path_string_config)
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def line_to_mobject(line: se.SimpleLine) -> Line:
"""Make a part of a line.
@@ -412,6 +424,7 @@ class SVGMobject(VMobject):
return Line(start=np.array([x1, y1, 0.0]), end=np.array([x2, y2, 0.0]))
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def rect_to_mobject(rect: se.Rect) -> Rectangle:
"""Make a part of a rectangle, its corners rounded if the file rounds them.
@@ -437,6 +450,7 @@ class SVGMobject(VMobject):
return mob
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def ellipse_to_mobject(ellipse: se.Ellipse | se.Circle) -> Circle:
"""Make a part of a circle or an ellipse.
@@ -456,6 +470,7 @@ class SVGMobject(VMobject):
return mob
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def polygon_to_mobject(polygon: se.Polygon) -> Polygon:
"""Make a part of a polygon.
@@ -467,6 +482,7 @@ class SVGMobject(VMobject):
"""
return Polygon(*(np.array([x, y, 0.0]) for x, y in polygon))
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def polyline_to_mobject(self, polyline: se.Polyline) -> VMobject:
"""Make a part of a polyline: an open path through its points.
@@ -479,6 +495,7 @@ class SVGMobject(VMobject):
return VMobject().set_points_as_corners([[x, y, 0.0] for x, y in polyline])
@staticmethod
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def text_to_mobject(text: se.Text) -> VMobject | None:
"""Skip a text element: SVG text is not supported, and a warning is logged.
@@ -491,6 +508,7 @@ class SVGMobject(VMobject):
logger.warning(f"Unsupported element type: {type(text)}")
return None
+ @deprecated("Manim CE's machinery: the constructor calls it", category=None)
def move_into_position(self) -> Self:
"""Center the drawing and scale it to `height` and `width`, as the constructor
was asked to.
@@ -504,6 +522,7 @@ class SVGMobject(VMobject):
return self
+@deprecated("Manim CE's machinery for SVGMobject: use SVGMobject", category=None)
class VMobjectFromSVGPath(VMobject):
"""A path of an SVG drawing, as a mobject: its lines, quadratic and cubic curves,
and arcs (approximated by quadratic curves), all made cubic curves.
diff --git a/tests/unit/mobjects/test_graph.py b/tests/unit/mobjects/test_graph.py
new file mode 100644
index 00000000..0940e3b5
--- /dev/null
+++ b/tests/unit/mobjects/test_graph.py
@@ -0,0 +1,305 @@
+"""A graph is its vertices and edges, edited through its public methods, beside a model of them.
+
+- Its vertices and edges are those added and not removed, in the order added; a vertex
+ removed takes its edges with it, and a key removed and added again is a fresh vertex, made
+ with the graph's vertex keywords under the ones given, without the label it had.
+- Each method returns what it added or removed: a new vertex, an edge's new vertices then
+ the edge, a vertex's edges then the vertex.
+- Every edge joins its vertices once the graph's updater runs: center to center, or outline
+ to outline for a directed graph's, wherever the vertices were moved or laid out.
+- A layout by positions puts each vertex at its own; a layout function is handed a fresh
+ graph of the current vertices and edges, the scale, and the layout keywords (over the
+ partitions and root vertex given), and what it does to that graph stays there; a layout by
+ name lays the vertices out as a graph made afresh with that layout would.
+- A copy goes on apart: what is done to it leaves the graph it was copied from.
+"""
+
+import networkx as nx
+import numpy as np
+import pytest
+from hypothesis import settings
+from hypothesis import strategies as st
+from hypothesis.stateful import (
+ RuleBasedStateMachine,
+ initialize,
+ invariant,
+ precondition,
+ rule,
+)
+
+import manimgx as m
+from manimgx.mobjects.graph import GenericGraph
+
+KEYS = range(6)
+SPOTS = [
+ np.array([x, y, 0.0]) for x in (-3.0, -1.5, 0.0, 1.5, 3.0) for y in (-2.0, 0, 2)
+]
+TOKEN = object() # (a layout keyword handed on as it is)
+# what a layout function was handed: its scale, keywords, nodes and edges, and the graph's
+# and the nodes' attributes
+type Seen = tuple[
+ float,
+ dict[str, object],
+ list[int],
+ set[tuple[int, int]],
+ dict[str, object],
+ list[dict[str, object]],
+]
+
+
+class Graphs(RuleBasedStateMachine):
+ """A graph or a directed one, its vertices added, removed, moved and laid out, its edges
+ added and removed, and copied, beside a model of where each vertex is and its color."""
+
+ graph: m.Graph[int] | m.DiGraph[int]
+
+ @initialize(directed=st.booleans(), drawn=st.booleans())
+ def made(self, directed: bool, drawn: bool) -> None:
+ self.kind = m.DiGraph if directed else m.Graph
+ style = {"radius": 0.15, "color": m.BLUE}
+ if drawn: # (a vertex given as its mobject, named only by it and by an edge)
+ dot = m.Dot(radius=0.15, color=m.YELLOW)
+ self.graph = self.kind(
+ [0],
+ [(0, 1)],
+ vertex_mobjects={1: dot},
+ layout="circular",
+ vertex_config=style,
+ )
+ else:
+ self.graph = self.kind(
+ [0, 1], [(0, 1)], layout="circular", vertex_config=style
+ )
+ fresh = self.kind([0, 1], [(0, 1)], layout="circular")
+ self.where = {v: fresh[v].get_center() for v in (0, 1)}
+ self.colors = {0: m.BLUE, 1: m.YELLOW if drawn else m.BLUE}
+ self.edges: list[tuple[int, int]] = [(0, 1)]
+ self.gone: list[m.Mobject] = [] # removed: never in the family again
+ self.copied: list[
+ tuple[GenericGraph[int], list[np.ndarray], list[int], list[object]]
+ ] = []
+
+ def free(self) -> list[np.ndarray]:
+ return [
+ s
+ for s in SPOTS
+ if all(np.linalg.norm(s - p) > 0.5 for p in self.where.values())
+ ]
+
+ @precondition(lambda self: len(self.where) < len(KEYS))
+ @rule(data=st.data(), red=st.booleans(), labeled=st.booleans())
+ def add_vertex(self, data: st.DataObject, red: bool, labeled: bool) -> None:
+ v = data.draw(st.sampled_from([v for v in KEYS if v not in self.where]))
+ spot = data.draw(st.sampled_from(self.free()))
+ label = m.Square(0.1)
+ added = self.graph.add_vertices(
+ v,
+ positions={v: spot},
+ labels={v: label} if labeled else False,
+ vertex_config={"color": m.RED} if red else None,
+ )
+ assert added.submobjects == [self.graph[v]]
+ if labeled:
+ assert label in self.graph[v].get_family()
+ else: # (a fresh vertex: no label left from a vertex of that key before)
+ assert self.graph[v].submobjects == []
+ self.where[v] = spot
+ self.colors[v] = m.RED if red else m.BLUE
+
+ @precondition(lambda self: self.where)
+ @rule(data=st.data())
+ def add_a_present_vertex(self, data: st.DataObject) -> None:
+ v = data.draw(st.sampled_from(sorted(self.where)))
+ with pytest.raises(ValueError, match="already used"):
+ self.graph.add_vertices(v)
+
+ @rule(data=st.data(), green=st.booleans())
+ def add_edge(self, data: st.DataObject, green: bool) -> None:
+ pairs = [
+ (u, v) for u in KEYS for v in KEYS if u != v and (u, v) not in self.edges
+ ]
+ # (an edge's reverse, often: see remove_edge)
+ reverses = [e for e in pairs if e[::-1] in self.edges]
+ u, v = data.draw(
+ st.sampled_from(reverses) | st.sampled_from(pairs)
+ if reverses
+ else st.sampled_from(pairs)
+ )
+ new = [w for w in (u, v) if w not in self.where]
+ spots = dict(zip(new, data.draw(st.permutations(self.free())), strict=False))
+ added = self.graph.add_edges(
+ (u, v),
+ positions=spots,
+ vertex_config={"color": m.GREEN} if green else None,
+ )
+ assert added.submobjects == [
+ *(self.graph[w] for w in new),
+ self.graph.edges[u, v],
+ ]
+ for w in new:
+ self.where[w] = spots[w]
+ self.colors[w] = m.GREEN if green else m.BLUE
+ self.edges.append((u, v))
+
+ @precondition(lambda self: self.where)
+ @rule(data=st.data())
+ def remove_vertex(self, data: st.DataObject) -> None:
+ v = data.draw(st.sampled_from(sorted(self.where)))
+ touching = [e for e in self.edges if v in e]
+ expected = [*(self.graph.edges[e] for e in touching), self.graph[v]]
+ assert self.graph.remove_vertices(v).submobjects == expected
+ self.gone += [mob for part in expected for mob in part.get_family()]
+ del self.where[v], self.colors[v]
+ self.edges = [e for e in self.edges if v not in e]
+
+ @precondition(lambda self: self.edges)
+ @rule(data=st.data())
+ def remove_edge(self, data: st.DataObject) -> None:
+ # (an undirected graph's (u, v) and (v, u) are two edges, and one connection
+ # until both are gone: the layout functions see it)
+ e = data.draw(st.sampled_from(self.edges))
+ edge = self.graph.edges[e]
+ assert self.graph.remove_edges(e).submobjects == [edge]
+ self.gone += edge.get_family()
+ self.edges.remove(e)
+
+ @precondition(lambda self: self.where)
+ @rule(data=st.data())
+ def move_vertex(self, data: st.DataObject) -> None:
+ v = data.draw(st.sampled_from(sorted(self.where)))
+ spot = data.draw(st.sampled_from(self.free()))
+ self.graph[v].move_to(spot)
+ self.where[v] = spot
+
+ @precondition(lambda self: self.where)
+ @rule(data=st.data(), flat=st.booleans())
+ def lay_out_by_hand(self, data: st.DataObject, flat: bool) -> None:
+ spots = data.draw(st.permutations(SPOTS))
+ positions = dict(zip(self.where, spots, strict=False))
+ self.graph.change_layout(
+ {v: list(p[:2]) if flat else p for v, p in positions.items()}
+ )
+ self.where.update(positions)
+
+ @precondition(lambda self: self.where)
+ @rule(
+ scale=st.sampled_from([1.0, 3.0]),
+ config=st.sampled_from(
+ [None, {"token": TOKEN}, {"root_vertex": 7, "partitions": [[0]]}]
+ ),
+ partitions=st.sampled_from([None, [[5]]]),
+ root=st.sampled_from([None, 0]),
+ )
+ def lay_out_by_a_function(
+ self,
+ scale: float,
+ config: dict[str, object] | None,
+ partitions: list[list[int]] | None,
+ root: int | None,
+ ) -> None:
+ seen: list[Seen] = []
+
+ def layout(
+ topology: nx.Graph, scale: float = 2.0, **kwargs: object
+ ) -> dict[int, list[float]]:
+ nodes = list(topology)
+ seen.append(
+ (
+ scale,
+ kwargs,
+ nodes,
+ set(topology.edges),
+ dict(topology.graph),
+ [dict(topology.nodes[v]) for v in nodes],
+ )
+ )
+ topology.graph["stale"] = True # (what it does stays in this call)
+ topology.add_edge(98, 99)
+ for v in nodes:
+ topology.nodes[v]["weight"] = 1
+ return {v: [scale * i, 0.5 * i] for i, v in enumerate(nodes)}
+
+ self.graph.change_layout(
+ layout,
+ layout_scale=scale,
+ layout_config=config,
+ partitions=partitions,
+ root_vertex=root,
+ )
+ keywords = dict(config or {})
+ if partitions is not None:
+ keywords.setdefault("partitions", partitions)
+ if root is not None:
+ keywords.setdefault("root_vertex", root)
+ nodes = list(self.where)
+ [(seen_scale, seen_keywords, seen_nodes, seen_edges, *fresh)] = seen
+ assert (seen_scale, seen_keywords, seen_nodes) == (scale, keywords, nodes)
+ if self.kind is m.DiGraph:
+ assert seen_edges == set(self.edges)
+ else: # (an undirected pair is one connection, either way round)
+ assert {frozenset(e) for e in seen_edges} == {
+ frozenset(e) for e in self.edges
+ }
+ assert fresh == [{}, [{}] * len(nodes)]
+ for i, v in enumerate(nodes):
+ self.where[v] = np.array([scale * i, 0.5 * i, 0])
+
+ @precondition(lambda self: self.where)
+ @rule(data=st.data(), name=st.sampled_from(["circular", "partite"]))
+ def lay_out_by_name(self, data: st.DataObject, name: str) -> None:
+ vertices = list(self.where)
+ partitions = None
+ if name == "partite":
+ order = data.draw(st.permutations(vertices))
+ cut = data.draw(st.integers(1, len(order)))
+ partitions = [order[:cut][::2], order[:cut][1::2]]
+ partitions = [p for p in partitions if p]
+ fresh = self.kind(vertices, self.edges, layout=name, partitions=partitions)
+ self.graph.change_layout(name, partitions=partitions)
+ for v in vertices:
+ self.where[v] = fresh[v].get_center()
+
+ @rule()
+ def copy(self) -> None:
+ graph = self.graph
+ points = [mob.points.copy() for mob in graph.get_family()]
+ self.copied.append((graph, points, list(graph.vertices), list(graph.edges)))
+ self.graph = graph.copy()
+ assert not {id(mob) for mob in self.graph.get_family()} & {
+ id(mob) for mob in graph.get_family()
+ }
+ self.gone = []
+
+ @invariant()
+ def edges_join_their_vertices(self) -> None:
+ graph = self.graph
+ assert list(graph.vertices) == list(self.where)
+ assert list(graph.edges) == self.edges
+ family = {id(mob) for mob in graph.get_family()}
+ assert not any(id(mob) in family for mob in self.gone)
+ graph.update(0)
+ for v, spot in self.where.items():
+ np.testing.assert_allclose(graph[v].get_center(), spot, atol=1e-9)
+ assert graph[v].get_color() == self.colors[v]
+ assert graph[v].width == pytest.approx(0.3)
+ for (u, v), edge in graph.edges.items():
+ start, end = graph[u].get_center(), graph[v].get_center()
+ if isinstance(graph, m.DiGraph):
+ direction = end - start
+ start = graph[u].get_boundary_point(direction)
+ end = graph[v].get_boundary_point(-direction)
+ np.testing.assert_allclose(
+ edge.get_start_and_end(), [start, end], atol=1e-9
+ )
+
+ @invariant()
+ def copies_go_on_apart(self) -> None:
+ for graph, points, vertices, edges in self.copied:
+ graph.update(0)
+ assert (list(graph.vertices), list(graph.edges)) == (vertices, edges)
+ for mob, before in zip(graph.get_family(), points, strict=True):
+ np.testing.assert_allclose(mob.points, before, atol=1e-9)
+
+
+TestGraphs = Graphs.TestCase
+TestGraphs.settings = settings(stateful_step_count=20, max_examples=60)
diff --git a/tests/unit/mobjects/test_grid.py b/tests/unit/mobjects/test_grid.py
new file mode 100644
index 00000000..00804cdb
--- /dev/null
+++ b/tests/unit/mobjects/test_grid.py
@@ -0,0 +1,138 @@
+"""A matrix and a table lay their entries out on a grid.
+
+- A matrix places its cells `h_buff` and `v_buff` apart, by the corner it aligns them on, and
+ its brackets outside them.
+- A table's lines enclose its entries and bisect the gaps between rows and columns, in drawing
+ order, styled as asked; a cell's rectangle spans its row's height and its column's width,
+ with half a gap on each side, labels and an empty top-left corner included, however the
+ table is moved and scaled.
+"""
+
+from itertools import pairwise
+
+import numpy as np
+import pytest
+from hypothesis import given
+from hypothesis import strategies as st
+
+import manimgx as m
+from manimgx.typing import Vector3D
+
+
[email protected]("corner", [m.DR, m.UL, m.ORIGIN])
[email protected]("stretch", [True, False])
+def test_matrix_cells_keep_constructor_grid_spacing(
+ corner: Vector3D, stretch: bool
+) -> None:
+ cells = [
+ [
+ m.Rectangle(width=0.2 + column / 5, height=0.3 + row / 5)
+ for column in range(3)
+ ]
+ for row in range(2)
+ ]
+ matrix = m.MobjectMatrix(
+ cells,
+ h_buff=1.7,
+ v_buff=0.9,
+ element_alignment_corner=corner,
+ stretch_brackets=stretch,
+ )
+ anchor = cells[0][0].get_critical_point(corner)
+ for row, entries in enumerate(cells):
+ for column, entry in enumerate(entries):
+ np.testing.assert_allclose(
+ entry.get_critical_point(corner) - anchor,
+ column * 1.7 * m.RIGHT + row * 0.9 * m.DOWN,
+ atol=1e-12,
+ )
+ assert list(matrix.get_entries()) == [cell for row in cells for cell in row]
+ left, right = matrix.get_brackets()
+ assert left.get_right()[0] < matrix.get_entries().get_left()[0]
+ assert right.get_left()[0] > matrix.get_entries().get_right()[0]
+
+
+@given(
+ rows=st.integers(1, 4),
+ columns=st.integers(1, 4),
+ outer=st.booleans(),
+ inner=st.booleans(),
+ labels=st.booleans(),
+ corner=st.booleans(),
+ h_buff=st.floats(0.1, 2),
+ v_buff=st.floats(0.1, 2),
+)
+def test_lines_enclose_and_separate_rows_and_columns(
+ rows: int,
+ columns: int,
+ outer: bool,
+ inner: bool,
+ labels: bool,
+ corner: bool,
+ h_buff: float,
+ v_buff: float,
+) -> None:
+ table = m.MobjectTable(
+ [
+ [m.Rectangle(width=0.2 + c / 4, height=0.3 + r / 4) for c in range(columns)]
+ for r in range(rows)
+ ],
+ row_labels=[m.Square(0.2) for _ in range(rows)] if labels else None,
+ col_labels=[m.Square(0.2) for _ in range(columns)] if labels else None,
+ top_left_entry=m.Square(0.2) if corner and labels else None,
+ h_buff=h_buff,
+ v_buff=v_buff,
+ include_outer_lines=outer,
+ include_inner_lines=inner,
+ line_config={"color": m.RED, "stroke_width": 2},
+ )
+ row_groups, column_groups = table.get_rows(), table.get_columns()
+ left = table.elements.get_left()[0] - h_buff / 2
+ right = table.elements.get_right()[0] + h_buff / 2
+ top = row_groups.get_top()[1] + v_buff / 2
+ bottom = row_groups.get_bottom()[1] - v_buff / 2
+ expected_horizontal = []
+ expected_vertical = []
+ if outer:
+ expected_horizontal.extend(
+ (([left, top, 0], [right, top, 0]), ([left, bottom, 0], [right, bottom, 0]))
+ )
+ expected_vertical.extend(
+ (([left, top, 0], [left, bottom, 0]), ([right, top, 0], [right, bottom, 0]))
+ )
+ if inner:
+ for above, below in pairwise(row_groups):
+ y = (above.get_bottom()[1] + below.get_top()[1]) / 2
+ expected_horizontal.append(([left, y, 0], [right, y, 0]))
+ for before, after in pairwise(column_groups):
+ x = (before.get_right()[0] + after.get_left()[0]) / 2
+ expected_vertical.append(([x, bottom, 0], [x, top, 0]))
+ for lines, expected in (
+ (table.horizontal_lines, expected_horizontal),
+ (table.vertical_lines, expected_vertical),
+ ):
+ assert len(lines) == len(expected)
+ for line, ends in zip(lines, expected, strict=True):
+ np.testing.assert_allclose(line.get_start_and_end(), ends, atol=1e-12)
+ assert line.get_stroke_color() == m.RED
+ assert line.get_stroke_width() == 2
+ assert line in table.submobjects
+ table.scale(1.7).shift(m.UR)
+ for r, row in enumerate(table.get_rows(), 1):
+ for c, column in enumerate(table.get_columns(), 1):
+ cell = table.get_cell((r, c))
+ np.testing.assert_allclose(
+ [
+ cell.get_left()[0],
+ cell.get_right()[0],
+ cell.get_bottom()[1],
+ cell.get_top()[1],
+ ],
+ [
+ column.get_left()[0] - h_buff / 2,
+ column.get_right()[0] + h_buff / 2,
+ row.get_bottom()[1] - v_buff / 2,
+ row.get_top()[1] + v_buff / 2,
+ ],
+ atol=1e-12,
+ )