Skip to content

Commit f3e1e04

Browse files
authored
Merge pull request #38 from petercorke/refactor/detach-hook
refactor: vertex kinds supply _detach, the twin of _attach; removed vertices leave the graph
2 parents 36fdbc8 + 74a87c7 commit f3e1e04

2 files changed

Lines changed: 185 additions & 13 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -612,12 +612,9 @@ def remove_edge(self, edge: Edge) -> None:
612612
613613
.. warning:: The connectivity of the network may be changed.
614614
615-
.. note:: A directed edge is tracked only by its source vertex's
616-
edge list, not its target's (see :attr:`BaseVertex.edges`), so
617-
membership is checked per endpoint rather than assumed for both
618-
-- removing a directed edge from an undirected-only
619-
implementation would otherwise raise ``ValueError`` on the
620-
target side.
615+
.. note:: An undirected edge is held by both of its vertices and a
616+
directed edge only by its source (see :meth:`BaseVertex.edges`).
617+
Each vertex kind knows which, so this method does not.
621618
622619
.. runblock:: pycon
623620
@@ -633,15 +630,16 @@ def remove_edge(self, edge: Edge) -> None:
633630
"""
634631
if edge not in self._edgelist:
635632
raise ValueError("edge does not belong to this graph")
636-
assert edge.v1 is not None and edge.v2 is not None
633+
v1, v2 = edge.v1, edge.v2
634+
if v1 is None or v2 is None:
635+
raise ValueError("edge does not connect two vertices")
637636

638-
if edge in edge.v1._edgelist:
639-
edge.v1._edgelist.remove(edge)
640-
if edge in edge.v2._edgelist:
641-
edge.v2._edgelist.remove(edge)
637+
# how the edge is held differs between undirected and directed
638+
# vertices, so the vertex kind undoes what its _attach did
639+
v1._detach(edge, v2)
642640

643-
edge.v1._connectivitychange = True
644-
edge.v2._connectivitychange = True
641+
v1._connectivitychange = True
642+
v2._connectivitychange = True
645643
self._connectivitychange = True
646644

647645
edge.v1 = None
@@ -688,6 +686,8 @@ def remove_vertex(self, vertex: BaseVertex) -> None:
688686

689687
self._vertexlist.remove(vertex)
690688
del self._vertexdict[vertex.name]
689+
vertex._graph = None # it is not in any graph now
690+
self._connectivitychange = True
691691

692692
def remove(self, x: Edge | BaseVertex) -> None:
693693
"""
@@ -3236,6 +3236,25 @@ def _attach(self, edge: Edge, dest: BaseVertex) -> None:
32363236
"subclass UVertex or DVertex"
32373237
)
32383238

