A community-maintained Python framework for creating mathematical animations.
New feature: Tree layout for Graph mobject (#922)
Noam Zaks852521841e86
diff --git a/docs/source/installation/mac.rst b/docs/source/installation/mac.rstindex 25064a4c1..871793882 100644--- a/docs/source/installation/mac.rst+++ b/docs/source/installation/mac.rst@@ -25,7 +25,7 @@ To install LaTeX:.. code-block:: bash- brew cask install mactex+ brew install --cask mactex.. warning:: Note that MacTeX will require at least 4.5GB of hard disk space.This is due to the fact that it installs every LaTeX addon package@@ -40,7 +40,7 @@ To install LaTeX:.. code-block:: bash- brew cask install basictex+ brew install --cask basictexEnsure that the TeXLiveManager tool ``tlmgr`` works, by running ``tlmgr--version`` in the terminal. Now rundiff --git a/manim/mobject/graph.py b/manim/mobject/graph.pyindex 69261f316..a1914e160 100644--- a/manim/mobject/graph.py+++ b/manim/mobject/graph.py@@ -4,7 +4,6 @@ __all__ = ["Graph",]-from ..constants import UPfrom ..utils.color import BLACKfrom .types.vectorized_mobject import VMobjectfrom .geometry import Dot, Line, LabeledDot@@ -17,6 +16,66 @@ import networkx as nximport numpy as np+def _tree_layout(+ G: nx.classes.graph.Graph,+ root_vertex: Union[Hashable, None],+ scale: float,+) -> dict:+ result = {root_vertex: np.array([0, 0, 0])}++ if not nx.is_tree(G):+ raise ValueError("The tree layout must be used with trees")+ if root_vertex is None:+ raise ValueError("The tree layout requires the root_vertex parameter")++ def _recursive_position_for_row(+ G: nx.classes.graph.Graph,+ result: dict,+ two_rows_before: List[Hashable],+ last_row: List[Hashable],+ current_height: float,+ ):+ new_row = []+ for v in last_row:+ for x in G.neighbors(v):+ if x not in two_rows_before:+ new_row.append(x)++ new_row_length = len(new_row)++ if new_row_length == 0:+ return++ if new_row_length == 1:+ result[new_row[0]] = np.array([0, current_height, 0])+ else:+ for i in range(new_row_length):+ result[new_row[i]] = np.array(+ [-1 + 2 * i / (new_row_length - 1), current_height, 0]+ )++ _recursive_position_for_row(+ G,+ result,+ two_rows_before=last_row,+ last_row=new_row,+ current_height=current_height + 1,+ )++ _recursive_position_for_row(+ G, result, two_rows_before=[], last_row=[root_vertex], current_height=1+ )++ height = max(map(lambda v: result[v][1], result))++ return dict(+ [+ (v, np.array([pos[0], 1 - 2 * pos[1] / height, pos[2]]) * scale / 2)+ for v, pos in result.items()+ ]+ )++class Graph(VMobject):"""An undirected graph (that is, a collection of vertices connected with edges).@@ -49,7 +108,7 @@ class Graph(VMobject):is set to ``True``. Has no effect for other values of ``labels``.layoutEither one of ``"spring"`` (the default), ``"circular"``, ``"kamada_kawai"``,- ``"planar"``, ``"random"``, ``"shell"``, ``"spectral"``, ``"spiral"``, and ``"partite"``+ ``"planar"``, ``"random"``, ``"shell"``, ``"spectral"``, ``"spiral"``, ``"tree"``, and ``"partite"``for automatic vertex positioning using ``networkx``(see `their documentation <https://networkx.org/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_for more details), or a dictionary specifying a coordinate (value)@@ -179,6 +238,32 @@ class Graph(VMobject):graph = Graph(list(G.nodes), list(G.edges), layout="partite", partitions=[[0, 1]])self.play(ShowCreation(graph))+ The custom tree layout can be used to show the graph+ by distance from the root vertex. You must pass the root vertex+ of the tree.++ .. manim:: Tree++ from manim import *+ import networkx as nx++ class Tree(Scene):+ def construct(self):+ G = nx.Graph()++ G.add_node("ROOT")++ for i in range(5):+ G.add_node("Child_%i" % i)+ G.add_node("Grandchild_%i" % i)+ G.add_node("Greatgrandchild_%i" % i)++ G.add_edge("ROOT", "Child_%i" % i)+ G.add_edge("Child_%i" % i, "Grandchild_%i" % i)+ G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)++ self.play(ShowCreation(+ Graph(list(G.nodes), list(G.edges), layout="tree", root_vertex="ROOT")))"""def __init__(@@ -194,6 +279,7 @@ class Graph(VMobject):vertex_config: Union[dict, None] = None,edge_type: "Mobject" = Line,partitions: Union[List[List[Hashable]], None] = None,+ root_vertex: Union[Hashable, None] = None,edge_config: Union[dict, None] = None,) -> None:VMobject.__init__(self)@@ -211,34 +297,50 @@ class Graph(VMobject):"shell": nx.layout.shell_layout,"spectral": nx.layout.spectral_layout,"partite": nx.layout.multipartite_layout,+ "tree": _tree_layout,"spiral": nx.layout.spiral_layout,"spring": nx.layout.spring_layout,}+ custom_layouts = ["random", "partite", "tree"]+if layout_config is None:layout_config = {}if isinstance(layout, dict):self._layout = layout- elif layout in automatic_layouts and layout != "random":- if layout == "partite":- if partitions is None or len(partitions) == 0:- raise ValueError(- "The partite layout requires the '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- # Add missing vertices to their own side- for v in nx_graph.nodes:- if "subset" not in nx_graph.nodes[v]:- nx_graph.nodes[v]["subset"] = partition_count+ elif layout in automatic_layouts and layout not in custom_layouts:+ self._layout = automatic_layouts[layout](+ nx_graph, scale=layout_scale, **layout_config+ )+ self._layout = dict(+ [(k, np.append(v, [0])) for k, v in self._layout.items()]+ )+ elif layout == "tree":self._layout = automatic_layouts[layout](+ nx_graph,+ root_vertex=root_vertex,+ scale=layout_scale,+ )+ elif layout == "partite":+ if partitions is None or len(partitions) == 0:+ raise ValueError(+ "The partite layout requires the '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+ # Add missing vertices to their own side+ for v in nx_graph.nodes:+ if "subset" not in nx_graph.nodes[v]:+ nx_graph.nodes[v]["subset"] = partition_count++ self._layout = automatic_layouts["partite"](nx_graph, scale=layout_scale, **layout_config)self._layout = dict(