Skip to content

Commit f34c61e

Browse files
authored
Merge pull request #35 from petercorke/refactor/vertex-connect-hook
refactor: connect() defined once, vertex kinds supply an _attach hook
2 parents d22408d + 66aff65 commit f34c61e

2 files changed

Lines changed: 219 additions & 107 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 69 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -3176,11 +3176,14 @@ def connect(
31763176
31773177
.. note::
31783178
3179-
- If the vertices subclass ``UVertex`` the edge is undirected, and if
3180-
they subclass ``DVertex`` the edge is directed.
3179+
- If the vertices subclass ``UVertex`` the edge is undirected: it is
3180+
recorded in the edge list of *both* vertices, so it is found from
3181+
either end. If they subclass ``DVertex`` the edge is directed: it
3182+
is recorded only in the edge list of this, the source, vertex.
31813183
- A supplied ``edge`` built without vertices has its ``v1`` and
31823184
``v2`` set to the vertices being connected. One built with
3183-
vertices must agree with them (in either order if undirected).
3185+
vertices must agree with them: in either order if undirected,
3186+
exactly ``self`` then ``dest`` if directed.
31843187
- Both vertices must already have been added to the same graph,
31853188
e.g. via :meth:`PGraph.add_vertex` -- since a graph only ever
31863189
accepts its own vertex subclass (see :meth:`UGraph.add_vertex`,
@@ -3220,8 +3223,32 @@ def connect(
32203223
self._graph._connectivitychange = True
32213224
self._connectivitychange = True
32223225

3226+
# the one thing that differs between undirected and directed vertices
3227+
self._attach(e, dest)
3228+
32233229
return e
32243230

3231+
def _attach(self, edge: Edge, dest: BaseVertex) -> None:
3232+
"""
3233+
Record a new edge in the vertices' edge lists (private method)
3234+
3235+
:param edge: the edge just created or supplied by :meth:`connect`, with
3236+
``edge.v1`` and ``edge.v2`` set and already part of the graph
3237+
:param dest: the vertex ``connect`` was called with
3238+
:raises NotImplementedError: not provided by this vertex kind
3239+
3240+
This is the hook that :meth:`connect` calls once the connection has
3241+
been validated and the edge registered with the graph, so it is never
3242+
called for a connection that is refused. :class:`UVertex` records the
3243+
edge at both ends and :class:`DVertex` at the source only. A vertex
3244+
kind of your own supplies this, not :meth:`connect`, which is defined
3245+
once.
3246+
"""
3247+
raise NotImplementedError(
3248+
f"{type(self).__name__} does not define how an edge is attached; "
3249+
"subclass UVertex or DVertex"
3250+
)
3251+
32253252
def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool:
32263253
"""
32273254
Test if an edge already connects this vertex to ``dest`` (private method)
@@ -3527,68 +3554,35 @@ class UVertex(BaseVertex):
35273554
35283555
This class can be inherited to provide user objects with graph capability.
35293556
3557+
:meth:`~BaseVertex.connect` adds the new edge to *both* vertices' edge
3558+
lists, so it is discovered from either end, and accepts a supplied edge
3559+
whose endpoints are the two vertices in either order.
3560+
3561+
.. runblock:: pycon
3562+
3563+
>>> from pgraph import UGraph
3564+
>>> g = UGraph()
3565+
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
3566+
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
3567+
>>> v1.connect(v2, cost=1.414)
3568+
>>> print(v1.edges())
3569+
>>> print(v2.edges())
35303570
35313571
.. inheritance-diagram:: UVertex
35323572
35333573
:seealso: :class:`BaseVertex` :class:`DVertex`
35343574
"""
35353575

3536-
def connect(
3537-
self,
3538-
dest: BaseVertex,
3539-
edge: Edge | None = None,
3540-
cost: float | None = None,
3541-
data: Any = None,
3542-
) -> Edge:
3576+
def _attach(self, edge: Edge, dest: BaseVertex) -> None:
35433577
"""
3544-
Connect this vertex to another with an undirected edge
3545-
3546-
:param dest: vertex to connect to
3547-
:type dest: BaseVertex subclass
3548-
:param edge: Use this as the edge object, otherwise a new object of the
3549-
graph's :attr:`_BaseGraph.edge_class` is created,
3550-
defaults to None
3551-
:type edge: ``Edge`` subclass, optional
3552-
:param cost: the cost to traverse this edge, defaults to None
3553-
:type cost: float, optional
3554-
:param data: reference to arbitrary data associated with the edge,
3555-
defaults to None
3556-
:type data: Any, optional
3557-
:raises ValueError: either vertex has not been added to a graph, the
3558-
vertices belong to different graphs, or ``edge`` already connects
3559-
other vertices
3560-
:raises TypeError: ``edge`` is not an instance of the graph's
3561-
:attr:`_BaseGraph.edge_class`
3562-
:return: the edge connecting the vertices
3563-
:rtype: Edge
3564-
3565-
Unlike the directed-graph counterpart, the new edge is added to
3566-
*both* vertices' edge lists, so it is discovered from either end.
3567-
3568-
If ``edge`` was built without vertices its ``v1`` and ``v2`` are set
3569-
to ``self`` and ``dest``. If it was built with vertices they must be
3570-
these two, in either order since an undirected edge has no direction.
3571-
3572-
.. runblock:: pycon
3573-
3574-
>>> from pgraph import UVertex, Edge, UGraph
3575-
>>> g = UGraph()
3576-
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
3577-
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
3578-
>>> v1.connect(v2, cost=1.414)
3579-
>>> print(v1.edges())
3580-
>>> print(g.edges())
3581-
>>> print(g)
3578+
Record an undirected edge at both ends (private method)
35823579
3583-
:seealso: :meth:`BaseVertex.connect` :meth:`DVertex.connect`
3580+
The edge is added to *both* vertices' edge lists, so it is discovered
3581+
from either end. A self-loop is therefore held twice by its vertex,
3582+
which is why it counts 2 towards the degree.
35843583
"""
3585-
3586-
e = super().connect(dest, edge=edge, cost=cost, data=data)
3587-
3588-
self._edgelist.append(e)
3589-
dest._edgelist.append(e)
3590-
3591-
return e
3584+
self._edgelist.append(edge)
3585+
dest._edgelist.append(edge)
35923586

35933587
def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool:
35943588
"""
@@ -3607,65 +3601,33 @@ class DVertex(BaseVertex):
36073601
36083602
This class can be inherited to provide user objects with graph capability.
36093603
3604+
:meth:`~BaseVertex.connect` adds the new edge only to *this* vertex's edge
3605+
list, so it is discoverable only from the start of the directed edge, and a
3606+
supplied edge must run exactly from this vertex to the other.
3607+
3608+
.. runblock:: pycon
3609+
3610+
>>> from pgraph import DGraph
3611+
>>> g = DGraph()
3612+
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
3613+
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
3614+
>>> v1.connect(v2, cost=1.414)
3615+
>>> print(v1.edges())
3616+
>>> print(v2.edges())
3617+
36103618
.. inheritance-diagram:: DVertex
36113619
36123620
:seealso: :class:`BaseVertex` :class:`UVertex`
36133621
"""
36143622

3615-
def connect(
3616-
self,
3617-
dest: BaseVertex,
3618-
edge: Edge | None = None,
3619-
cost: float | None = None,
3620-
data: Any = None,
3621-
) -> Edge:
3623+
def _attach(self, edge: Edge, dest: BaseVertex) -> None:
36223624
"""
3623-
Connect this vertex to another with a directed edge
3625+
Record a directed edge at its source only (private method)
36243626
3625-
:param dest: vertex to connect to
3626-
:type dest: BaseVertex subclass
3627-
:param edge: Use this as the edge object, otherwise a new object of the
3628-
graph's :attr:`_BaseGraph.edge_class` is created,
3629-
defaults to None
3630-
:type edge: ``Edge`` subclass, optional
3631-
:param cost: the cost to traverse this edge, defaults to None
3632-
:type cost: float, optional
3633-
:param data: reference to arbitrary data associated with the edge,
3634-
defaults to None
3635-
:type data: Any, optional
3636-
:raises ValueError: either vertex has not been added to a graph, the
3637-
vertices belong to different graphs, or ``edge`` already connects
3638-
other vertices
3639-
:raises TypeError: ``edge`` is not an instance of the graph's
3640-
:attr:`_BaseGraph.edge_class`
3641-
:return: the edge connecting the vertices
3642-
:rtype: Edge
3643-
3644-
Unlike the undirected-graph counterpart, the new edge is added only
3645-
to *this* vertex's edge list -- it is only discoverable from the
3646-
start of the directed edge.
3647-
3648-
If ``edge`` was built without vertices its ``v1`` and ``v2`` are set
3649-
to ``self`` and ``dest``. If it was built with vertices they must be
3650-
exactly these two, in this order, since the edge has a direction.
3651-
3652-
.. runblock:: pycon
3653-
3654-
>>> from pgraph import DVertex, Edge, DGraph
3655-
>>> g = DGraph()
3656-
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
3657-
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
3658-
>>> v1.connect(v2, cost=1.414)
3659-
>>> print(v1.edges())
3660-
>>> print(g.edges())
3661-
>>> print(g)
3662-
3663-
:seealso: :meth:`BaseVertex.connect` :meth:`UVertex.connect`
3627+
The edge is added only to *this* vertex's edge list, so it is
3628+
discoverable only from the start of the directed edge.
36643629
"""
3665-
e = super().connect(dest, edge=edge, cost=cost, data=data)
3666-
3667-
self._edgelist.append(e)
3668-
return e
3630+
self._edgelist.append(edge)
36693631

36703632

36713633
# UGraph/DGraph declare their _vertex_cls here, rather than in their own

‎tests/test_vertex_hook.py‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
"""
2+
``BaseVertex.connect()`` is the one public method; what differs between an
3+
undirected and a directed vertex is a single bookkeeping hook, ``_attach``,
4+
that ``connect()`` calls once the connection has been validated and the edge
5+
registered with the graph.
6+
7+
This pins the design: ``connect`` is defined once, the hook is what a vertex
8+
kind supplies, and nothing is attached when validation fails.
9+
"""
10+
11+
import unittest
12+
13+
from pgraph import DGraph, Edge, UGraph, DVertex, UVertex
14+
from pgraph.PGraph import BaseVertex
15+
16+
17+
class TestConnectIsDefinedOnce(unittest.TestCase):
18+
def test_subclasses_inherit_connect(self):
19+
self.assertIs(UVertex.connect, BaseVertex.connect)
20+
self.assertIs(DVertex.connect, BaseVertex.connect)
21+
22+
def test_subclasses_supply_the_hook(self):
23+
self.assertIsNot(UVertex._attach, BaseVertex._attach)
24+
self.assertIsNot(DVertex._attach, BaseVertex._attach)
25+
self.assertIsNot(UVertex._attach, DVertex._attach)
26+
27+
def test_base_hook_is_not_implemented(self):
28+
a, b = BaseVertex(name="a"), BaseVertex(name="b")
29+
with self.assertRaises(NotImplementedError):
30+
a._attach(Edge(a, b), b)
31+
32+
33+
class TestBareBaseVertex(unittest.TestCase):
34+
"""BaseVertex stays constructible (see policy.rst) but can never join a graph"""
35+
36+
def test_instantiable(self):
37+
v = BaseVertex([1, 2], name="v")
38+
self.assertEqual(v.name, "v")
39+
40+
def test_cannot_connect_or_be_added(self):
41+
a, b = BaseVertex(name="a"), BaseVertex(name="b")
42+
with self.assertRaises(ValueError):
43+
a.connect(b)
44+
with self.assertRaises(TypeError):
45+
UGraph().add_vertex(a)
46+
with self.assertRaises(TypeError):
47+
DGraph().add_vertex(a)
48+
49+
50+
class _Hook:
51+
Graph: type
52+
Vertex: type
53+
54+
def setUp(self):
55+
self.calls = []
56+
outer = self
57+
58+
class Recording(self.Vertex):
59+
def _attach(self, edge, dest):
60+
# the edge is already registered with the graph at this point
61+
outer.calls.append(
62+
(self, edge, dest, edge in self._graph._edgelist)
63+
)
64+
super()._attach(edge, dest)
65+
66+
self.g = self.Graph(vertex_class=Recording)
67+
self.a = self.g.add_vertex([0, 0], name="a")
68+
self.b = self.g.add_vertex([1, 0], name="b")
69+
70+
def test_attach_called_once_with_the_edge(self):
71+
e = self.a.connect(self.b, cost=3)
72+
self.assertEqual(len(self.calls), 1)
73+
v, edge, dest, registered = self.calls[0]
74+
self.assertIs(v, self.a)
75+
self.assertIs(edge, e)
76+
self.assertIs(dest, self.b)
77+
self.assertTrue(registered)
78+
79+
def test_returns_the_edge(self):
80+
e = self.a.connect(self.b, cost=3)
81+
self.assertIsInstance(e, Edge)
82+
self.assertEqual(e.cost, 3)
83+
self.assertIn(e, self.g.edges())
84+
85+
def test_nothing_attached_when_validation_fails(self):
86+
other = self.Graph().add_vertex([5, 5], name="x")
87+
with self.assertRaises(ValueError):
88+
self.a.connect(other) # different graph
89+
with self.assertRaises(ValueError):
90+
self.a.connect(self.b, edge=Edge(self.b, self.b)) # wrong endpoints
91+
ungraphed = self.Vertex([9, 9])
92+
with self.assertRaises(ValueError):
93+
self.a.connect(ungraphed)
94+
self.assertEqual(self.calls, [])
95+
self.assertEqual(self.g.ne, 0)
96+
self.assertEqual((self.a.edges(), self.b.edges()), ([], []))
97+
98+
def test_add_edge_and_edge_connect_go_through_the_hook(self):
99+
self.g.add_edge(self.a, self.b)
100+
Edge(cost=1).connect(self.a, self.b)
101+
self.assertEqual(len(self.calls), 2)
102+
103+
104+
class TestUndirectedHook(_Hook, unittest.TestCase):
105+
Graph, Vertex = UGraph, UVertex
106+
107+
def test_edge_is_held_by_both_ends(self):
108+
e = self.a.connect(self.b)
109+
self.assertEqual(self.a.edges(), [e])
110+
self.assertEqual(self.b.edges(), [e])
111+
112+
def test_self_loop_is_held_twice_by_its_vertex(self):
113+
e = self.a.connect(self.a)
114+
self.assertEqual(self.a.edges(), [e, e])
115+
self.assertEqual(self.a.degree, 2)
116+
117+
118+
class TestDirectedHook(_Hook, unittest.TestCase):
119+
Graph, Vertex = DGraph, DVertex
120+
121+
def test_edge_is_held_by_the_source_only(self):
122+
e = self.a.connect(self.b)
123+
self.assertEqual(self.a.edges(), [e])
124+
self.assertEqual(self.b.edges(), [])
125+
126+
def test_self_loop_is_held_once(self):
127+
e = self.a.connect(self.a)
128+
self.assertEqual(self.a.edges(), [e])
129+
self.assertEqual(self.a.degree, 1)
130+
131+
132+
class TestHookIsTheExtensionPoint(unittest.TestCase):
133+
def test_custom_bookkeeping(self):
134+
# a user kind that records the edge on the source only, though it is
135+
# built on the undirected vertex: only the hook has to change
136+
class OneSided(UVertex):
137+
def _attach(self, edge, dest):
138+
self._edgelist.append(edge)
139+
140+
g = UGraph(vertex_class=OneSided)
141+
a = g.add_vertex([0, 0], name="a")
142+
b = g.add_vertex([1, 0], name="b")
143+
e = a.connect(b)
144+
self.assertEqual(a.edges(), [e])
145+
self.assertEqual(b.edges(), [])
146+
self.assertEqual(g.ne, 1)
147+
148+
149+
if __name__ == "__main__":
150+
unittest.main()

0 commit comments

Comments
 (0)