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

Orient graph layouts and derive edge geometry from current settings

Sina Atalay9920c27619ab
diff --git a/src/manimgx/mobjects/graph.py b/src/manimgx/mobjects/graph.py
index 5268977b..1bd68e63 100644
--- a/src/manimgx/mobjects/graph.py
+++ b/src/manimgx/mobjects/graph.py
@@ -18,7 +18,6 @@ from typing import (
Literal,
Protocol,
Self,
- TypedDict,
TypeIs,
Unpack,
cast,
@@ -26,6 +25,7 @@ from typing import (
)
import numpy as np
+from typing_extensions import TypedDict
if TYPE_CHECKING:
import networkx as nx
@@ -255,6 +255,119 @@ def _kamada_kawai_layout(
return dict(zip(nodes, x, strict=True))
+def _spectral_layout(
+ graph: NxGraph,
+ weight: str | None = "weight",
+ scale: float = 1,
+ center: Point3DLike | None = None,
+ dim: int = 2,
+ store_pos_as: str | None = None,
+) -> dict[Hashable, np.ndarray]:
+ """Laplacian coordinates with axes fixed by node order, including repeated eigenvalues.
+
+ An eigensolver chooses arbitrary signs and arbitrary orthonormal bases of repeated
+ eigenspaces. Projecting node coordinate axes into each whole space and choosing the
+ largest remaining projection avoids magnifying a nearly zero coordinate into an axis.
+ Node order breaks numerical ties. Unresolved neighboring spaces are oriented jointly;
+ like any spectral embedding, nearly degenerate weights can make coordinates sensitive
+ to perturbations. The constant direction is removed explicitly, also for disconnected
+ graphs.
+ """
+ import networkx as nx
+
+ nodes, n = list(graph), len(graph)
+ origin = np.zeros(dim) if center is None else np.asarray(center, dtype=float)
+ if dim < 1 or origin.shape != (dim,):
+ raise ValueError(
+ "a layout needs a positive dimension and a center of that dimension"
+ )
+ if n == 0:
+ return {}
+ points = np.zeros((n, dim))
+ if n > 1:
+ adjacency = nx.to_numpy_array(graph, weight=weight)
+ if not np.isfinite(adjacency).all():
+ raise ValueError("spectral edge weights must be finite")
+ if magnitude := float(np.abs(adjacency).max()):
+ adjacency /= magnitude
+ if graph.is_directed():
+ adjacency += adjacency.T.copy()
+ laplacian = np.diag(adjacency.sum(axis=1)) - adjacency
+ values, vectors = np.linalg.eigh(laplacian)
+ rounding = np.finfo(float).eps * n
+ # Cluster only eigenvalues indistinguishable at this solve's backward error:
+ # its measured residual plus the rounding in an n-term matrix product.
+ error = np.linalg.norm(laplacian @ vectors - vectors * values)
+ error += rounding * np.sqrt(n) * np.linalg.norm(laplacian, ord=np.inf)
+ cuts = [0, *(np.flatnonzero(np.diff(values) > 2 * error) + 1), n]
+ columns: list[np.ndarray] = []
+ group = 0
+ while group + 1 < len(cuts):
+ start, end = cuts[group : group + 2]
+ # A space and its orthogonal complement define the same projector. Use the
+ # smaller basis: a full space is exactly I, independent of a solver's axes.
+ complement = end - start > n // 2
+ space = (
+ np.concatenate((vectors[:, :start], vectors[:, end:]), axis=1)
+ if complement
+ else vectors[:, start:end]
+ )
+ projection = space @ space.T
+ if complement:
+ projection = np.eye(n) - projection
+ orthogonality = np.linalg.norm(space.T @ space - np.eye(space.shape[1]))
+ constant = bool(np.any(np.abs(values[start:end]) <= error))
+ if constant:
+ projection -= np.full((n, n), 1 / n)
+ gap = min(
+ values[start] - values[start - 1] if start else np.inf,
+ values[end] - values[end - 1] if end < n else np.inf,
+ )
+ # Residual/gap estimates the uncertainty of a space, not just its eigenvalue.
+ uncertainty = rounding + orthogonality + error / (gap - error)
+ wanted = min(end - start - int(constant), dim - len(columns))
+ basis: list[np.ndarray] = []
+ projection -= projection.mean(axis=0)
+ for _ in range(2):
+ for previous in columns:
+ projection -= np.outer(previous, previous @ projection)
+ for _ in range(wanted):
+ lengths = np.linalg.norm(projection, axis=0)
+ largest = float(lengths.max())
+ if largest <= 2 * uncertainty:
+ break
+ pivot = int(np.flatnonzero(lengths >= largest - uncertainty)[0])
+ direction = projection[:, pivot] / lengths[pivot]
+ basis.append(direction)
+ # Pivoted, twice-orthogonalized projections keep later axes away from
+ # directions already chosen, without amplifying tiny first-node entries.
+ for _ in range(2):
+ projection -= np.outer(direction, direction @ projection)
+ if len(basis) < wanted:
+ # These directions cannot be resolved from a neighboring space with
+ # this solve's accuracy. Orient their joint space instead of silently
+ # losing a low-frequency coordinate or replacing it with a higher one.
+ neighbors = [i for i in (group, group + 1) if 0 < i < len(cuts) - 1]
+ if not neighbors:
+ raise ValueError("spectral coordinates could not be resolved")
+ boundary = min(
+ neighbors, key=lambda i: values[cuts[i]] - values[cuts[i] - 1]
+ )
+ del cuts[boundary]
+ columns, group = [], 0
+ continue
+ columns.extend(basis)
+ if len(columns) == dim:
+ break
+ group += 1
+ points[:, : len(columns)] = np.array(columns).T
+ points = nx.rescale_layout(points, scale=scale) + origin
+ positions = dict(zip(nodes, points, strict=True))
+ if store_pos_as is not None:
+ nx.set_node_attributes(graph, positions, store_pos_as)
+ return positions
+
+
LayoutName = Literal[
"circular",
"kamada_kawai",
@@ -267,8 +380,8 @@ LayoutName = Literal[
"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."""
+[GenericGraph][manimgx.mobjects.graph.GenericGraph]). The spectral layout fixes its axes by
+node order, so an eigensolver's arbitrary choice of basis does not rotate or skew a graph."""
def _layout(name: LayoutName) -> LayoutFunction[Hashable]:
@@ -280,7 +393,7 @@ def _layout(name: LayoutName) -> LayoutFunction[Hashable]:
"partite": _partite_layout,
"planar": nx.layout.planar_layout,
"shell": nx.layout.shell_layout,
- "spectral": nx.layout.spectral_layout,
+ "spectral": _spectral_layout,
"spiral": nx.layout.spiral_layout,
"spring": nx.layout.spring_layout,
"tree": _tree_layout,
@@ -302,7 +415,7 @@ def _is_name(layout: object) -> TypeIs[LayoutName]:
return isinstance(layout, str) and layout in get_args(LayoutName)
-class VertexOptions[V: Hashable](TypedDict, total=False):
+class VertexOptions[V: Hashable](TypedDict, total=False, closed=True):
"""[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."""
@@ -324,18 +437,7 @@ class VertexOptions[V: Hashable](TypedDict, total=False):
"""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):
+class GraphOptions[V: Hashable](TypedDict, total=False, closed=True):
"""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
@@ -493,19 +595,10 @@ class GenericGraph[V: Hashable = Hashable](VMobject):
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.default_edge_config, own_edges = _split(edge_config, edges)
+ self._edge_config: dict[Edge[V], Config] = {
+ e: own_edges.get(e, copy(self.default_edge_config)) for e in edges
+ }
self._populate_edge_dict(edges, edge_type)
self.add(*self.vertices.values())
self.add(*self.edges.values())
@@ -726,7 +819,13 @@ class GenericGraph[V: Hashable = Hashable](VMobject):
self.add(edge_mobject)
return Group(edge_mobject)
- def add_edges(self, *edges: Edge[V], **kwargs: Unpack[EdgeOptions[V]]) -> Group:
+ def add_edges(
+ self,
+ *edges: Edge[V],
+ edge_type: Maker = Line,
+ edge_config: Configs | None = None,
+ **kwargs: Unpack[VertexOptions[V]],
+ ) -> Group:
"""Add edges to the graph, and the vertices they name that it lacks.
The missing vertices are added first, as
@@ -736,15 +835,17 @@ class GenericGraph[V: Hashable = Hashable](VMobject):
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.
+ edge_type: The class of the new edges.
+ edge_config: 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;
+ None for none.
+ **kwargs: [Vertex keywords][manimgx.mobjects.graph.VertexOptions] for the
+ vertices the edges name that the graph lacks.
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)
+ shared, own = _split(edge_config, 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
@@ -955,8 +1056,9 @@ class Graph[V: Hashable = Hashable](GenericGraph[V]):
return nx.Graph()
def _make_edge(self, edge_type: Maker, u: V, v: V, config_: Config) -> Mobject:
+ style = {k: v for k, v in config_.items() if k != "tip_config"}
return edge_type(
- start=self[u].get_center(), end=self[v].get_center(), z_index=-1, **config_
+ start=self[u].get_center(), end=self[v].get_center(), z_index=-1, **style
)
def update_edges(self, graph: Mobject) -> Self:
@@ -1016,9 +1118,14 @@ class DiGraph[V: Hashable = Hashable](GenericGraph[V]):
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_)
+ style = config_.copy()
+ tips = cast(
+ "TipConfig",
+ style.pop("tip_config", self.default_edge_config.get("tip_config", {})),
+ )
+ edge = edge_type(start=self[u], end=self[v], z_index=-1, **style)
if isinstance(edge, Line):
- edge.add_tip(**cast("TipConfig", self._tip_config.get((u, v), {})))
+ edge.add_tip(**tips)
return edge
def update_edges(self, graph: Mobject) -> Self:
diff --git a/src/manimgx/mobjects/plotting.py b/src/manimgx/mobjects/plotting.py
index c2f8516a..b0896977 100644
--- a/src/manimgx/mobjects/plotting.py
+++ b/src/manimgx/mobjects/plotting.py
@@ -34,7 +34,6 @@ from typing import (
ClassVar,
Literal,
Self,
- TypedDict,
Unpack,
cast,
overload,
@@ -43,6 +42,7 @@ from typing import (
import numpy as np
import numpy.typing as npt
from isosurfaces import plot_isoline
+from typing_extensions import TypedDict
from manimgx.config import config
from manimgx.constants import (
@@ -80,6 +80,7 @@ from manimgx.drawing.paint import (
ParsableManimColor,
Style,
StyleBase,
+ _Style,
color_gradient,
colors_by_value,
invert_color,
@@ -94,10 +95,12 @@ from manimgx.mobjects.shapes import (
DashedLineOptions,
Dot,
Line,
+ LineOptions,
Polygon,
Rectangle,
RegularPolygon,
Tipped,
+ _Tipped,
)
from manimgx.mobjects.text import MathTex, MathTexOptions, Tex, Typst
from manimgx.typing import ManimTextLabel, Vector3D
@@ -323,10 +326,8 @@ class LogBase(_ScaleBase):
_CURVE_LINEAR = LinearBase() # a default (never changed)
-class CurveOptions(Style, total=False):
- """How a curve is sampled and smoothed, with the style keywords: the keywords of
- [plot][manimgx.Axes.plot] and the other curves, for the methods that
- pass them on."""
+class _CurveOptions(_Style, total=False):
+ """CurveOptions's keys, open, for the keywords that add to them."""
dt: float
"""How far short of each discontinuity the curve's pieces stop, in units of its
@@ -339,7 +340,13 @@ class CurveOptions(Style, total=False):
straight segments (default True)."""
-class ParametricOptions(CurveOptions, total=False):
+class CurveOptions(_CurveOptions, total=False, closed=True):
+ """How a curve is sampled and smoothed, with the style keywords: the keywords of
+ [plot][manimgx.Axes.plot] and the other curves, for the methods that
+ pass them on."""
+
+
+class ParametricOptions(_CurveOptions, total=False):
"""A [ParametricFunction][manimgx.ParametricFunction]'s keywords but its function:
its parameter's range and spacing, with the curve keywords."""
@@ -565,7 +572,7 @@ class FunctionGraph(ParametricFunction):
return self.parametric_function(x)
-class ImplicitOptions(Style, total=False):
+class ImplicitOptions(_Style, total=False, closed=True):
"""An [ImplicitFunction][manimgx.ImplicitFunction]'s smoothing, with the style
keywords, for the methods that pass them on
([plot_implicit_curve][manimgx.Axes.plot_implicit_curve])."""
@@ -667,7 +674,7 @@ default)."""
_AXIS_LINEAR = LinearBase() # a default (never changed)
-class NumberLineOptions(Tipped, total=False):
+class NumberLineOptions(_Tipped, total=False, closed=True):
"""A [NumberLine][manimgx.NumberLine]'s keywords but its range, for the configs that
pass them on (a coordinate system's axes): its size, ticks, tip and numbers, with
the style and tip keywords."""
@@ -1333,6 +1340,13 @@ type Coordinates = (
points at once."""
+def _halved(opacity: float | Sequence[float]) -> float | list[float]:
+ """An opacity, or one for each part, at half strength."""
+ if isinstance(opacity, int | float):
+ return opacity * 0.5
+ return [o * 0.5 for o in opacity]
+
+
def merged_axis_config(*configs: NumberLineOptions | None) -> NumberLineOptions:
"""Merge axis configs: later ones win, key by key, and inside their
`decimal_number_config` too. An iterator among the values is read into a list: the
@@ -1365,7 +1379,7 @@ def merged_axis_config(*configs: NumberLineOptions | None) -> NumberLineOptions:
return merged
-class AxisLine(TypedDict, total=False):
+class AxisLine(TypedDict, total=False, closed=True):
"""The keywords of a line from an axis to a point
([get_vertical_line][manimgx.Axes.get_vertical_line] and the like): its class, its
keywords, its color and its width."""
@@ -1383,7 +1397,7 @@ class AxisLine(TypedDict, total=False):
"""The line's width, in hundredths of a scene unit (default 2)."""
-class PlotOptions(CurveOptions, total=False):
+class PlotOptions(_CurveOptions, total=False, closed=True):
"""[plot][manimgx.Axes.plot]'s keywords but its function, for the methods that pass
them on ([plot_derivative_graph][manimgx.Axes.plot_derivative_graph],
[plot_antiderivative_graph][manimgx.Axes.plot_antiderivative_graph]): the range of
@@ -1449,10 +1463,12 @@ class Axes(VGroup):
x_range: The x-axis's range, `[x_min, x_max, x_step]`, or `[x_min, x_max]` for
a step of 1; None for the frame's width, [-7, 7, 1].
y_range: The y-axis's range, likewise; None for the frame's height, [-4, 4, 1].
- x_length: The x-axis's length, in scene units: by default the frame's width
- less 2, rounded (12); None for `unit_size` (by default 1) per unit.
- y_length: The y-axis's length, in scene units: by default the frame's height
- less 2, rounded (6); None for `unit_size` per unit.
+ x_length: The x-axis's length, in scene units; None for the frame's width
+ less 2, rounded, as the frame is when the axes are made (12 in a wide video,
+ 6 in a tall one), or `unit_size` per unit if the axis's config gives one.
+ y_length: The y-axis's length, in scene units; None for the frame's height
+ less 2, rounded (6 in a wide video, 12 in a tall one), or `unit_size` per unit
+ if the axis's config gives one.
axis_config: [Number line keywords][manimgx.NumberLine]
for both axes: `include_numbers`, `font_size`, `color`, …; None for none.
x_axis_config: Number line keywords for the x-axis, over `axis_config`'s; None
@@ -1488,8 +1504,8 @@ class Axes(VGroup):
self,
x_range: Sequence[float] | None = None,
y_range: Sequence[float] | None = None,
- x_length: float | None = round(config.frame_width) - 2,
- y_length: float | None = round(config.frame_height) - 2,
+ x_length: float | None = None,
+ y_length: float | None = None,
axis_config: NumberLineOptions | None = None,
x_axis_config: NumberLineOptions | None = None,
y_axis_config: NumberLineOptions | None = None,
@@ -1516,9 +1532,9 @@ class Axes(VGroup):
y_axis_config,
)
)
- self.x_axis = self._create_axis(self.x_range, x_axis_config, x_length)
+ self.x_axis = self._create_axis(self.x_range, x_axis_config, x_length, 0)
"""The x-axis, a [NumberLine][manimgx.NumberLine]."""
- self.y_axis = self._create_axis(self.y_range, y_axis_config, y_length)
+ self.y_axis = self._create_axis(self.y_range, y_axis_config, y_length, 1)
"""The y-axis, a [NumberLine][manimgx.NumberLine]."""
self.x_length, self.y_length = (
self.x_axis.get_length(),
@@ -1538,11 +1554,20 @@ class Axes(VGroup):
range_terms: Sequence[float] | None,
axis_config: NumberLineOptions,
length: float | None,
+ index: int,
) -> NumberLine:
+ if length is None and "unit_size" not in axis_config:
+ length = self._fitting_length(index)
axis = NumberLine(range_terms, **(axis_config | {"length": length}))
axis.shift(-axis.number_to_point(_origin_shift([axis.x_min, axis.x_max])))
return axis
+ def _fitting_length(self, index: int) -> float:
+ """The length of an axis given none (0: x, 1: y): the frame's width or height
+ less 2, rounded, as the frame is now (a scene's file may make it tall after
+ manimgx is imported)."""
+ return round((config.frame_width, config.frame_height)[index]) - 2
+
def coords_to_point(self, *coords: Coordinates) -> npt.NDArray[np.float64]:
"""Convert coordinates on the axes to a point of the scene, or arrays of them to
points.
@@ -1884,12 +1909,18 @@ class Axes(VGroup):
Returns:
A new line, not added to the axes.
"""
+ start = self.get_axis(index).get_projection(point)
style = (line_config or DashedLineOptions()).copy()
style["color"], style["stroke_width"] = (
ManimColor(WHITE if color is None else color),
stroke_width,
)
- return line_func(self.get_axis(index).get_projection(point), point, **style)
+ if issubclass(line_func, DashedLine):
+ return line_func(start, point, **style)
+ # a solid line has no dashes: it takes the line keywords without them
+ style.pop("dash_length", None)
+ style.pop("dashed_ratio", None)
+ return line_func(start, point, **cast("LineOptions", style))
def get_vertical_line(self, point: Point3DLike, **kwargs: Unpack[AxisLine]) -> Line:
"""Make a line from the x-axis up (or down) to a point: dashed, white and thin
@@ -2918,11 +2949,8 @@ def _origin_shift(axis_range: Sequence[float]) -> float:
return 0
-class AxesOptions(Style, total=False):
- """[Axes][manimgx.Axes]' keywords but their ranges and lengths, for the classes that
- pass them on ([ThreeDAxes][manimgx.ThreeDAxes], the planes,
- [BarChart][manimgx.BarChart]): their axes' configs and tips, with the style
- keywords."""
+class _AxesOptions(_Style, total=False):
+ """AxesOptions's keys, open, for the keywords that add to them."""
axis_config: NumberLineOptions | None
"""[Number line keywords][manimgx.NumberLine]
@@ -2938,6 +2966,13 @@ class AxesOptions(Style, total=False):
unless `axis_config` includes `include_tip`)."""
+class AxesOptions(_AxesOptions, total=False, closed=True):
+ """[Axes][manimgx.Axes]' keywords but their ranges and lengths, for the classes that
+ pass them on ([ThreeDAxes][manimgx.ThreeDAxes], the planes,
+ [BarChart][manimgx.BarChart]): their axes' configs and tips, with the style
+ keywords."""
+
+
def _origin_tick(config_: NumberLineOptions) -> NumberLineOptions:
"""A linear axis leaves its origin unticked (the other axis crosses there)."""
return config_ | {
@@ -2969,12 +3004,13 @@ class ThreeDAxes(Axes):
a step of 1; None for [-7, 7, 1].
y_range: The y-axis's range, likewise; None for [-4, 4, 1].
z_range: The z-axis's range, likewise; None for [-7, 7, 1].
- x_length: The x-axis's length, in scene units: by default the frame's height
- plus 2.5 (10.5); None for `unit_size` (by default 1) per unit.
- y_length: The y-axis's length, in scene units: by default 10.5 too; None for
- `unit_size` per unit.
- z_length: The z-axis's length, in scene units: by default the frame's height
- less 1.5 (6.5); None for `unit_size` per unit.
+ x_length: The x-axis's length, in scene units; None for the frame's short side
+ plus 2.5 (10.5, in a wide video and a tall one), or `unit_size` per unit if
+ the axis's config gives one.
+ y_length: The y-axis's length, in scene units; None for 10.5 too, or `unit_size`
+ per unit if the axis's config gives one.
+ z_length: The z-axis's length, in scene units; None for the frame's short side
+ less 1.5 (6.5), or `unit_size` per unit if the axis's config gives one.
z_axis_config: [Number line keywords][manimgx.NumberLine]
for the z-axis, over `axis_config`'s; None for none.
**kwargs: [Axes keywords][manimgx.mobjects.plotting.AxesOptions]:
@@ -3006,9 +3042,9 @@ class ThreeDAxes(Axes):
x_range: Sequence[float] | None = (-6, 6, 1),
y_range: Sequence[float] | None = (-5, 5, 1),
z_range: Sequence[float] | None = (-4, 4, 1),
- x_length: float | None = config.frame_height + 2.5,
- y_length: float | None = config.frame_height + 2.5,
- z_length: float | None = config.frame_height - 1.5,
+ x_length: float | None = None,
+ y_length: float | None = None,
+ z_length: float | None = None,
z_axis_config: NumberLineOptions | None = None,
**kwargs: Unpack[AxesOptions],
):
@@ -3028,7 +3064,7 @@ class ThreeDAxes(Axes):
"""The z-axis's range, as given."""
z_axis_config = _origin_tick(merged_axis_config(axis_config, z_axis_config))
self.dimension = 3
- z_axis = self._create_axis(self.z_range, z_axis_config, z_length)
+ z_axis = self._create_axis(self.z_range, z_axis_config, z_length, 2)
z_origin = _origin_shift([z_axis.x_min, z_axis.x_max])
z_axis.rotate_about_number(z_origin, -PI / 2, UP)
z_axis.rotate_about_number(z_origin, angle_of_vector(DOWN))
@@ -3046,6 +3082,12 @@ class ThreeDAxes(Axes):
self._add_3d_pieces()
self._set_axis_shading()
+ def _fitting_length(self, index: int) -> float:
+ """The length of an axis given none (0: x, 1: y, 2: z), from the frame's short
+ side, which a wide video and a tall one share."""
+ short = min(config.frame_width, config.frame_height)
+ return short - 1.5 if index == 2 else short + 2.5
+
def _add_3d_pieces(self) -> None:
for axis in self.axes:
drawing = VMobject(z_index=axis.z_index)
@@ -3171,6 +3213,10 @@ class _Plane(Axes):
background_line_style = Style(
stroke_color=BLUE_D, stroke_width=2, stroke_opacity=1
) | (background_line_style or Style())
+ # a plane's unit is a scene unit, unless a length or a unit_size is given
+ kwargs["axis_config"] = merged_axis_config(
+ {"unit_size": 1}, kwargs.get("axis_config")
+ )
super().__init__(
x_range=x_range,
y_range=y_range,
@@ -3180,10 +3226,12 @@ class _Plane(Axes):
)
if faded_line_style is None: # the background lines at half strength
faded = background_line_style.copy()
- for key in ("stroke_width", "stroke_opacity", "fill_opacity"):
- value = faded.get(key)
- if value is not None:
- faded[key] = value * 0.5
+ if (width := faded.get("stroke_width")) is not None:
+ faded["stroke_width"] = width * 0.5
+ if (opacity := faded.get("stroke_opacity")) is not None:
+ faded["stroke_opacity"] = _halved(opacity)
+ if (opacity := faded.get("fill_opacity")) is not None:
+ faded["fill_opacity"] = _halved(opacity)
faded_line_style = faded
self.background_lines, self.faded_lines = self._get_lines(faded_line_ratio)
for lines, style in (
@@ -3239,7 +3287,7 @@ class _Plane(Axes):
return self
-class NumberPlaneOptions(AxesOptions, total=False):
+class NumberPlaneOptions(_AxesOptions, total=False, closed=True):
"""A [NumberPlane][manimgx.NumberPlane]'s keywords, for the scenes that pass them on
([LinearTransformationScene][manimgx.LinearTransformationScene], …): its ranges,
sizes and grid, with the axes' keywords."""
diff --git a/tests/unit/mobjects/test_graph.py b/tests/unit/mobjects/test_graph.py
index 0940e3b5..5a9b1e7f 100644
--- a/tests/unit/mobjects/test_graph.py
+++ b/tests/unit/mobjects/test_graph.py
@@ -11,9 +11,14 @@
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.
+- Spectral coordinates depend on Laplacian eigenspaces, independent of their solved basis.
+- Each edge uses its current settings; removing it releases those settings and their keys.
- A copy goes on apart: what is done to it leaves the graph it was copied from.
"""
+import gc
+import weakref
+
import networkx as nx
import numpy as np
import pytest
@@ -28,7 +33,7 @@ from hypothesis.stateful import (
)
import manimgx as m
-from manimgx.mobjects.graph import GenericGraph
+from manimgx.mobjects.graph import GenericGraph, _spectral_layout
KEYS = range(6)
SPOTS = [
@@ -303,3 +308,247 @@ class Graphs(RuleBasedStateMachine):
TestGraphs = Graphs.TestCase
TestGraphs.settings = settings(stateful_step_count=20, max_examples=60)
+
+
+ ("graph", "groups"),
+ [
+ (nx.empty_graph(2), [(0, 2)]),
+ (nx.empty_graph(6), [(0, 6)]),
+ (nx.complete_graph(6), [(0, 1), (1, 6)]),
+ (nx.cycle_graph(6), [(0, 1), (1, 3), (3, 5), (5, 6)]),
+ (
+ nx.disjoint_union(nx.path_graph(3), nx.path_graph(3)),
+ [(0, 2), (2, 4), (4, 6)],
+ ),
+ (
+ nx.Graph(
+ [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1), (5, 1), (1, 3), (3, 5)]
+ ),
+ [(0, 1), (1, 3), (3, 4), (4, 6)],
+ ),
+ ],
+ ids=["isolated-pair", "isolated", "complete", "cycle", "disconnected", "corpus"],
+)
+def test_axes_do_not_depend_on_the_eigensolvers_basis(
+ graph: nx.Graph, groups: list[tuple[int, int]], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ expected = np.array(list(_spectral_layout(graph).values()))
+ solve = np.linalg.eigh
+ rng = np.random.default_rng(2026)
+
+ def other_basis(matrix: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ values, vectors = solve(matrix)
+ for start, end in groups:
+ rotation, _ = np.linalg.qr(rng.normal(size=(end - start, end - start)))
+ vectors[:, start:end] = vectors[:, start:end] @ rotation
+ return values, vectors
+
+ monkeypatch.setattr(np.linalg, "eigh", other_basis)
+ for _ in range(64):
+ found = np.array(list(_spectral_layout(graph).values()))
+ np.testing.assert_allclose(found, expected, rtol=0, atol=1e-13)
+
+
+ "graph",
+ [nx.path_graph(8), nx.complete_graph(8), nx.cycle_graph(8), nx.empty_graph(8)],
+)
+def test_coordinates_are_centered_orthogonal_lowest_laplacian_directions(
+ graph: nx.Graph,
+) -> None:
+ adjacency = nx.to_numpy_array(graph)
+ laplacian = np.diag(adjacency.sum(axis=1)) - adjacency
+ expected = np.linalg.eigvalsh(laplacian)[1:4]
+ points = np.array(list(_spectral_layout(graph, dim=3).values()))
+ directions = points / np.linalg.norm(points, axis=0)
+ np.testing.assert_allclose(directions.mean(axis=0), 0, atol=1e-13)
+ np.testing.assert_allclose(directions.T @ directions, np.eye(3), atol=1e-13)
+ np.testing.assert_allclose(
+ laplacian @ directions, directions * expected, atol=1e-13
+ )
+
+
[email protected]("count", [0, 1, 2, 3])
+def test_small_graphs_honor_dimensions_scale_and_center(count: int) -> None:
+ graph = nx.path_graph(count)
+ center = np.array([2.0, 3.0, 4.0])
+ positions = _spectral_layout(
+ graph, dim=3, scale=2, center=center, store_pos_as="position"
+ )
+ assert list(positions) == list(graph)
+ for node, position in positions.items():
+ assert position.shape == (3,)
+ np.testing.assert_array_equal(graph.nodes[node]["position"], position)
+ if count:
+ points = np.array(list(positions.values()))
+ np.testing.assert_allclose(points.mean(axis=0), center, atol=1e-13)
+ assert np.abs(points - center).max() == pytest.approx(0 if count == 1 else 2)
+
+
+def test_directed_edges_define_the_same_symmetric_laplacian() -> None:
+ directed = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
+ expected = _spectral_layout(directed.to_undirected())
+ found = _spectral_layout(directed)
+ np.testing.assert_array_equal(list(found.values()), list(expected.values()))
+
+
[email protected]("separation", [2.0**-20, 2.0**-47])
+def test_unresolved_orientation_neither_flips_nor_drops_a_low_mode(
+ separation: float, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Backward-stable solves can disagree at a zero component near another mode."""
+ s = 2**-0.5
+ q = np.array(
+ [[0.5, 0, s, 0.5], [0.5, s, 0, -0.5], [0.5, -s, 0, -0.5], [0.5, 0, -s, 0.5]]
+ )
+ first = np.outer([0, 1, -1, 0], [0, 1, -1, 0])
+ second = np.outer([1, 0, 0, -1], [1, 0, 0, -1])
+ last = np.outer([1, -1, -1, 1], [1, -1, -1, 1])
+ adjacency = -0.5 * first - 0.5 * (1 + separation) * second - 0.375 * last
+ np.fill_diagonal(adjacency, 0)
+ graph = nx.from_numpy_array(adjacency)
+ found: list[np.ndarray] = []
+ for angle in (-1e-10, 1e-10):
+
+ def solve(
+ matrix: np.ndarray, angle: float = angle
+ ) -> tuple[np.ndarray, np.ndarray]:
+ values = np.diag(q.T @ matrix @ q).copy()
+ vectors = q.copy()
+ c, s = np.cos(angle), np.sin(angle)
+ vectors[:, 1:3] = vectors[:, 1:3] @ np.array([[c, -s], [s, c]])
+ assert np.linalg.norm(matrix @ vectors - vectors * values) < 1e-14
+ return values, vectors
+
+ monkeypatch.setattr(np.linalg, "eigh", solve)
+ points = np.array(list(_spectral_layout(graph).values()))
+ directions = points / np.linalg.norm(points, axis=0)
+ np.testing.assert_allclose(directions.T @ directions, np.eye(2), atol=1e-13)
+ np.testing.assert_allclose(
+ directions @ directions.T, q[:, 1:3] @ q[:, 1:3].T, atol=1e-13
+ )
+ found.append(points)
+ np.testing.assert_allclose(found[0], found[1], atol=1e-8)
+
+
[email protected]("scale", [1e-200, 1e200])
+def test_uniform_weight_scale_does_not_change_the_coordinates(scale: float) -> None:
+ graph = nx.cycle_graph(6)
+ expected = _spectral_layout(graph)
+ nx.set_edge_attributes(graph, scale, "weight")
+ found = _spectral_layout(graph)
+ np.testing.assert_allclose(
+ list(found.values()), list(expected.values()), atol=1e-13
+ )
+
+
+def test_a_nearly_zero_node_projection_does_not_amplify_solver_rounding(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ constant = np.ones(6) / np.sqrt(6)
+ first = np.array([0, 1, -1, 0, 0, 0]) / np.sqrt(2)
+ second = np.array([0, 1, 1, -2, 0, 0]) / np.sqrt(6)
+ high = np.array([5, -1, -1, -1, -1, -1]) / np.sqrt(30)
+ q, _ = np.linalg.qr(
+ np.column_stack([constant, first, second, high]), mode="complete"
+ )
+
+ def rotate(q: np.ndarray, left: int, right: int, angle: float) -> np.ndarray:
+ q = q.copy()
+ c, s = np.cos(angle), np.sin(angle)
+ q[:, [left, right]] = q[:, [left, right]] @ np.array([[c, -s], [s, c]])
+ return q
+
+ q = rotate(q, 1, 3, 1e-13)
+ adjacency = -(q @ np.diag([0, 4, 4, 5, 5, 5]) @ q.T)
+ np.fill_diagonal(adjacency, 0)
+ assert (adjacency >= 0).all()
+ graph = nx.from_numpy_array(adjacency)
+ found: list[np.ndarray] = []
+ for noise in (-2e-15, 2e-15):
+
+ def solve(
+ matrix: np.ndarray, noise: float = noise
+ ) -> tuple[np.ndarray, np.ndarray]:
+ values = np.diag(q.T @ matrix @ q).copy()
+ vectors = rotate(q, 2, 3, noise)
+ assert np.linalg.norm(matrix @ vectors - vectors * values) < 1e-14
+ return values, vectors
+
+ monkeypatch.setattr(np.linalg, "eigh", solve)
+ found.append(np.array(list(_spectral_layout(graph).values())))
+ np.testing.assert_allclose(found[0], found[1], rtol=0, atol=1e-13)
+
+
+PLACES = {0: [-3, 0, 0], 1: [-1, 0, 0], 2: [1, 0, 0], 3: [3, 0, 0]}
+
+
[email protected]("added", [False, True])
+def test_constructed_and_added_edges_apply_default_and_own_tip_settings(
+ added: bool,
+) -> None:
+ edges = [(0, 1), (1, 2), (2, 3)]
+ shared = {"tip_config": {"tip_shape": m.ArrowSquareTip, "tip_length": 0.2}}
+ own = {
+ (0, 1): {"color": m.RED},
+ (1, 2): {"tip_config": {"tip_shape": m.ArrowCircleTip, "tip_length": 0.3}},
+ }
+ graph = m.DiGraph(
+ list(PLACES),
+ [] if added else edges,
+ layout=PLACES,
+ edge_config=shared if added else shared | own,
+ )
+ if added:
+ graph.add_edges(*edges, edge_config=own)
+ graph.update(0)
+ for key, shape, length in [
+ ((0, 1), m.ArrowSquareTip, 0.2),
+ ((1, 2), m.ArrowCircleTip, 0.3),
+ ((2, 3), m.ArrowSquareTip, 0.2),
+ ]:
+ edge = graph.edges[key]
+ assert isinstance(edge, m.Line)
+ assert type(edge.get_tip()) is shape
+ assert edge.get_tip().length == pytest.approx(shape(length=length).length)
+ assert graph.edges[0, 1].get_color() == m.RED
+
+
[email protected]("vertex", [False, True])
+def test_readded_edges_use_current_settings_instead_of_removed_edge_settings(
+ vertex: bool,
+) -> None:
+ graph = m.DiGraph(
+ [0, 1],
+ [(0, 1)],
+ layout=PLACES,
+ edge_config={"tip_config": {"tip_shape": m.ArrowSquareTip}},
+ )
+ previous = graph.edges[0, 1]
+ if vertex:
+ graph.remove_vertices(1)
+ else:
+ graph.remove_edges((0, 1))
+ graph.add_edges(
+ (0, 1),
+ positions=PLACES,
+ edge_config={"tip_config": {"tip_shape": m.ArrowCircleTip}},
+ )
+ edge = graph.edges[0, 1]
+ assert isinstance(edge, m.Line)
+ assert type(edge.get_tip()) is m.ArrowCircleTip
+ assert previous not in graph.get_family()
+
+
+def test_removing_a_vertex_releases_the_keys_of_its_edge_settings() -> None:
+ class Key:
+ pass
+
+ key = Key()
+ reference = weakref.ref(key)
+ graph = m.DiGraph([key, 0], [(key, 0)], layout="circular")
+ graph.remove_vertices(key)
+ del key
+ gc.collect()
+ assert reference() is None
diff --git a/tests/unit/mobjects/test_plotting.py b/tests/unit/mobjects/test_plotting.py
index 6f05275a..a3a2ab45 100644
--- a/tests/unit/mobjects/test_plotting.py
+++ b/tests/unit/mobjects/test_plotting.py
@@ -21,6 +21,9 @@
with a background line. Faded lines are half as wide and opaque as the background ones.
- Each bar of a bar chart spans from 0 to its value, made with the values or changed to them.
- A sample space's divisions tile it, in either direction.
+- Axes and planes fit the frame they are made in, wide, tall or square: axes given no length
+ span the frame less a margin (3D axes, its short side), and planes fill it, but an axis
+ given a `unit_size` and no length is that size per unit.
"""
from collections.abc import Callable, Sequence
@@ -449,6 +452,47 @@ def test_a_plane_fills_the_frame_it_is_made_in(size: tuple[int, int]) -> None:
assert m.PolarPlane().width == pytest.approx(2 * min(w, h))
+ ("size", "lengths"),
+ [((1920, 1080), (12, 6)), ((1080, 1920), (6, 12)), ((1000, 1000), (6, 6))],
+)
+def test_axes_fit_the_frame_they_are_made_in(
+ size: tuple[int, int], lengths: tuple[float, float]
+) -> None:
+ # the frame as the scene's file sets it, after manimgx is imported: wide, tall, square
+ m.config.pixel_width, m.config.pixel_height = size
+ axes = m.Axes()
+ assert (axes.x_length, axes.y_length) == pytest.approx(lengths)
+ # 3D axes take the frame's short side, which these frames share
+ three_d = m.ThreeDAxes()
+ assert (three_d.x_length, three_d.y_length, three_d.z_length) == pytest.approx(
+ (10.5, 10.5, 6.5)
+ )
+
+
+def test_an_axis_given_a_unit_size_and_no_length_is_that_size_per_unit() -> None:
+ axes = m.Axes(x_range=[0, 10, 1], x_axis_config={"unit_size": 0.5})
+ assert axes.x_length == pytest.approx(5)
+ assert axes.y_length == pytest.approx(6) # the other axis fits the frame
+ # a length given wins
+ axes = m.Axes(x_length=7, x_axis_config={"unit_size": 0.5})
+ assert axes.x_length == pytest.approx(7)
+ # and a plane's unit is a scene unit unless one is given
+ plane = m.NumberPlane(x_range=[-2, 2, 1], axis_config={"unit_size": 2})
+ assert plane.x_length == pytest.approx(8)
+
+
+def test_a_planes_faded_lines_halve_each_of_several_opacities() -> None:
+ # an opacity can be one for each part of a stroke: each is halved
+ plane = m.NumberPlane(
+ faded_line_ratio=2, background_line_style={"stroke_opacity": [1.0, 0.5]}
+ )
+ full = plane.background_lines[0].get_stroke_opacity()
+ assert len(plane.faded_lines) > 0
+ for line in plane.faded_lines:
+ assert line.get_stroke_opacity() == pytest.approx(full * 0.5)
+
+
@pytest.mark.parametrize("plane_type", [m.NumberPlane, m.ComplexPlane, m.PolarPlane])
def test_plane_faded_lines_use_half_the_background_width_and_opacity(
plane_type: type[m.NumberPlane] | type[m.PolarPlane],