Skip to content

Commit b6e799a

Browse files
authored
Merge pull request #27 from petercorke/feat/add-edge-accepts-edge
feat: add_edge() accepts an Edge as well as two vertices
2 parents cf7e537 + 2bb12c0 commit b6e799a

2 files changed

Lines changed: 186 additions & 14 deletions

File tree

‎src/pgraph/PGraph.py‎

Lines changed: 77 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import tempfile
1111
import subprocess
1212
import webbrowser
13-
from typing import Any, Callable, ClassVar
13+
from typing import Any, Callable, ClassVar, overload
1414
from numpy.typing import ArrayLike, NDArray
1515

1616
from spatialmath.base.graphics import axes_logic
@@ -416,19 +416,43 @@ def _require_cost(self, edge: Edge) -> float:
416416
)
417417
return edge.cost
418418

419-
def add_edge(self, v1: BaseVertex | str, v2: BaseVertex | str, **kwargs: Any) -> Edge:
419+
@overload
420+
def add_edge(self, v1: Edge, **kwargs: Any) -> Edge: ...
421+
422+
@overload
423+
def add_edge(
424+
self, v1: BaseVertex | str, v2: BaseVertex | str, **kwargs: Any
425+
) -> Edge: ...
426+
427+
def add_edge(
428+
self,
429+
v1: Edge | BaseVertex | str,
430+
v2: BaseVertex | str | None = None,
431+
**kwargs: Any,
432+
) -> Edge:
420433
"""
421434
Add an edge to the graph (base class method)
422435
423-
:param v1: first vertex (start if a directed graph)
424-
:type v1: BaseVertex subclass or str
425-
:param v2: second vertex (end if a directed graph)
426-
:type v2: BaseVertex subclass or str
427-
:param kwargs: optional arguments to pass to ``BaseVertex.connect``
436+
:param v1: first vertex (start if a directed graph), or an existing
437+
edge that already carries its two vertices
438+
:type v1: BaseVertex subclass, str or Edge
439+
:param v2: second vertex (end if a directed graph), must be omitted
440+
if ``v1`` is an edge
441+
:type v2: BaseVertex subclass or str, optional
442+
:param kwargs: optional arguments to pass to ``BaseVertex.connect``,
443+
not allowed if ``v1`` is an edge
444+
:raises TypeError: ``v1`` or ``v2`` is of the wrong type, or ``v2``,
445+
``cost`` or ``data`` is given along with an edge
446+
:raises ValueError: the edge has no vertices, or the vertices do not
447+
belong to this graph
428448
:return: edge
429449
:rtype: Edge
430450
431-
Create an edge between a vertex pair and adds it to the graph.
451+
- ``g.add_edge(v1, v2)`` creates an edge between a vertex pair and
452+
adds it to the graph.
453+
- ``g.add_edge(e)`` takes an edge, or an instance of an ``Edge``
454+
subclass, that was constructed with its two vertices and adds it to
455+
the graph, just as ``g.add_vertex(v)`` takes an existing vertex.
432456
433457
This is a graph centric way of creating an edge. The
434458
alternative is the ``connect`` method of a vertex.
@@ -445,14 +469,53 @@ def add_edge(self, v1: BaseVertex | str, v2: BaseVertex | str, **kwargs: Any) ->
445469
>>> e2 = g.add_edge('v2', 'v3', cost=99)
446470
>>> print(e2)
447471
448-
:seealso: :meth:`Edge.connect` :meth:`BaseVertex.connect`
449-
"""
450-
v1 = self._resolve_vertex(v1, "v1")
451-
v2 = self._resolve_vertex(v2, "v2")
472+
Adding an instance of a user-defined ``Edge`` subclass:
473+
474+
.. runblock:: pycon
475+
476+
>>> from pgraph import UGraph, Edge
477+
>>> class MyEdge(Edge):
478+
... pass
479+
>>> g = UGraph()
480+
>>> v1 = g.add_vertex(coord=[0,0], name='v1')
481+
>>> v2 = g.add_vertex(coord=[1,1], name='v2')
482+
>>> e = g.add_edge(MyEdge(v1, v2, data="a road"))
483+
>>> print(type(e).__name__, e.data)
484+
485+
.. note:: To supply an edge that does not yet have vertices use
486+
``g.add_edge(v1, v2, edge=e)`` or ``e.connect(v1, v2)``.
487+
488+
:seealso: :meth:`add_vertex` :meth:`Edge.connect` :meth:`BaseVertex.connect`
489+
"""
490+
if isinstance(v1, Edge):
491+
if v2 is not None:
492+
raise TypeError("v2 must not be given when adding an Edge")
493+
if kwargs:
494+
raise TypeError(
495+
"add_edge(edge) takes no other arguments, got "
496+
+ ", ".join(kwargs)
497+
+ " -- set them on the edge itself"
498+
)
499+
edge = v1
500+
if edge.v1 is None or edge.v2 is None:
501+
raise ValueError(
502+
"edge does not have both vertices; use "
503+
"add_edge(v1, v2, edge=e) or e.connect(v1, v2)"
504+
)
505+
start, end = edge.v1, edge.v2
506+
kwargs = {"edge": edge}
507+
else:
508+
if v2 is None:
509+
raise TypeError("add_edge() requires two vertices, or an Edge")
510+
start = self._resolve_vertex(v1, "v1")
511+
end = self._resolve_vertex(v2, "v2")
512+
513+
if start._graph is not self or end._graph is not self:
514+
raise ValueError("vertices must belong to this graph")
452515

453516
if self._verbose:
454-
print(f"New edge from {v1.name} to {v2.name}")
455-
return v1.connect(v2, **kwargs)
517+
print(f"New edge from {start.name} to {end.name}")
518+
return start.connect(end, **kwargs)
456519

457520
def remove_edge(self, edge: Edge) -> None:
458521
"""

