Skip to content

Commit 2fbda2f

Browse files
petercorkeclaude
andcommitted
feat: add_edge() accepts an Edge as well as two vertices
g.add_edge(MyEdge(v1, v2)) now works, mirroring add_vertex() which takes coordinates or an existing vertex. The edge must already carry both vertices; extra cost/data arguments are rejected since connect() would silently ignore them. add_edge() (either form) now also refuses vertices that belong to a different graph instead of silently adding the edge to that graph. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 6f69e7d commit 2fbda2f

1 file changed

Lines changed: 77 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
"""

0 commit comments

Comments
 (0)