diff --git a/src/pgraph/PGraph.py b/src/pgraph/PGraph.py index f92d00de..b73a9926 100644 --- a/src/pgraph/PGraph.py +++ b/src/pgraph/PGraph.py @@ -2379,10 +2379,17 @@ def connect(self, v1: BaseVertex, v2: BaseVertex) -> None: :type v1: BaseVertex subclass :param v2: end of the edge :type v2: BaseVertex subclass + :raises ValueError: either vertex has not been added to a graph, or + the vertices belong to different graphs The edge connects vertices ``v1`` and ``v2``, and is added to the graph that those vertices belong to. + .. warning:: Intended for an edge that is not yet part of a graph. The + edge's ``v1`` and ``v2`` are overwritten without checking, so + connecting an edge that is already in a graph leaves it + referenced from its old vertices as well. + .. runblock:: pycon >>> from pgraph import UVertex, Edge, UGraph @@ -2761,8 +2768,9 @@ def connect( :param data: reference to arbitrary data associated with the edge, defaults to None :type data: Any, optional - :raises ValueError: either vertex has not been added to a graph, or - the vertices belong to different graphs + :raises ValueError: either vertex has not been added to a graph, the + vertices belong to different graphs, or ``edge`` already connects + other vertices :return: the edge connecting the vertices :rtype: Edge @@ -2772,6 +2780,9 @@ def connect( - If the vertices subclass ``UVertex`` the edge is undirected, and if they subclass ``DVertex`` the edge is directed. + - A supplied ``edge`` built without vertices has its ``v1`` and + ``v2`` set to the vertices being connected. One built with + vertices must agree with them (in either order if undirected). - Both vertices must already have been added to the same graph, e.g. via :meth:`PGraph.add_vertex` -- since a graph only ever accepts its own vertex subclass (see :meth:`UGraph.add_vertex`, @@ -2798,6 +2809,7 @@ def connect( raise ValueError("vertices must belong to the same graph") elif isinstance(edge, Edge): e = edge + self._bind_edge(e, dest) else: e = Edge(self, dest, cost=cost, data=data) @@ -2807,6 +2819,38 @@ def connect( return e + def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool: + """ + Test if an edge already connects this vertex to ``dest`` (private method) + + A directed edge must run from this vertex to ``dest``; see + :meth:`UVertex._endpoints_match` for the undirected relaxation. + """ + return edge.v1 is self and edge.v2 is dest + + def _bind_edge(self, edge: Edge, dest: BaseVertex) -> None: + """ + Make a caller-supplied edge connect this vertex to ``dest`` (private method) + + :param edge: edge passed to :meth:`connect` + :param dest: vertex being connected to + :raises ValueError: ``edge`` already connects other vertices + + An edge built without vertices has its ``v1`` and ``v2`` set here. + One built with vertices is left alone provided they agree with the + connection being made; otherwise it is rejected before anything is + changed, rather than leaving the graph holding an edge whose + endpoints disagree with the vertices' edge lists. + """ + if edge.v1 is None and edge.v2 is None: + edge.v1 = self + edge.v2 = dest + elif not self._endpoints_match(edge, dest): + raise ValueError( + f"edge already connects {edge.v1} and {edge.v2}, " + f"not {self} and {dest}" + ) + def edgeto(self, dest: BaseVertex) -> Edge: """ Get edge connecting vertex to specific neighbour @@ -3095,12 +3139,19 @@ def connect( :param data: reference to arbitrary data associated with the edge, defaults to None :type data: Any, optional + :raises ValueError: either vertex has not been added to a graph, the + vertices belong to different graphs, or ``edge`` already connects + other vertices :return: the edge connecting the vertices :rtype: Edge Unlike the directed-graph counterpart, the new edge is added to *both* vertices' edge lists, so it is discovered from either end. + If ``edge`` was built without vertices its ``v1`` and ``v2`` are set + to ``self`` and ``dest``. If it was built with vertices they must be + these two, in either order since an undirected edge has no direction. + .. runblock:: pycon >>> from pgraph import UVertex, Edge, UGraph @@ -3122,6 +3173,16 @@ def connect( return e + def _endpoints_match(self, edge: Edge, dest: BaseVertex) -> bool: + """ + Test if an edge already connects this vertex and ``dest`` (private method) + + An undirected edge has no direction, so either order is accepted. + """ + return (edge.v1 is self and edge.v2 is dest) or ( + edge.v1 is dest and edge.v2 is self + ) + class DVertex(BaseVertex): """ @@ -3154,6 +3215,9 @@ def connect( :param data: reference to arbitrary data associated with the edge, defaults to None :type data: Any, optional + :raises ValueError: either vertex has not been added to a graph, the + vertices belong to different graphs, or ``edge`` already connects + other vertices :return: the edge connecting the vertices :rtype: Edge @@ -3161,6 +3225,10 @@ def connect( to *this* vertex's edge list -- it is only discoverable from the start of the directed edge. + If ``edge`` was built without vertices its ``v1`` and ``v2`` are set + to ``self`` and ``dest``. If it was built with vertices they must be + exactly these two, in this order, since the edge has a direction. + .. runblock:: pycon >>> from pgraph import DVertex, Edge, DGraph diff --git a/tests/test_connect_edge.py b/tests/test_connect_edge.py new file mode 100644 index 00000000..ba83df9b --- /dev/null +++ b/tests/test_connect_edge.py @@ -0,0 +1,96 @@ +""" +``v.connect(w, edge=e)`` with a caller-supplied ``Edge`` must leave the edge +knowing its endpoints, and refuse an edge that already names other vertices. +""" + +import unittest + +from pgraph import DGraph, Edge, UGraph + + +class MyEdge(Edge): + pass + + +class _ConnectEdge: + Graph: type + + def setUp(self): + self.g = self.Graph() + self.a = self.g.add_vertex([0, 0], name="a") + self.b = self.g.add_vertex([1, 0], name="b") + self.c = self.g.add_vertex([2, 0], name="c") + self.d = self.g.add_vertex([3, 0], name="d") + + def test_bare_edge_gets_endpoints(self): + e = Edge(cost=7) + r = self.a.connect(self.b, edge=e) + + self.assertIs(r, e) + self.assertIs(e.v1, self.a) + self.assertIs(e.v2, self.b) + self.assertEqual(self.g.ne, 1) + + def test_bare_edge_is_a_working_edge(self): + e = MyEdge(cost=7) + self.a.connect(self.b, edge=e) + + self.assertEqual(self.g.incidence().shape, (4, 1)) + self.assertEqual(self.a.edgeto(self.b).cost, 7) + self.g.remove_edge(e) # asserted on v1/v2 not being None + self.assertEqual(self.g.ne, 0) + self.assertIsNone(e.v1) + + def test_edge_with_matching_endpoints(self): + e = MyEdge(self.a, self.b, cost=3) + self.assertIs(self.a.connect(self.b, edge=e), e) + self.assertEqual((e.v1, e.v2), (self.a, self.b)) + + def test_edge_with_other_endpoints_rejected(self): + e = Edge(self.a, self.b) + with self.assertRaises(ValueError): + self.c.connect(self.d, edge=e) + + # nothing was half-done + self.assertEqual(self.g.ne, 0) + self.assertEqual(self.c.edges(), []) + self.assertEqual(self.d.edges(), []) + self.assertEqual((e.v1, e.v2), (self.a, self.b)) + + def test_edge_with_one_endpoint_matching_rejected(self): + e = Edge(self.a, self.b) + with self.assertRaises(ValueError): + self.a.connect(self.c, edge=e) + self.assertEqual(self.g.ne, 0) + + def test_edge_connect_method_still_works(self): + e = MyEdge(cost=2) + e.connect(self.a, self.b) + self.assertEqual((e.v1, e.v2), (self.a, self.b)) + self.assertEqual(self.g.ne, 1) + + +class TestUGraphConnectEdge(_ConnectEdge, unittest.TestCase): + Graph = UGraph + + def test_reversed_endpoints_are_the_same_undirected_edge(self): + e = Edge(self.b, self.a) + self.assertIs(self.a.connect(self.b, edge=e), e) + self.assertEqual(self.g.ne, 1) + self.assertIn(self.b, self.a.neighbours()) + self.assertIn(self.a, self.b.neighbours()) + + +class TestDGraphConnectEdge(_ConnectEdge, unittest.TestCase): + Graph = DGraph + + def test_reversed_endpoints_rejected(self): + # an arrow b->a is not the arrow a->b + e = Edge(self.b, self.a) + with self.assertRaises(ValueError): + self.a.connect(self.b, edge=e) + self.assertEqual(self.g.ne, 0) + + +if __name__ == "__main__": + unittest.main()