‎tests/test_add_edge_edge.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
"""
2+
``graph.add_edge()`` accepts either two vertices (or names) or an ``Edge``
3+
that already carries its vertices, mirroring ``add_vertex()`` which accepts
4+
coordinates or a vertex.
5+
"""
6+
7+
import unittest
8+
9+
from pgraph import DGraph, Edge, UGraph, UVertex
10+
11+
12+
class MyEdge(Edge):
13+
pass
14+
15+
16+
class _AddEdge:
17+
Graph: type
18+
19+
def setUp(self):
20+
self.g = self.Graph()
21+
self.a = self.g.add_vertex([0, 0], name="a")
22+
self.b = self.g.add_vertex([3, 4], name="b")
23+
self.c = self.g.add_vertex([6, 8], name="c")
24+
25+
def test_two_vertices_unchanged(self):
26+
e = self.g.add_edge(self.a, self.b)
27+
self.assertIs(type(e), Edge)
28+
self.assertEqual((e.v1, e.v2), (self.a, self.b))
29+
self.assertEqual(e.cost, 5.0)
30+
31+
def test_two_names_unchanged(self):
32+
e = self.g.add_edge("a", "b", cost=9)
33+
self.assertEqual((e.v1, e.v2, e.cost), (self.a, self.b, 9))
34+
35+
def test_edge_subclass(self):
36+
e = MyEdge(self.a, self.b, cost=2, data="hello")
37+
r = self.g.add_edge(e)
38+
39+
self.assertIs(r, e)
40+
self.assertIsInstance(r, MyEdge)
41+
self.assertEqual(self.g.ne, 1)
42+
self.assertIn(e, self.g.edges())
43+
self.assertIs(self.a.edgeto(self.b), e)
44+
self.assertEqual(e.data, "hello")
45+
46+
def test_edge_cost_computed_at_construction(self):
47+
r = self.g.add_edge(MyEdge(self.a, self.b))
48+
self.assertEqual(r.cost, 5.0)
49+
50+
def test_edge_must_carry_vertices(self):
51+
with self.assertRaises(ValueError) as cm:
52+
self.g.add_edge(MyEdge(cost=1))
53+
self.assertIn("edge=", str(cm.exception)) # points at the alternative
54+
with self.assertRaises(ValueError):
55+
self.g.add_edge(MyEdge(self.a)) # only one end
56+
self.assertEqual(self.g.ne, 0)
57+
58+
def test_edge_and_second_vertex_is_an_error(self):
59+
with self.assertRaises(TypeError):
60+
self.g.add_edge(MyEdge(self.a, self.b), self.c)
61+
self.assertEqual(self.g.ne, 0)
62+
63+
def test_edge_with_cost_or_data_kwargs_is_an_error(self):
64+
# connect() would silently ignore them when given an edge
65+
e = MyEdge(self.a, self.b)
66+
with self.assertRaises(TypeError):
67+
self.g.add_edge(e, cost=3)
68+
with self.assertRaises(TypeError):
69+
self.g.add_edge(e, data="x")
70+
self.assertEqual(self.g.ne, 0)
71+
72+
def test_wrong_type(self):
73+
with self.assertRaises(TypeError):
74+
self.g.add_edge(42, self.b)
75+
with self.assertRaises(TypeError):
76+
self.g.add_edge(self.a, 42)
77+
78+
def test_vertices_of_another_graph(self):
79+
h = self.Graph()
80+
x = h.add_vertex([0, 0], name="x")
81+
y = h.add_vertex([1, 1], name="y")
82+
with self.assertRaises(ValueError):
83+
self.g.add_edge(MyEdge(x, y))
84+
with self.assertRaises(ValueError):
85+
self.g.add_edge(x, y)
86+
self.assertEqual(self.g.ne, 0)
87+
self.assertEqual(h.ne, 0)
88+
89+
def test_edge_between_ungraphed_vertices(self):
90+
v, w = UVertex([0, 0]), UVertex([1, 1])
91+
with self.assertRaises(ValueError):
92+
self.g.add_edge(MyEdge(v, w))
93+
94+
95+
class TestUGraphAddEdge(_AddEdge, unittest.TestCase):
96+
Graph = UGraph
97+
98+
99+
class TestDGraphAddEdge(_AddEdge, unittest.TestCase):
100+
Graph = DGraph
101+
102+
def test_direction_follows_edge(self):
103+
self.g.add_edge(MyEdge(self.b, self.a))
104+
self.assertEqual(self.b.neighbours(), [self.a])
105+
self.assertEqual(self.a.neighbours(), [])
106+
107+
108+
if __name__ == "__main__":
109+
unittest.main()

0 commit comments

Comments
 (0)