A community-maintained Python framework for creating mathematical animations.
Replaced current tree layout algorithm with SageMath's for improved layout of large trees. (#2343)
Benjamin Hacklf40ba6a9cecc
diff --git a/manim/mobject/graph.py b/manim/mobject/graph.pyindex 2ff065e0d..52c495330 100644--- a/manim/mobject/graph.py+++ b/manim/mobject/graph.py@@ -98,65 +98,94 @@ def _determine_graph_layout(def _tree_layout(- G: nx.classes.graph.Graph,+ T: nx.classes.graph.Graph,root_vertex: Union[Hashable, None],- scale: float,-) -> dict:- result = {root_vertex: np.array([0, 0, 0])}+ scale: Union[float, tuple] = 2,+ orientation: str = "down",+):+ children = {root_vertex: list(T.neighbors(root_vertex))}- if not nx.is_tree(G):+ if not nx.is_tree(T):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))+ # The following code is SageMath's tree layout implementation, taken from+ # https://github.com/sagemath/sage/blob/cc60cfebc4576fed8b01f0fc487271bdee3cefed/src/sage/graphs/graph_plot.py#L1447++ # Always make a copy of the children because they get eaten+ stack = [[u for u in children[root_vertex]]]+ stick = [root_vertex]+ parent = {u: root_vertex for u in children[root_vertex]}+ pos = {}+ obstruction = [0.0] * len(T)+ if orientation == "down":+ o = -1+ else:+ o = 1- return {- v: np.array([pos[0], 1 - 2 * pos[1] / height, pos[2]]) * scale / 2- for v, pos in result.items()- }+ def slide(v, dx):+ """+ Shift the vertex v and its descendants to the right by dx.+ Precondition: v and its descendents have already had their+ positions computed.+ """+ 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)++ # the resulting layout is then rescaled again to fit on Manim's canvas++ 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 isinstance(scale, (float, int)):+ sf = 2 * scale / max(width, height)+ else:+ sf = np.array([2 * scale[0] / width, 2 * scale[1] / height, 0])+ return {v: (np.array([x, y, 0]) - center) * sf for v, (x, y) in pos.items()}class Graph(VMobject, metaclass=ConvertToOpenGL):@@ -199,7 +228,9 @@ class Graph(VMobject, metaclass=ConvertToOpenGL):layout_scaleThe scale of automatically generated layouts: the vertices willbe arranged such that the coordinates are located within the- interval ``[-scale, scale]``. Default: 2.+ interval ``[-scale, scale]``. Some layouts accept a tuple ``(scale_x, scale_y)``+ causing the first coordinate to be in the interval ``[-scale_x, scale_x]``,+ and the second in ``[-scale_y, scale_y]``. Default: 2.layout_configOnly for automatically generated layouts. A dictionary whose entriesare passed as keyword arguments to the automatic layout algorithm@@ -359,7 +390,7 @@ class Graph(VMobject, metaclass=ConvertToOpenGL):labels: Union[bool, dict] = False,label_fill_color: str = BLACK,layout: Union[str, dict] = "spring",- layout_scale: float = 2,+ layout_scale: Union[float, tuple] = 2,layout_config: Union[dict, None] = None,vertex_type: Type["Mobject"] = Dot,vertex_config: Union[dict, None] = None,