3239+
def _detach(self, edge: Edge, dest: BaseVertex) -> None:
3240+
"""
3241+
Remove an edge from the vertices' edge lists (private method)
3242+
3243+
:param edge: the edge being removed, with ``edge.v1`` and ``edge.v2``
3244+
still set
3245+
:param dest: the vertex at the other end, ``edge.v2``
3246+
:raises NotImplementedError: not provided by this vertex kind
3247+
3248+
The twin of :meth:`_attach`: it undoes exactly what that recorded.
3249+
Called by :meth:`_BaseGraph.remove_edge` before the edge's endpoints
3250+
are cleared. An edge that is absent from a list is skipped rather
3251+
than treated as an error.
3252+
"""
3253+
raise NotImplementedError(
3254+
f"{type(self).__name__} does not define how an edge is detached; "
3255+
"subclass UVertex or DVertex"
3256+
)
3257+
32393258
def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool:
32403259
"""
32413260
Test if an edge already connects this vertex to ``dest`` (private method)
@@ -3571,6 +3590,17 @@ def _attach(self, edge: Edge, dest: BaseVertex) -> None:
35713590
self._edgelist.append(edge)
35723591
dest._edgelist.append(edge)
35733592

3593+
def _detach(self, edge: Edge, dest: BaseVertex) -> None:
3594+
"""
3595+
Remove an undirected edge from both ends (private method)
3596+
3597+
A self-loop was recorded twice by :meth:`_attach`, so it is removed
3598+
twice.
3599+
"""
3600+
for vertex in (self, dest):
3601+
if edge in vertex._edgelist:
3602+
vertex._edgelist.remove(edge)
3603+
35743604
def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool:
35753605
"""
35763606
Test if an edge already connects this vertex and ``dest`` (private method)
@@ -3616,6 +3646,15 @@ def _attach(self, edge: Edge, dest: BaseVertex) -> None:
36163646
"""
36173647
self._edgelist.append(edge)
36183648

3649+
def _detach(self, edge: Edge, dest: BaseVertex) -> None:
3650+
"""
3651+
Remove a directed edge from its source (private method)
3652+
3653+
``dest`` never held it.
3654+
"""
3655+
if edge in self._edgelist:
3656+
self._edgelist.remove(edge)
3657+
36193658

36203659
# UGraph/DGraph declare their _vertex_cls here, rather than in their own
36213660
# class body, because UVertex/DVertex are defined later in this file --

‎tests/test_detach_hook.py‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
"""
2+
``_attach`` records an edge in the vertices' edge lists when it is connected;
3+
``_detach`` is its twin, undoing exactly that when the edge is removed, so each
4+
vertex kind states how an edge enters and leaves its lists once, and
5+
``remove_edge`` / ``remove_vertex`` need no knowledge of which kind they hold.
6+
"""
7+
8+
import unittest
9+
10+
from pgraph import DGraph, DVertex, Edge, UGraph, UVertex
11+
from pgraph.PGraph import BaseVertex
12+
13+
14+
class TestHookIsDefinedPerKind(unittest.TestCase):
15+
def test_kinds_supply_it(self):
16+
self.assertIsNot(UVertex._detach, BaseVertex._detach)
17+
self.assertIsNot(DVertex._detach, BaseVertex._detach)
18+
self.assertIsNot(UVertex._detach, DVertex._detach)
19+
20+
def test_base_hook_is_not_implemented(self):
21+
a, b = BaseVertex(name="a"), BaseVertex(name="b")
22+
with self.assertRaises(NotImplementedError):
23+
a._detach(Edge(a, b), b)
24+
25+
26+
class _Detach:
27+
Graph: type
28+
Vertex: type
29+
30+
def setUp(self):
31+
self.calls = []
32+
outer = self
33+
34+
class Recording(self.Vertex):
35+
def _detach(self, edge, dest):
36+
# at this point the edge still knows its endpoints
37+
outer.calls.append((self, edge, dest, edge.v1, edge.v2))
38+
super()._detach(edge, dest)
39+
40+
self.g = self.Graph(vertex_class=Recording)
41+
self.a = self.g.add_vertex([0, 0], name="a")
42+
self.b = self.g.add_vertex([1, 0], name="b")
43+
self.c = self.g.add_vertex([2, 0], name="c")
44+
45+
def consistent(self):
46+
"""every edge held by a vertex is in the graph, and vice versa"""
47+
held = {id(e) for v in self.g for e in v.edges()}
48+
return held <= {id(e) for e in self.g.edges()} and all(
49+
e.v1 is not None and e.v2 is not None for e in self.g.edges()
50+
)
51+
52+
def test_remove_edge_calls_the_hook_once(self):
53+
e = self.a.connect(self.b)
54+
self.g.remove_edge(e)
55+
self.assertEqual(len(self.calls), 1)
56+
v, edge, dest, v1, v2 = self.calls[0]
57+
self.assertIs(v, self.a)
58+
self.assertIs(edge, e)
59+
self.assertIs(dest, self.b)
60+
self.assertEqual((v1, v2), (self.a, self.b))
61+
self.assertEqual(self.g.ne, 0)
62+
self.assertIsNone(e.v1)
63+
64+
def test_refused_removal_detaches_nothing(self):
65+
other = self.Graph()
66+
x, y = other.add_vertex(name="x"), other.add_vertex(name="y")
67+
e = x.connect(y)
68+
with self.assertRaises(ValueError):
69+
self.g.remove_edge(e)
70+
self.assertEqual(self.calls, [])
71+
72+
def test_removing_one_of_parallel_edges(self):
73+
e1 = self.a.connect(self.b, cost=1)
74+
e2 = self.a.connect(self.b, cost=2)
75+
self.g.remove_edge(e1)
76+
self.assertEqual(self.a.edges(), [e2])
77+
self.assertTrue(self.consistent())
78+
79+
def test_remove_vertex_removes_its_edges_through_the_hook(self):
80+
self.a.connect(self.b)
81+
self.b.connect(self.c)
82+
self.c.connect(self.a)
83+
self.g.remove_vertex(self.b)
84+
self.assertEqual(self.g.n, 2)
85+
self.assertEqual(self.g.ne, 1) # c-a survives
86+
self.assertTrue(self.consistent())
87+
self.assertEqual(len(self.calls), 2) # a-b and b-c
88+
89+
def test_removed_vertex_no_longer_points_at_the_graph(self):
90+
self.a.connect(self.b)
91+
self.g.remove_vertex(self.a)
92+
self.assertIsNone(self.a._graph)
93+
self.assertEqual(self.a.edges(), [])
94+
with self.assertRaises(ValueError):
95+
self.a.remove() # not in a graph any more, a clear error
96+
# and it can join another graph
97+
self.Graph(vertex_class=type(self.a)).add_vertex(self.a)
98+
self.assertEqual(self.g.n, 2)
99+
100+
101+
class TestUndirectedDetach(_Detach, unittest.TestCase):
102+
Graph, Vertex = UGraph, UVertex
103+
104+
def test_both_ends_are_cleared(self):
105+
e = self.a.connect(self.b)
106+
self.g.remove_edge(e)
107+
self.assertEqual((self.a.edges(), self.b.edges()), ([], []))
108+
109+
def test_self_loop_is_cleared_from_both_entries(self):
110+
e = self.a.connect(self.a)
111+
self.assertEqual(self.a.edges(), [e, e])
112+
self.g.remove_edge(e)
113+
self.assertEqual(self.a.edges(), [])
114+
115+
116+
class TestDirectedDetach(_Detach, unittest.TestCase):
117+
Graph, Vertex = DGraph, DVertex
118+
119+
def test_only_the_source_held_it(self):
120+
e = self.a.connect(self.b)
121+
self.g.remove_edge(e)
122+
self.assertEqual((self.a.edges(), self.b.edges()), ([], []))
123+
124+
def test_removing_a_vertex_removes_edges_that_point_at_it(self):
125+
self.a.connect(self.b) # a -> b, held by a only
126+
self.g.remove_vertex(self.b)
127+
self.assertEqual(self.a.edges(), [])
128+
self.assertEqual(self.g.ne, 0)
129+
self.assertTrue(self.consistent())
130+
131+
132+
if __name__ == "__main__":
133+
unittest.main()

0 commit comments

Comments
 (0)