Modifying loaded graphs
This guide shows how to add and remove vertices and edges from already loaded graphs. This can be useful for “what-if” analyses.
Recap: Loading a graph
At first we need to load a graph.
1session = pypgx.get_session()
2graph = session.read_graph_with_properties(self.graph_path)
This will load the following sample graph:
Adding, removing and modifying vertices
Now that we have a graph loaded we can start modifying it.
First we need a GraphChangeSet
- an object similar to the GraphBuilder
.
It provides methods for modifying all aspects of a graph.
We are going to add a new vertex 42
with the property value 23
for prop1
.
Additionally we are going to set the value of prop1
for vertex 128
to 5
.
Finally we will remove the vertex with ID 1908
.
1change_set = graph.create_change_set()
2# Add, remove and modify vertices
3change_set.add_vertex(42).set_property("prop", 23)
4change_set.update_vertex(128).set_property("prop", 5)
5change_set.remove_vertex(1908)
6updated_graph = change_set.build()
7# Check if the new changes are applied to updated_graph
8self.assertTrue(updated_graph.has_vertex(42))
9self.assertFalse(updated_graph.has_vertex(1908))
Notice that vertex 1908
has one edge attached in the original graph. This edge will be deleted automatically with the deletion of the vertex.
The resulting graph will have the following form:
Adding edges
The same way edges can be added to the graph. For example we can add a new triangle to the graph:
1change_set_2 = graph.create_change_set()
2change_set_2.add_edge(128, 99).set_property("cost", 42.42)
3change_set_2.add_edge(333, 1908)
4updated_graph_2 = change_set_2.build()
Note that we do not provide a value for the property cost for the second edge we add. In this case the property will be assigned a default value of 0.0
.
This is the resulting graph:
Note that by calling change_set_2.build()
we created a brand new graph with a unique name assigned by PGX;
if need be, we can specify a name argument to the build()
method.