Adding and removing vertices and edges
Building up and tearing down a graph’s structure can be achieved by methods on the graph, vertex, and edge classes. These methods work for directed and undirected graphs.
Graph
The graph class provides methods for adding and removing vertices and edges.
Add a vertex to the graph |
|
Add an edge to the graph (base class method) |
|
Remove an edge from the graph |
|
Remove a vertex, and all its edges, from the graph |
Vertex
The vertex class provides methods for connecting a vertex to another vertex and for removing a vertex, and its edges, from the graph.
Connect two vertices with an edge |
|
Remove this vertex, and all its edges, from its graph |
Edge
The edge class provides methods for attaching an edge to a pair of vertices and for removing an edge from the graph. They are described on the Edges & Vertices page.
Attach this edge to a pair of vertices |
|
Remove this edge from its graph |
Details
- Graph.add_vertex(coord=None, name=None)[source]
Add a vertex to the graph
- Parameters:
coord (array-like or Vertex subclass, optional) – coordinate for an embedded graph, or an existing vertex (an instance of this graph’s
vertex_class, not belonging to a graph) to add as-is, defaults to Nonename (str, optional) – name of vertex, defaults to “#i”
- Raises:
TypeError –
coordis aVertexthat is not an instance of this graph’svertex_classValueError – the name is already used by another vertex in the graph, or
coordis a vertex that already belongs to a graphValueError – the graph was constructed with
dim, andcoordis given but its length doesn’t match
- Returns:
the added vertex
- Return type:
Vertex subclass
This is a graph-centric way of creating a vertex.
g.add_vertex()creates a new vertex with optionalcoordandname.g.add_vertex(v)takes an instance of this graph’svertex_class(by default anyVertex) and adds it to the graph.
If the vertex has no name and
nameis None give it a default name#NwhereNis the number of vertices, or the next integer above it that is not already used by a name in the graph.Names are unique within a graph, since they are how
g[name]finds a vertex, and a vertex belongs to one graph at a time.Changed in version 1.0: Adding a vertex whose name is already used raises
ValueError. It used to replace the earlier vertex in the name table, leaving it in the graph but unreachable by name. A default name could also clash with an existing one after a vertex had been removed.The vertex is placed into the graph’s vertex dictionary with a key equal to its name.
If the graph was constructed with a required
dim(seeGraph), every embedded vertex must have a coordinate of exactly that length – adding one of the wrong length raisesValueError:Note
This single implementation, shared by
UGraphandDGraph, is parameterized by the graph’svertex_classrather than duplicated per subclass – see Object lifecycle and graph-membership policy for why that matters.- Seealso:
- Graph.add_edge(v1, v2=None, **kwargs)[source]
Add an edge to the graph (base class method)
- Parameters:
v1 (Vertex subclass, str or Edge) – first vertex (start if a directed graph), or an existing edge that already carries its two vertices
v2 (Vertex subclass or str, optional) – second vertex (end if a directed graph), must be omitted if
v1is an edgekwargs (
Any) – optional arguments to pass toVertex.connect, not allowed ifv1is an edge
- Raises:
TypeError –
v1orv2is of the wrong type, orv2,costordatais given along with an edgeValueError – the edge has no vertices, or the vertices do not belong to this graph
- Returns:
edge
- Return type:
This is a graph-centric way of creating an edge. The alternative is the
connectmethod of a vertex.g.add_edge(v1, v2)creates an edge between a vertex pair and adds it to the graph.g.add_edge(e)takes an edge, or an instance of anEdgesubclass, that was constructed with its two vertices and adds it to the graph, just asg.add_vertex(v)takes an existing vertex.
1>>> from pgraph import UGraph 2>>> g = UGraph() 3>>> v1 = g.add_vertex(coord=[0,0], name='v1') 4>>> v2 = g.add_vertex(coord=[1,1], name='v2') 5>>> v3 = g.add_vertex(coord=[2,2], name='v3') 6>>> e = g.add_edge(v1, v2) 7>>> print(e) 8Edge{[v1] -- [v2], cost=1.414} 9>>> e2 = g.add_edge('v2', 'v3', cost=99) 10>>> print(e2) 11Edge{[v2] -- [v3], cost=99}
Note that at line 9 the vertices are specified by their string names.
Adding an instance of a user-defined
Edgesubclass:Note
Vertices have coordinates and the edge
costdefaults to the distance between them, but if the vertices have no coordinates the edge cost must be set explicitly, otherwise it will beNoneand path planning will fail with aValueError.Note
To supply an edge that does not yet have vertices use
g.add_edge(v1, v2, edge=e)ore.connect(v1, v2).- Seealso:
- Graph.remove_edge(edge)[source]
Remove an edge from the graph
- Parameters:
edge (
Edge) – edge to remove- Raises:
ValueError –
edgedoes not belong to this graph- Return type:
The edge is removed from this graph’s own edge collection and from the edge lists of its connected vertices, and
edge.v1/edge.v2are cleared toNone.Warning
The connectivity of the network may be changed.
>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> e = g.add_edge(v1, v2) >>> g.remove_edge(e) >>> print(g) UGraph: 2 vertices, 0 edges, 2 components
Note
A directed edge is tracked only by its source vertex’s edge list, not its target’s (see
Vertex.edges), so membership is checked per endpoint rather than assumed for both – removing a directed edge from an undirected-only implementation would otherwise raiseValueErroron the target side.- Seealso:
- Graph.remove_vertex(vertex)[source]
Remove a vertex, and all its edges, from the graph
- Parameters:
vertex (
Vertex) – vertex to remove- Raises:
ValueError –
vertexdoes not belong to this graph- Return type:
Every edge touching
vertex– incoming or outgoing – is removed viaremove_edge(), then the vertex itself is removed.Warning
The connectivity of the network may be changed.
>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> g.add_edge(v1, v2) Edge{[v1] -- [v2], cost=1.414} >>> g.remove_vertex(v2) >>> print(g) UGraph: 1 vertex, 0 edges, 1 component
Note
This scans the graph’s own edge set for edges touching
vertex, rather than iteratingvertex.edges()– for aDGraphvertex that only ever reports outgoing edges (seeVertex.edges), so incoming edges would otherwise be missed and left dangling.- Seealso:
- Graph.remove(x)[source]
Remove element from graph (deprecated)
- Parameters:
x (Edge or Vertex subclass) – element to remove from graph
- Raises:
TypeError – unknown type
- Return type:
Deprecated since version use:
remove_edge()orremove_vertex()instead – this dispatched ontype(x)to two operations with very different blast radii (detach one edge, vs. cascade-remove everything touching a vertex) hidden behind one ambiguous name.- Seealso:
- Vertex.connect(dest, edge=None, cost=None, data=None)[source]
Connect two vertices with an edge
- Parameters:
dest (
Vertexsubclass) – The vertex to connect toedge (
Edgesubclass, optional) – Use this as the edge object, otherwise a new object of the graph’sGraph.edge_classis created from the vertices being connected, and thecostanddataparameters, defaults to Nonecost (float, optional) – the cost to traverse this edge, defaults to None
data (Any, optional) – reference to arbitrary data associated with the edge, defaults to None
- Raises:
ValueError – either vertex has not been added to a graph, the vertices belong to different graphs, or
edgealready connects other verticesTypeError –
edgeis not an instance of the graph’sGraph.edge_class
- Returns:
the edge connecting the vertices
- Return type:
v1.connect(v2)connects vertexv1to vertexv2.Note
In an undirected graph the edge is recorded in the edge list of both vertices, so it is found from either end. In a directed graph it is recorded as leaving this, the start, vertex and entering
dest.A supplied
edgebuilt without vertices has itsv1andv2set to the vertices being connected. One built with vertices must agree with them: in either order if undirected, exactlyselfthendestif directed.Both vertices must already have been added to the same graph, e.g. via
Graph.add_vertex().
>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> e = v1.connect(v2, cost=1.414) >>> print(e) Edge{[v1] -- [v2], cost=1.414}
- Seealso:
- Vertex.remove()[source]
Remove this vertex, and all its edges, from its graph
- Raises:
ValueError – the vertex is not connected to a graph
v.remove()removesv, and every edge touching it (incoming or outgoing), from its graph. TheVertexobject itself is not deleted.Note
This is a thin convenience wrapper around
Graph.remove_vertex().- Return type:
None
>>> from pgraph import UGraph >>> g = UGraph() >>> v1 = g.add_vertex(coord=[0,0], name='v1') >>> v2 = g.add_vertex(coord=[1,1], name='v2') >>> g.add_edge(v1, v2) Edge{[v1] -- [v2], cost=1.414} >>> v2.remove() >>> print(g) UGraph: 1 vertex, 0 edges, 1 component
- Seealso: