*********************** 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. .. code-block:: python :linenos: session = pypgx.get_session() graph = session.read_graph_with_properties(self.graph_path) This will load the following sample graph: .. image:: /_static/images/pgx-sample-graph.jpg :alt: pgx sample graph Adding, removing and modifying vertices --------------------------------------- Now that we have a graph loaded we can start modifying it. First we need a :class:`GraphChangeSet` - an object similar to the :class:`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``. .. code-block:: python :linenos: change_set = graph.create_change_set() # Add, remove and modify vertices change_set.add_vertex(42).set_property("prop", 23) change_set.update_vertex(128).set_property("prop", 5) change_set.remove_vertex(1908) updated_graph = change_set.build() # Check if the new changes are applied to updated_graph self.assertTrue(updated_graph.has_vertex(42)) self.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: .. image:: /_static/images/pgx-sample-graph-updated.png :alt: pgx sample graph updated Adding edges ------------ The same way edges can be added to the graph. For example we can add a new triangle to the graph: .. code-block:: python :linenos: change_set_2 = graph.create_change_set() change_set_2.add_edge(128, 99).set_property("cost", 42.42) change_set_2.add_edge(333, 1908) updated_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: .. image:: /_static/images/pgx-sample-graph-updated-2.png :alt: pgx sample graph updated 2 Note that by calling :meth:`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 :meth:`build()` method.