Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions manim/mobject/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,8 @@ def _populate_edge_dict(
raise NotImplementedError("To be implemented in concrete subclasses")

def __getitem__(self: Graph, v: Hashable) -> Mobject:
if isinstance(v, tuple) and len(v) == 2:
return self.edges[v]
return self.vertices[v]
Comment on lines 672 to 675
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing I mentioned in issue #3798 is that vertices can be any hashable object. This includes tuples: vertices can be tuples themselves. This is not too strange, actually. For example, vertices could represent 2D coordinates. There's also this concept of a "line graph L of a graph G" where each vertex of L is an edge of G: if there is an edge connecting vertices 1 and 3 of G, then L has a vertex (1, 3), and so on. networkx actually implements this.

It is possible that the graph contains two vertices, say, (1, 2) and (1, 3), and an edge connecting both: ((1, 2), (1, 3)). Thus, verifying that v is a tuple containing two elements is not enough to determine whether it represents an edge or a vertex.

One way I would solve this is by directly asking whether v is contained in the vertices or the edges before attempting to retrieve the Mobject:

if v in self.vertices:
    return self.vertices[v]
if v in self.edges:
    return self.edges[v]
raise IndexError(f"Vertex or edge {v} not found")
# or some more elaborated message, like
# "Couldn't find vertex {v} or edge connecting vertices {v[0]} and {v[1]}"
# when v is a tuple of 2 elements


def _create_vertex(
Expand Down
13 changes: 13 additions & 0 deletions tests/module/mobject/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,19 @@ def test_graph_add_edges():
assert set(G._graph.edges()) == set(G.edges.keys())


def test_graph_getitem():
vertices = [1, 2, 3, 4]
edges = [(1, 2), (2, 3), (3, 4), (4, 1)]
G = Graph(vertices, edges)
# Vertex access
assert G[1] is G.vertices[1]
# Edge access via tuple key
assert G[(1, 2)] is G.edges[(1, 2)]
# DiGraph edge access
DG = DiGraph(vertices, edges)
assert DG[(1, 2)] is DG.edges[(1, 2)]


def test_graph_remove_edges():
G = Graph([1, 2, 3, 4, 5], [(1, 2), (2, 3), (3, 4), (4, 5), (1, 5)])
removed_mobjects = G.remove_edges((1, 2))
Expand Down
Loading