Graph#

class graph_tool.Graph(g=None, directed=True, prune=False, vorder=None, fast_edge_removal=False, fast_edge_lookup=False, parallel=True, **kwargs)[git][source]#

General multigraph class.

This class encapsulates either a directed multigraph (default or if directed == True) or an undirected multigraph (if directed == False), with optional internal edge, vertex, or graph properties.

If g is specified, it can be one of:

  1. Another Graph object, in which case the corresponding graph (and its internal properties) will be copied.

  2. An integer, in which case it corresponds to the number of vertices in the graph, which is initially empty.

  3. An edge list, i.e. an iterable over (source, target) pairs, which will be used to populate the graph.

    This is equivalent to calling add_edge_list() with an empty graph, as follows:

    >>> elist = [(0, 1), (0, 2)]
    >>> g = gt.Graph()
    >>> g.add_edge_list(elist)
    
  4. An adjacency list, i.e. a dictionary with vertex keys mapping to an iterable of vertices, which will be used to populate the graph. For directed graphs, the adjacency should list the out-neighbors.

    This is equivalent to calling add_edge_list() as such:

    >>> adj = {0: [1, 2], 2: [3], 4: []}
    >>> def elist():
    ...     for u, vw in adj.items():
    ...         k = 0
    ...         for v in vw:
    ...             k += 1
    ...             yield u, v
    ...         if k == 0:
    ...             yield u, None
    >>> g = gt.Graph()
    >>> g.add_edge_list(elist())
    

    Note

    For undirected graphs, if a vertex u appears in the adjacency list of v and vice versa, then the edge (u,v) is added twice in the graph. To prevent this from happening the adjacency list should mention an edge only once.

  5. A sparse adjacency matrix of type scipy.sparse.sparray or scipy.sparse.spmatrix. The matrix entries will be stored as an internal EdgePropertyMap named "weight". If directed == False, only the upper triangular portion of this matrix will be considered, and the remaining entries will be ignored.

    This is equivalent to calling add_edge_list() as such:

    >>> a = scipy.sparse.coo_array([[0, 2, 1], [3, 1, 2], [0, 1, 0]])
    >>> s, t, w = scipy.sparse.find(a)
    >>> es = np.array([s, t, w]).T
    >>> g = gt.Graph(a.shape[0])
    >>> g.add_edge_list(es, eprops=[("weight", "int")])
    

In cases 3 and 4 above, all remaining keyword parameters passed to Graph will be passed along to the Graph.add_edge_list() function. If the option hashed == True is passed, the vertex ids will be stored in an internal VertexPropertyMap called "ids".

In case g is specified and points to a Graph object, the following options take effect:

  • If prune is set to True, only the filtered graph will be copied, and the new graph object will not be filtered. Optionally, a tuple of three booleans can be passed as value to prune, to specify a different behavior to vertex, edge, and reversal filters, respectively.

  • If vorder is specified, it should correspond to a vertex VertexPropertyMap specifying the ordering of the vertices in the copied graph.

The value of fast_edge_removal is passed to set_fast_edge_removal().

If parallel == False, the graph is copied (or its edges inserted, in cases 3, 4, and 5 above) with a single thread. The copy is the same in either case, while the order of edges inserted from a list depends on the scheduling of the threads if parallel == True (see add_edge_list()).

The value of fast_edge_lookup is passed to set_fast_edge_lookup().

Note

The graph is implemented internally as an adjacency list, where both vertex and edge lists are C++ STL vectors.

copy()[git][source]#

Return a deep copy of self. All internal property maps are also copied.

Iterating over vertices and edges

See Iterating over vertices and edges for more documentation and examples.

Iterator-based interface with descriptors:

vertices()[git][source]#

Return an iterator over the vertices.

Note

The order of the vertices traversed by the iterator always corresponds to the vertex index ordering, as given by the vertex_index property map.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.Graph()
>>> vlist = list(g.add_vertex(5))
>>> vlist2 = []
>>> for v in g.vertices():
...     vlist2.append(v)
...
>>> assert(vlist == vlist2)
edges()[git][source]#

Return an iterator over the edges.

Note

The order of the edges traversed by the iterator does not necessarily correspond to the edge index ordering, as given by the edge_index property map. This will only happen after reindex_edges() is called, or in certain situations such as just after a graph is loaded from a file. However, further manipulation of the graph may destroy the ordering.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Iterator-based interface without descriptors:

iter_vertices(vprops=[])[git][source]#

Return an iterator over the vertex indices, and optional vertex properties list vprops.

Note

This mode of iteration is more efficient than using vertices(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.Graph()
>>> g.add_vertex(5)
<...>
>>> for v in g.iter_vertices():
...     print(v)
0
1
2
3
4
iter_edges(eprops=[])[git][source]#

Return an iterator over the edge (source, target) pairs, and optional edge properties list eprops.

Note

This mode of iteration is more efficient than using edges(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["karate"]
>>> for s, t, i in g.iter_edges([g.edge_index]):
...     print(s, t, i)
...     if s == 5:
...         break
1 0 0
2 0 1
2 1 2
3 0 3
3 1 4
3 2 5
4 0 6
5 0 7
iter_out_edges(v, eprops=[])[git][source]#

Return an iterator over the out-edge (source, target) pairs for vertex v, and optional edge properties list eprops.

Note

This mode of iteration is more efficient than using out_edges(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for s, t, i in g.iter_out_edges(66, [g.edge_index]):
...     print(s, t, i)
66 63 5266
66 20369 5267
66 13980 5268
66 8687 5269
66 38674 5270
iter_in_edges(v, eprops=[])[git][source]#

Return an iterator over the in-edge (source, target) pairs for vertex v, and optional edge properties list eprops.

Note

This mode of iteration is more efficient than using in_edges(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for s, t, i in g.iter_in_edges(66, [g.edge_index]):
...     print(s, t, i)
8687 66 179681
20369 66 255033
38674 66 300230
iter_all_edges(v, eprops=[])[git][source]#

Return an iterator over the in- and out-edge (source, target) pairs for vertex v, and optional edge properties list eprops.

Note

This mode of iteration is more efficient than using all_edges(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for s, t, i in g.iter_all_edges(66, [g.edge_index]):
...     print(s, t, i)
66 63 5266
66 20369 5267
66 13980 5268
66 8687 5269
66 38674 5270
8687 66 179681
20369 66 255033
38674 66 300230
iter_out_neighbors(v, vprops=[])[git][source]#

Return an iterator over the out-neighbors of vertex v, and optional vertex properties list vprops.

Note

This mode of iteration is more efficient than using out_neighbors(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for u, i in g.iter_out_neighbors(66, [g.vp.uid]):
...     print(u, i)
63 ['paul wilders <webmaster@wilders.org>']
20369 ['Zhen-Xjell <zhen-xjell@teamhelix.net>']
13980 ['Hooman <Hooman@iname.com>']
8687 ['H. Loeung (howe81) <howe81@unixque.com>', 'howe81 <howe81@bigpond.net.au>', 'Howie L (howe81) <howe81@bigpond.net.au>']
38674 ['Howie L (howe81) <howe81@bigpond.net.au>']
iter_in_neighbors(v, vprops=[])[git][source]#

Return an iterator over the in-neighbors of vertex v, and optional vertex properties list vprops.

Note

This mode of iteration is more efficient than using in_neighbors(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for u, i in g.iter_in_neighbors(66, [g.vp.uid]):
...     print(u, i)
8687 ['H. Loeung (howe81) <howe81@unixque.com>', 'howe81 <howe81@bigpond.net.au>', 'Howie L (howe81) <howe81@bigpond.net.au>']
20369 ['Zhen-Xjell <zhen-xjell@teamhelix.net>']
38674 ['Howie L (howe81) <howe81@bigpond.net.au>']
iter_all_neighbors(v, vprops=[])[git][source]#

Return an iterator over the in- and out-neighbors of vertex v, and optional vertex properties list vprops.

Note

This mode of iteration is more efficient than using all_neighbors(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> for u, i in g.iter_all_neighbors(66, [g.vp.uid]):
...     print(u, i)
63 ['paul wilders <webmaster@wilders.org>']
20369 ['Zhen-Xjell <zhen-xjell@teamhelix.net>']
13980 ['Hooman <Hooman@iname.com>']
8687 ['H. Loeung (howe81) <howe81@unixque.com>', 'howe81 <howe81@bigpond.net.au>', 'Howie L (howe81) <howe81@bigpond.net.au>']
38674 ['Howie L (howe81) <howe81@bigpond.net.au>']
8687 ['H. Loeung (howe81) <howe81@unixque.com>', 'howe81 <howe81@bigpond.net.au>', 'Howie L (howe81) <howe81@bigpond.net.au>']
20369 ['Zhen-Xjell <zhen-xjell@teamhelix.net>']
38674 ['Howie L (howe81) <howe81@bigpond.net.au>']
iter_edge_range(s, t, eprops)[git][source]#

Return an iterator over the edge properties list eprops for parallel edges between vertices s and t.

This operation normally will take \(O(\min(k(s), k(t)))\) time, where \(k(s)\) and \(k(t)\) are the out-degree and in-degree (or out-degree if undirected) of vertices \(s\) and \(t\). However, if set_fast_edge_lookup() is set to True, this operation becomes \(O(m)\), where \(m\) is the number of parallel edges.

Note

This mode of iteration is more efficient than using edge(), as descriptor objects are not created.

Warning

The graph must not be modified (e.g. by adding or removing vertices or edges) while the iterator is in use, since this invalidates it.

Examples

>>> g = gt.Graph([(0, 1), (0, 1)])
>>> for i in g.iter_edge_range(0, 1, [g.edge_index]):
...     print(i)
[0]
[1]

Array-based interface:

get_vertices(vprops=[])[git][source]#

Return a numpy.ndarray containing the vertex indices, and optional vertex properties list vprops. If vprops is not empty, the shape of the array will be (V, 1 + len(vprops)), where V is the number of vertices, and each line will contain the vertex and the vertex property values.

Note

The order of the vertices is identical to vertices().

Examples

>>> g = gt.Graph()
>>> g.add_vertex(5)
<...>
>>> g.get_vertices()
array([0, 1, 2, 3, 4])
get_edges(eprops=[])[git][source]#

Return a numpy.ndarray containing the edges, and optional edge properties list eprops. The shape of the array will be (E, 2 + len(eprops)), where E is the number of edges, and each line will contain the source, target, and the edge property values.

Note

The order of the edges is identical to edges().

Examples

>>> g = gt.random_graph(6, lambda: 1, directed=False)
>>> g.get_edges([g.edge_index])
array([[3, 2, 0],
       [4, 1, 2],
       [5, 0, 1]])
get_out_edges(v, eprops=[])[git][source]#

Return a numpy.ndarray containing the out-edges of vertex v, and optional edge properties list eprops. The shape of the array will be (E, 2 + len(eprops)), where E is the number of edges, and each line will contain the source, target, and the edge property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_out_edges(66, [g.edge_index])
array([[   66,    63,  5266],
       [   66, 20369,  5267],
       [   66, 13980,  5268],
       [   66,  8687,  5269],
       [   66, 38674,  5270]])
get_in_edges(v, eprops=[])[git][source]#

Return a numpy.ndarray containing the in-edges of vertex v, and optional edge properties list eprops. The shape of the array will be (E, 2 + len(eprops)), where E is the number of edges, and each line will contain the source, target, and the edge property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_in_edges(66, [g.edge_index])
array([[  8687,     66, 179681],
       [ 20369,     66, 255033],
       [ 38674,     66, 300230]])
get_all_edges(v, eprops=[])[git][source]#

Return a numpy.ndarray containing the in- and out-edges of vertex v, and optional edge properties list eprops. The shape of the array will be (E, 2 + len(eprops)), where E is the number of edges, and each line will contain the source, target, and the edge property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_all_edges(66, [g.edge_index])
array([[    66,     63,   5266],
       [    66,  20369,   5267],
       [    66,  13980,   5268],
       [    66,   8687,   5269],
       [    66,  38674,   5270],
       [  8687,     66, 179681],
       [ 20369,     66, 255033],
       [ 38674,     66, 300230]])
get_out_neighbors(v, vprops=[])[git][source]#

Return a numpy.ndarray containing the out-neighbors of vertex v, and optional vertex properties list vprops. If vprops is not empty, the shape of the array will be (V, 1 + len(vprops)), where V is the number of vertices, and each line will contain a vertex and its property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_out_neighbors(66)
array([   63, 20369, 13980,  8687, 38674])
get_in_neighbors(v, vprops=[])[git][source]#

Return a numpy.ndarray containing the in-neighbors of vertex v, and optional vertex properties list vprops. If vprops is not empty, the shape of the array will be (V, 1 + len(vprops)), where V is the number of vertices, and each line will contain a vertex and its property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_in_neighbors(66)
array([ 8687, 20369, 38674])
get_all_neighbors(v, vprops=[])[git][source]#

Return a numpy.ndarray containing the in-neighbors and out-neighbors of vertex v, and optional vertex properties list vprops. If vprops is not empty, the shape of the array will be (V, 1 + len(vprops)), where V is the number of vertices, and each line will contain a vertex and its property values.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_all_neighbors(66)
array([   63, 20369, 13980,  8687, 38674,  8687, 20369, 38674])
get_out_degrees(vs, eweight=None)[git][source]#

Return a numpy.ndarray containing the out-degrees of vertex list vs. If supplied, the degrees will be weighted according to the edge EdgePropertyMap eweight.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_out_degrees([42, 666])
array([20, 38], dtype=uint64)
get_in_degrees(vs, eweight=None)[git][source]#

Return a numpy.ndarray containing the in-degrees of vertex list vs. If supplied, the degrees will be weighted according to the edge EdgePropertyMap eweight.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_in_degrees([42, 666])
array([20, 39], dtype=uint64)
get_total_degrees(vs, eweight=None)[git][source]#

Return a numpy.ndarray containing the total degrees (i.e. in- plus out-degree) of vertex list vs. If supplied, the degrees will be weighted according to the edge EdgePropertyMap eweight.

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_total_degrees([42, 666])
array([40, 77], dtype=uint64)
get_edge_range(s, t, eprops)[git][source]#

Return a numpy.ndarray containing the parallel edge properties eprops for the parallel edges between vertices s and t.

The shape of the array will be (m, len(eprops)), where m is the number of parallel edges, and each line will contain the edge property values.

This operation normally will take \(O(\min(k(s), k(t)))\) time, where \(k(s)\) and \(k(t)\) are the out-degree and in-degree (or out-degree if undirected) of vertices \(s\) and \(t\). However, if set_fast_edge_lookup() is set to True, this operation becomes \(O(m)\), where \(m\) is the number of parallel edges.

Note

The order of the edges is identical to edge().

Examples

>>> g = gt.Graph([(0, 1), (0, 1)])
>>> g.get_edge_range(0, 1, [g.edge_index])
array([[0],
       [1]])

Obtaining vertex and edge descriptors

vertex(i, use_index=True, add_missing=False)[git][source]#

Return the vertex with index i. If use_index=False, the i-th vertex is returned (which can differ from the vertex with index i in case of filtered graphs).

If add_missing == True, and the vertex does not exist in the graph, the necessary number of missing vertices are inserted, and the new vertex is returned.

edge(s, t, all_edges=False, add_missing=False)[git][source]#

Return the edge from vertex s to t, if it exists. If all_edges=True then a list is returned with all the parallel edges from s to t, otherwise only one edge is returned.

If add_missing == True, a new edge is created and returned, if none currently exists.

This operation normally will take \(O(\min(k(s), k(t)))\) time, where \(k(s)\) and \(k(t)\) are the out-degree and in-degree (or out-degree if undirected) of vertices \(s\) and \(t\). However, if set_fast_edge_lookup() is set to True, this operation becomes \(O(1)\).

set_fast_edge_lookup(fast=True)[git][source]#

If fast == True the fast \(O(1)\) lookup of edges will be enabled. This requires an additional data structure of size \(O(E)\) to be kept at all times. If fast == False, this data structure is destroyed.

get_fast_edge_lookup()[git][source]#

Return whether the fast \(O(1)\) lookup of edges is currently enabled.

Number of vertices and edges

num_vertices(ignore_filter=False)[git][source]#

Get the number of vertices.

If ignore_filter == True, vertex filters are ignored.

Note

If the vertices are being filtered, and ignore_filter == False, this operation is \(O(V)\). Otherwise it is \(O(1)\).

num_edges(ignore_filter=False)[git][source]#

Get the number of edges.

If ignore_filter == True, edge filters are ignored.

Note

If the edges are being filtered, and ignore_filter == False, this operation is \(O(E)\). Otherwise it is \(O(1)\).

Modifying vertices and edges

The following functions allow for addition and removal of vertices in the graph.

add_vertex(n=1)[git][source]#

Add a vertex to the graph, and return it. If n != 1, n vertices are inserted and an iterator over the new vertices is returned. This operation is \(O(n)\).

remove_vertex(vertex, fast=False)[git][source]#

Remove a vertex from the graph. If vertex is an iterable, it should correspond to a sequence of vertices to be removed.

Note

If the option fast == False is given, this operation is \(O(V + E)\) (this is the default). Otherwise it is \(O(k + k_{\text{last}})\), where \(k\) is the (total) degree of the vertex being deleted, and \(k_{\text{last}}\) is the (total) degree of the vertex with the largest index.

Warning

This operation may invalidate vertex descriptors. Vertices are always indexed contiguously in the range \([0, N-1]\), hence vertex descriptors with an index higher than vertex will be invalidated after removal (if fast == False, otherwise only descriptors pointing to vertices with the largest index will be invalidated).

Because of this, the only safe way to remove more than one vertex at once is to sort them in decreasing index order:

# 'del_list' is a list of vertex descriptors
for v in reversed(sorted(del_list)):
    g.remove_vertex(v)

Alternatively (and preferably), a list (or iterable) may be passed directly as the vertex parameter, and the above is performed internally (in C++).

Warning

If fast == True, the vertex being deleted is ‘swapped’ with the last vertex (i.e. with the largest index), which will in turn inherit the index of the vertex being deleted. All property maps associated with the graph will be properly updated, but the index ordering of the graph will no longer be the same.

The following functions allow for addition and removal of edges in the graph.

add_edge(source, target, add_missing=True)[git][source]#

Add a new edge from source to target to the graph, and return it. This operation is \(O(1)\).

If add_missing == True, the source and target vertices are included in the graph if they don’t yet exist.

remove_edge(edge)[git][source]#

Remove an edge from the graph.

Note

This operation is normally \(O(k_s + k_t)\), where \(k_s\) and \(k_t\) are the total degrees of the source and target vertices, respectively. However, if set_fast_edge_removal() is set to True, this operation becomes \(O(1)\).

Warning

The relative ordering of the remaining edges in the graph is kept unchanged, unless set_fast_edge_removal() is set to True, in which case it can change.

add_edge_list(edge_list, hashed=False, hash_type='string', eprops=None, parallel=True)[git][source]#

Add a list of edges to the graph, given by edge_list, which can be an iterator of (source, target) pairs where both source and target are vertex indices (or can be so converted), or a numpy.ndarray of shape (E,2), where E is the number of edges, and each line specifies a (source, target) pair. If the list references vertices which do not exist in the graph, they will be created.

Optionally, if hashed == True, the vertex values in the edge list are not assumed to correspond to vertex indices directly. In this case they will be mapped to vertex indices according to the order in which they are encountered, and a vertex property map with the vertex values is returned. The option hash_type will determine the expected type used by the hash keys, and they can be any property map value type (see PropertyMap), unless edge_list is a numpy.ndarray, in which case the value of this option is ignored, and the type is determined automatically.

If hashed == False and the target value of an edge corresponds to the maximum integer value (sys.maxsize, or the maximum integer type of the numpy.ndarray object), or is a numpy.nan or numpy.inf value, then only the source vertex will be added to the graph.

If hashed == True, and the target value corresponds to None, then only the source vertex will be added to the graph.

If given, eprops should specify an iterable containing edge property maps that will be filled with the remaining values at each row, if there are more than two. Alternatively, eprops can contain a list of (name, value_type) pairs, in which case new internal edge property maps will be created with the corresponding name and value type.

If parallel == True, edge_list is a numpy.ndarray, and hashed == False, the edges are inserted concurrently by several threads (if OpenMP is enabled with more than one thread), and hence their indices, and their order in the adjacency lists, depend on the scheduling of the threads (the property values given in edge_list remain attached to the correct edges). If parallel == False, the edges are inserted one by one in the order of edge_list, so that, if the graph has no free edge indices left by removed edges, the edge indices follow the positions in the list.

Note

If edge_list is a numpy.ndarray object, the execution of this function will be done entirely in C++, and hence much faster.

Examples

>>> edge_list = [(0, 1, .3, 10), (2, 3, .1, 0), (2, 0, .4, 42)]
>>> g = gt.Graph()
>>> eweight = g.new_ep("double")
>>> elayer = g.new_ep("int")
>>> g.add_edge_list(edge_list, eprops=[eweight, elayer])
>>> print(eweight.fa)
[0.3 0.1 0.4]
>>> g.get_edges()
array([[0, 1],
       [2, 3],
       [2, 0]])
set_fast_edge_removal(fast=True)[git][source]#

If fast == True the fast \(O(1)\) removal of edges will be enabled. This requires an additional data structure of size \(O(E)\) to be kept at all times. If fast == False, this data structure is destroyed.

get_fast_edge_removal()[git][source]#

Return whether the fast \(O(1)\) removal of edges is currently enabled.

The following functions allow for easy removal of vertices and edges from the graph.

clear()[git][source]#

Remove all vertices and edges from the graph.

clear_vertex(vertex)[git][source]#

Remove all in and out-edges from the given vertex.

clear_edges()[git][source]#

Remove all edges from the graph.

After the removal of many edges and/or vertices, the underlying containers may have a capacity that significantly exceeds the size of the graph. The function below corrects this.

shrink_to_fit()[git][source]#

Force the physical capacity of the underlying containers to match the graph’s actual size, potentially freeing memory back to the system.

Directedness and reversal of edges

Note

These functions do not actually modify the graph, and are fully reversible. They are also very cheap, with an \(O(1)\) complexity.

set_directed(is_directed)[git][source]#

Set the directedness of the graph.

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Changing directedness will invalidate existing vertex and edge descriptors, which will still point to the original graph.

is_directed()[git][source]#

Get the directedness of the graph.

set_reversed(is_reversed)[git][source]#

Reverse the direction of the edges, if is_reversed is True, or maintain the original direction otherwise.

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Reversing the graph will invalidate existing vertex and edge descriptors, which will still point to the original graph.

is_reversed()[git][source]#

Return True if the edges are reversed, and False otherwise.

Creation of new property maps

new_property(key_type, value_type, vals=None, val=None)[git][source]#

Create a new (uninitialized) property map of key type key_type (v, e, or g), value type value_type, and return it. If provided, the values will be initialized by vals, which should be a sequence, or by val which should be a single value.

new_vertex_property(value_type, vals=None, val=None)[git][source]#

Create a new vertex property map of type value_type, and return it. If provided, the values will be initialized by vals, which should be a sequence in vertex index order (the same as fa), or by val which should be a single value.

new_vp(value_type, vals=None, val=None)[git]#

Alias to new_vertex_property().

new_edge_property(value_type, vals=None, val=None)[git][source]#

Create a new edge property map of type value_type, and return it. If provided, the values will be initialized by vals, which should be a sequence in edge index order (the same as fa), or by val which should be a single value.

new_ep(value_type, vals=None, val=None)[git]#

Alias to new_edge_property().

new_graph_property(value_type, val=None)[git][source]#

Create a new graph property map of type value_type, and return it. If val is not None, the property is initialized to its value.

new_gp(value_type, val=None)[git]#

Alias to new_graph_property().

New property maps can be created by copying already existing ones.

copy_property(src, tgt=None, value_type=None, g=None, full=True)[git][source]#

Copy contents of src property to tgt property. If tgt is None, then a new property map of the same type (or with the type given by the optional value_type parameter) is created, and returned. The optional parameter g specifies the source graph to copy properties from (defaults to the graph that owns src). If full == False, then in the case of filtered graphs only the unmasked values are copied (with the remaining ones taking the type-dependent default value).

Note

In case the source property map belongs to different graphs, this function behaves as follows.

For vertex properties, the source and target graphs must have the same number of vertices, and the properties are copied according to the index values.

For edge properties, the edge index is not important, and the properties are copied by matching edges between the different graphs according to the source and target vertex indices. In case the graph has parallel edges with the same source and target vertices, they are matched according to their iteration order. The edge sets do not have to be the same between source and target graphs, as the copying occurs only for edges that lie at their intersection.

degree_property_map(deg, weight=None)[git][source]#

Create and return a vertex property map containing the degree type given by deg, which can be any of "in", "out", or "total". If provided, weight should be an edge EdgePropertyMap containing the edge weights which should be summed.

Index property maps

vertex_index[git]#

Vertex index map.

It maps for each vertex in the graph a unique integer in the range [0, num_vertices() - 1].

Note

Like edge_index, this is a special instance of a VertexPropertyMap class, which is immutable, and cannot be accessed as an array.

edge_index[git]#

Edge index map.

It maps for each edge in the graph a unique integer.

Note

Like vertex_index, this is a special instance of a EdgePropertyMap class, which is immutable, and cannot be accessed as an array.

Additionally, the indices may not necessarily lie in the range [0, num_edges() - 1]. However this will always happen whenever no edges are deleted from the graph.

edge_index_range[git]#

The size of the range of edge indices.

reindex_edges()[git][source]#

Reset the edge indices so that they lie in the [0, num_edges() - 1] range. The index ordering will be compatible with the sequence returned by the edges() function.

Warning

Calling this function will invalidate all existing edge property maps, if the index ordering is modified! The property maps will still be usable, but their contents will still be tied to the old indices, and thus may become scrambled.

Internal property maps

Internal property maps are just like regular property maps, with the only exception that they are saved and loaded to/from files together with the graph itself. See internal property maps for more details.

Note

All dictionaries below are mutable. However, any dictionary returned below is only an one-way proxy to the internally-kept properties. If you modify this object, the change will be propagated to the internal dictionary, but not vice-versa. Keep this in mind if you intend to keep a copy of the returned object.

properties[git]#

Dictionary of internal properties. Keys must always be a tuple, where the first element is a string from the set {'v', 'e', 'g'}, representing a vertex, edge, or graph property, respectively, and the second element is the name of the property map.

Examples

>>> g = gt.Graph()
>>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
>>> del g.properties[("e", "foo")]
vertex_properties[git]#

Dictionary of internal vertex properties. The keys are the property names.

vp[git]#

Alias to vertex_properties.

edge_properties[git]#

Dictionary of internal edge properties. The keys are the property names.

ep[git]#

Alias to edge_properties.

graph_properties[git]#

Dictionary of internal graph properties. The keys are the property names.

gp[git]#

Alias to graph_properties.

own_property(prop)[git][source]#

Return a version of the property map ‘prop’ (possibly belonging to another graph) which is owned by the current graph.

list_properties()[git][source]#

Print a list of all internal properties.

Examples

>>> g = gt.Graph()
>>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>")
>>> g.vertex_properties["foo"] = g.new_vertex_property("double")
>>> g.vertex_properties["bar"] = g.new_vertex_property("python::object")
>>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!")
>>> g.list_properties()
gnat           (graph)   (type: string, val: hi there!)
bar            (vertex)  (type: python::object)
foo            (vertex)  (type: double)
foo            (edge)    (type: vector<double>)

Filtering of vertices and edges.

See Graph filtering for more details.

Note

These functions do not actually modify the graph, and are fully reversible. They are also very cheap, and have an \(O(1)\) complexity.

set_filters(eprop, vprop)[git][source]#

Set the boolean properties for edge and vertex filters, respectively. Only the vertices and edges with value different than False are kept in the filtered graph. If any of the supplied properties is None, an empty filter is constructed which allows all edges or vertices. If both are None, the graph is returned to the unfiltered state, as with clear_filters().

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Setting vertex or edge filters will invalidate existing vertex and edge descriptors, which will still point to the unfiltered graph.

set_vertex_filter(prop)[git][source]#

Set the vertex boolean filter property. Only the vertices with value different than False are kept in the filtered graph. If the supplied property is None, the filter is replaced by a uniform filter allowing all vertices.

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Setting vertex filters will invalidate existing vertex and edge descriptors, which will still point to the unfiltered graph.

get_vertex_filter()[git][source]#

Return the vertex filter property.

set_edge_filter(prop)[git][source]#

Set the edge boolean filter property. Only the edges with value different than False are kept in the filtered graph. If the supplied property is None, the filter is replaced by a uniform filter allowing all edges.

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Setting edge filters will invalidate existing vertex and edge descriptors, which will still point to the unfiltered graph.

get_edge_filter()[git][source]#

Return the edge filter property map.

clear_filters()[git][source]#

Remove vertex and edge filters, and set the graph to the unfiltered state.

Note

This is a \(O(1)\) operation that does not modify the storage of the graph.

Warning

Clearing vertex and edge filters will invalidate existing vertex and edge descriptors.

Warning

The purge functions below irreversibly remove the filtered vertices or edges from the graph. Note that, contrary to the functions above, these are \(O(V)\) and \(O(E)\) operations, respectively.

purge_vertices(in_place=False, parallel=True)[git][source]#

Remove all vertices of the graph which are currently being filtered out. This operation is not reversible.

If the option in_place == True is given, the algorithm will remove the filtered vertices and re-index all property maps which are tied with the graph. This is a slow operation which has an \(O(V^2)\) complexity.

If in_place == False, the graph and its vertex and edge property maps are temporarily copied to a new unfiltered graph, which will replace the contents of the original graph. This is a fast operation with an \(O(V + E)\) complexity. This is the default behaviour if no option is given.

If parallel == False, the operation runs with a single thread. The result is the same in either case.

Note

The graph will remain in a filtered state after this operation, since there might be edge filters present. To return the graph to an unfiltered state, use clear_filters().

purge_edges(parallel=True)[git][source]#

Remove all edges of the graph which are currently being filtered out. This operation is not reversible.

If parallel == False, the operation runs with a single thread. The result is the same in either case.

Note

The graph will remain in a filtered state after this operation, since there might be vertex filters present. To return the graph to an unfiltered state, use clear_filters().

I/O operations

See Graph I/O for more details.

load(file_name, fmt='auto', ignore_vp=None, ignore_ep=None, ignore_gp=None)[git][source]#

Load a graph from a file into this graph, replacing its vertices, edges, and property maps.

Parameters:
file_namestr or file-like object

Name of the file, or a file-like object (opened in binary mode).

fmtstr (optional, default: "auto")

File format, as given in the table below. If "auto", the format is given by the extension of file_name, or is "gt" for file-like objects.

ignore_vplist of str (optional, default: None)

Names of the vertex property maps that are not read.

ignore_eplist of str (optional, default: None)

Names of the edge property maps that are not read.

ignore_gplist of str (optional, default: None)

Names of the graph property maps that are not read.

See also

load_graph

Load a new graph from a file

Notes

The vertices, edges, and property maps of the graph are replaced by those of the file. All property maps of the graph are removed before it is loaded, since they refer to its previous vertices and edges, and so are its vertex and edge filters and its reversal, which are then restored from the file if the format stores them (see the table below). A new graph is loaded from a file with load_graph().

The format is given by fmt, or, if fmt is "auto", by the extension of the file name, according to the following table:

fmt

Extension

Format

"gt"

.gt

Binary format of graph-tool (see Sec. The gt file format)

"graphml"

.graphml, .xml

GraphML ("xml" is a synonym)

"dot"

.dot

Graphviz DOT

"gml"

.gml

GML

"gexf"

.gexf

GEXF (Gephi)

"pajek"

.net

Pajek

"json"

.json

JSON node-link

"cytoscape_json"

.cyjs

Cytoscape JSON

"adjacency_json"

JSON adjacency

"tree_json"

JSON tree, of directed trees

"mtx"

.mtx

Matrix Market

"graph6"

.g6

graph6 (nauty)

"sparse6"

.s6

sparse6 (nauty)

"digraph6"

.d6

digraph6 (nauty)

"metis"

.graph, .metis

METIS

"paj"

.paj

Pajek project, with a network, partitions, and vectors

"ncol"

.ncol

NCOL (Large Graph Layout)

"lgl"

.lgl

LGL (Large Graph Layout)

"edgelist"

.edgelist, .edges, .edge

Edge list

"adjlist"

.adjlist

Adjacency list

"multiline_adjlist"

Multiline adjacency list

"adjacency"

.adj

Adjacency matrix as text

"dl"

.dl

UCINET DL, in the fullmatrix, edgelist1, and nodelist1 formats

"leda"

.gw, .leda, .lgr

LEDA

"graphdb"

.graphdb

GraphDB, the binary format of the ARG database (DOI: 10.1016/S0167-8655(02)00253-2 [sci-hub, @tor])

"dimacs"

.dimacs, .max, .col

DIMACS maximum flow (p max) and edge (p edge) problems

"network_text"

Network text, a drawing of the graph as text, which can only be saved

A file name that ends in .gz, .bz2, .xz, or .zst, after the extension of the format, is compressed when the graph is saved and decompressed when it is loaded, with gzip, bzip2, xz, or zstd, respectively, while a file-like object is neither compressed nor decompressed.

Only the "gt" format stores every property map with its value type, together with the state of the graph, i.e. its vertex and edge filters, whether it is reversed, and whether fast edge removal and lookup are enabled (see Sec. Reserved property maps). It is also the fastest and most compact format. The other formats store only part of the property maps or of the state, as summarized in the following table, where “all” stands for the vertex, edge, and graph property maps:

fmt

Property maps

State

"gt"

All, with their value types

All

"graphml"

All, with their value types, except the vertex and edge index maps, which are not stored, and the property maps whose values are all empty, which are not restored

All

"dot"

The vertex and edge property maps, as text that is read back as strings, with the vertex property map vertex_name as the names of the vertices

None

"gml"

All, the scalar values as numbers that are read back as double, and the other values as text that is read back as strings, except the graph property map directed, the vertex property map id, and the edge property maps id, source, and target, whose names are keys of the format and which cannot be saved

None

"gexf"

The vertex and edge property maps, with their value types (the property maps pos, color, size, thickness, and shape as visualization data), and the graph property maps description and keywords

None

"pajek"

The vertex property maps label, pos, and shape, the edge property map weight, the other vertex and edge property maps as text that is read back as strings (on vertex lines without a shape, after Pajek’s default shape ellipse, which is read back as well), and the graph property map name

None

"json"

All, as JSON values that are read back as bool, int64_t, double, string, vectors of these, or python::object

None

"cytoscape_json", "adjacency_json"

Those of "json"

None

"tree_json"

The vertex property maps, as in "json"

None

"mtx"

The edge property map weight, with integer, floating point, or complex values (the latter as vectors of two floating point values)

None

"graph6", "sparse6", "digraph6"

None

None

"metis"

The integer vertex property maps size and weight, and the integer edge property map weight

None

"paj"

Those of "pajek", with the integer and floating point vertex property maps as partitions and vectors, which are read back as int64_t and double

None

"ncol", "lgl"

The vertex property map name, as text, and the scalar edge property map weight, which is read back as double

None

"edgelist", "multiline_adjlist"

The vertex property map name, as text, and the edge property maps whose values are Python literals, read back as bool, int64_t, double, string, vectors of these, or python::object

None

"adjlist"

The vertex property map name, as text

None

"adjacency"

The sums of the values of the scalar edge property map weight, or the numbers of edges

None

"dl"

The vertex property map name, as text, and the scalar edge property map weight

None

"leda"

The vertex property map label, and the edge property map weight (or label if there is no weight), with scalar or string values

None

"graphdb"

None

None

"dimacs"

For directed graphs, the scalar edge property map capacity and the graph property maps source and target, for undirected graphs, the scalar vertex property map weight

None

"network_text"

The vertex property maps label and collapse

None

When a filtered graph is saved by save() in the "gt" or "graphml" format with preserve_filter=True (the default), all its vertices and edges are stored, together with the filters, so that the loaded graph is filtered in the same way, and the filtered-out vertices and edges can be recovered by removing the filters; a reversed graph is likewise loaded reversed. With preserve_filter=False, or in any other format, the graph is stored as it is seen instead, i.e. only the vertices and edges that are not filtered out, with the vertices renumbered consecutively, and the edges of a reversed graph in their reversed direction. In neither case is the graph copied. The "graph6" format can only store undirected graphs without self-loops or parallel edges, the "sparse6" and "metis" formats only undirected graphs, and the "digraph6" format only directed graphs without parallel edges. Saving other graphs in these formats raises a ValueError, as does saving a graph with more than 65535 vertices, or with a vertex with more than 65535 edges, in the "graphdb" format. Directed graphs are saved in the "dimacs" format as maximum flow problems (with unit capacities if there is no edge property map capacity), and undirected graphs as edge problems. Only the first network of a file in the "paj" format is loaded, with the partitions and vectors of the same number of vertices. Since the "dot" and "gml" formats do not escape backslashes, a string value that ends in a backslash produces a file that cannot be read back.

The formats of other programs that do not state whether the graph is directed ("ncol", "lgl", "edgelist", "adjlist", "multiline_adjlist", "adjacency", "dl", and "graphdb") are handled as follows. The lists of edges and the adjacency lists contain each edge of an undirected graph once, and are read as undirected graphs, whose edges keep the direction in which they appear in the file, so that a directed graph is obtained with set_directed(). The formats that describe an adjacency matrix ("adjacency", "dl", and "graphdb") contain each edge of an undirected graph in both directions (and each self-loop once), and are read as undirected graphs if the matrix is symmetric, and as directed graphs otherwise, so that a directed graph with a symmetric adjacency matrix is read as an undirected graph. In the "adjacency" format, integer entries are numbers of edges, and other values are edge weights, which are read into the edge property map weight, while in the "dl" format the nonzero entries are edge weights, unless they are all equal to one.

The vertices are identified in the "ncol", "lgl", "edgelist", "adjlist", "multiline_adjlist", and "dl" formats by the values of the vertex property map name, which must be distinct and contain no whitespace or # (nor , or " in the "dl" format), or by their indices if there is no such property map. When such a file is loaded, the identifiers are stored in the vertex property map name, with the vertices numbered in the order of their first appearance (the vertices with lines of their own first), except that non-negative integer identifiers are the vertex indices themselves in the "edgelist", "adjlist", and "multiline_adjlist" formats, and that identifiers equal to the vertex indices are not stored. The "ncol" and "edgelist" formats do not contain the vertices without edges. The edge property maps of the "edgelist" and "multiline_adjlist" formats are stored as a Python dictionary for each edge, whose values may also be the floating point values nan and inf (which Python writes as such, but which are not Python literals).

The values of the property maps of type python::object are stored as their pickle by the "gt" and "graphml" formats, and loaded as the original objects. In the "gt" format, an object that appears in several values is stored only once and loaded as a single object, and references to the graph itself are loaded as references to the loaded graph (see Sec. Python objects). The "dot", "gml", "gexf", and "pajek" formats store the base64 encoding of the pickles as text, loaded as strings. The "json" format stores the objects as JSON values, so that they must be representable in JSON (a ValueError is raised otherwise), and it does not restore a property map whose values are all None.

The "cytoscape_json", "adjacency_json", and "tree_json" formats store the property maps as the "json" format does, and identify the vertices by the values of the vertex property map value in the "cytoscape_json" format and id in the other two (or by their indices if there is no such property map), which are read back into these property maps unless they are the vertex indices. The "tree_json" format can only store directed trees whose edges point away from the root, and is loaded with the vertices numbered in depth-first order. The edges of a graph with parallel edges are stored by the "cytoscape_json" and "adjacency_json" formats with keys, which are the values of the edge property map key, if there is one, and otherwise the numbers of the previous edges with the same endpoints, so that they are read back into this property map only in the first case. The "network_text" format is a drawing of the graph as a forest of trees in text, drawn with box-drawing characters, where the vertices are labelled by the values of the vertex property map label, or by their indices, and the trees below the vertices with a true value of the vertex property map collapse are omitted; it cannot be loaded.

Warning

Unpickling can execute arbitrary code. Files with property maps of type python::object should therefore only be loaded from trusted sources.

save(file_name, fmt='auto', preserve_filter=True, nthreads=None)[git][source]#

Save the graph to a file, with all its property maps.

Parameters:
file_namestr or file-like object

Name of the file, or a file-like object (opened in binary mode).

fmtstr (optional, default: "auto")

File format, as given in the table below. If "auto", the format is given by the extension of file_name, or is "gt" for file-like objects.

preserve_filterbool (optional, default: True)

If True, a filtered graph is saved in the "gt" and "graphml" formats with all its vertices and edges, together with its filters. Otherwise, or in the other formats, only the vertices and edges that are not filtered out are saved.

nthreadsint (optional, default: None)

Number of threads of the xz and zstd compression. If None, the number given by openmp_get_num_threads() is used, or a single thread if graph-tool was compiled without OpenMP.

See also

load_graph

Load a graph from a file

Notes

Warning

Only the "gt" and "graphml" formats store the filters of a filtered graph and the reversal of a reversed graph. In all the other formats, the graph is saved as it is seen, i.e. without its filtered-out vertices and edges, and with the edges of a reversed graph in their reversed direction, so that loading the file gives only this graph, and the original graph cannot be recovered from it.

The format is given by fmt, or, if fmt is "auto", by the extension of the file name, according to the following table:

fmt

Extension

Format

"gt"

.gt

Binary format of graph-tool (see Sec. The gt file format)

"graphml"

.graphml, .xml

GraphML ("xml" is a synonym)

"dot"

.dot

Graphviz DOT

"gml"

.gml

GML

"gexf"

.gexf

GEXF (Gephi)

"pajek"

.net

Pajek

"json"

.json

JSON node-link

"cytoscape_json"

.cyjs

Cytoscape JSON

"adjacency_json"

JSON adjacency

"tree_json"

JSON tree, of directed trees

"mtx"

.mtx

Matrix Market

"graph6"

.g6

graph6 (nauty)

"sparse6"

.s6

sparse6 (nauty)

"digraph6"

.d6

digraph6 (nauty)

"metis"

.graph, .metis

METIS

"paj"

.paj

Pajek project, with a network, partitions, and vectors

"ncol"

.ncol

NCOL (Large Graph Layout)

"lgl"

.lgl

LGL (Large Graph Layout)

"edgelist"

.edgelist, .edges, .edge

Edge list

"adjlist"

.adjlist

Adjacency list

"multiline_adjlist"

Multiline adjacency list

"adjacency"

.adj

Adjacency matrix as text

"dl"

.dl

UCINET DL, in the fullmatrix, edgelist1, and nodelist1 formats

"leda"

.gw, .leda, .lgr

LEDA

"graphdb"

.graphdb

GraphDB, the binary format of the ARG database (DOI: 10.1016/S0167-8655(02)00253-2 [sci-hub, @tor])

"dimacs"

.dimacs, .max, .col

DIMACS maximum flow (p max) and edge (p edge) problems

"network_text"

Network text, a drawing of the graph as text, which can only be saved

A file name that ends in .gz, .bz2, .xz, or .zst, after the extension of the format, is compressed when the graph is saved and decompressed when it is loaded, with gzip, bzip2, xz, or zstd, respectively, while a file-like object is neither compressed nor decompressed.

Only the "gt" format stores every property map with its value type, together with the state of the graph, i.e. its vertex and edge filters, whether it is reversed, and whether fast edge removal and lookup are enabled (see Sec. Reserved property maps). It is also the fastest and most compact format. The other formats store only part of the property maps or of the state, as summarized in the following table, where “all” stands for the vertex, edge, and graph property maps:

fmt

Property maps

State

"gt"

All, with their value types

All

"graphml"

All, with their value types, except the vertex and edge index maps, which are not stored, and the property maps whose values are all empty, which are not restored

All

"dot"

The vertex and edge property maps, as text that is read back as strings, with the vertex property map vertex_name as the names of the vertices

None

"gml"

All, the scalar values as numbers that are read back as double, and the other values as text that is read back as strings, except the graph property map directed, the vertex property map id, and the edge property maps id, source, and target, whose names are keys of the format and which cannot be saved

None

"gexf"

The vertex and edge property maps, with their value types (the property maps pos, color, size, thickness, and shape as visualization data), and the graph property maps description and keywords

None

"pajek"

The vertex property maps label, pos, and shape, the edge property map weight, the other vertex and edge property maps as text that is read back as strings (on vertex lines without a shape, after Pajek’s default shape ellipse, which is read back as well), and the graph property map name

None

"json"

All, as JSON values that are read back as bool, int64_t, double, string, vectors of these, or python::object

None

"cytoscape_json", "adjacency_json"

Those of "json"

None

"tree_json"

The vertex property maps, as in "json"

None

"mtx"

The edge property map weight, with integer, floating point, or complex values (the latter as vectors of two floating point values)

None

"graph6", "sparse6", "digraph6"

None

None

"metis"

The integer vertex property maps size and weight, and the integer edge property map weight

None

"paj"

Those of "pajek", with the integer and floating point vertex property maps as partitions and vectors, which are read back as int64_t and double

None

"ncol", "lgl"

The vertex property map name, as text, and the scalar edge property map weight, which is read back as double

None

"edgelist", "multiline_adjlist"

The vertex property map name, as text, and the edge property maps whose values are Python literals, read back as bool, int64_t, double, string, vectors of these, or python::object

None

"adjlist"

The vertex property map name, as text

None

"adjacency"

The sums of the values of the scalar edge property map weight, or the numbers of edges

None

"dl"

The vertex property map name, as text, and the scalar edge property map weight

None

"leda"

The vertex property map label, and the edge property map weight (or label if there is no weight), with scalar or string values

None

"graphdb"

None

None

"dimacs"

For directed graphs, the scalar edge property map capacity and the graph property maps source and target, for undirected graphs, the scalar vertex property map weight

None

"network_text"

The vertex property maps label and collapse

None

When a filtered graph is saved by save() in the "gt" or "graphml" format with preserve_filter=True (the default), all its vertices and edges are stored, together with the filters, so that the loaded graph is filtered in the same way, and the filtered-out vertices and edges can be recovered by removing the filters; a reversed graph is likewise loaded reversed. With preserve_filter=False, or in any other format, the graph is stored as it is seen instead, i.e. only the vertices and edges that are not filtered out, with the vertices renumbered consecutively, and the edges of a reversed graph in their reversed direction. In neither case is the graph copied. The "graph6" format can only store undirected graphs without self-loops or parallel edges, the "sparse6" and "metis" formats only undirected graphs, and the "digraph6" format only directed graphs without parallel edges. Saving other graphs in these formats raises a ValueError, as does saving a graph with more than 65535 vertices, or with a vertex with more than 65535 edges, in the "graphdb" format. Directed graphs are saved in the "dimacs" format as maximum flow problems (with unit capacities if there is no edge property map capacity), and undirected graphs as edge problems. Only the first network of a file in the "paj" format is loaded, with the partitions and vectors of the same number of vertices. Since the "dot" and "gml" formats do not escape backslashes, a string value that ends in a backslash produces a file that cannot be read back.

The formats of other programs that do not state whether the graph is directed ("ncol", "lgl", "edgelist", "adjlist", "multiline_adjlist", "adjacency", "dl", and "graphdb") are handled as follows. The lists of edges and the adjacency lists contain each edge of an undirected graph once, and are read as undirected graphs, whose edges keep the direction in which they appear in the file, so that a directed graph is obtained with set_directed(). The formats that describe an adjacency matrix ("adjacency", "dl", and "graphdb") contain each edge of an undirected graph in both directions (and each self-loop once), and are read as undirected graphs if the matrix is symmetric, and as directed graphs otherwise, so that a directed graph with a symmetric adjacency matrix is read as an undirected graph. In the "adjacency" format, integer entries are numbers of edges, and other values are edge weights, which are read into the edge property map weight, while in the "dl" format the nonzero entries are edge weights, unless they are all equal to one.

The vertices are identified in the "ncol", "lgl", "edgelist", "adjlist", "multiline_adjlist", and "dl" formats by the values of the vertex property map name, which must be distinct and contain no whitespace or # (nor , or " in the "dl" format), or by their indices if there is no such property map. When such a file is loaded, the identifiers are stored in the vertex property map name, with the vertices numbered in the order of their first appearance (the vertices with lines of their own first), except that non-negative integer identifiers are the vertex indices themselves in the "edgelist", "adjlist", and "multiline_adjlist" formats, and that identifiers equal to the vertex indices are not stored. The "ncol" and "edgelist" formats do not contain the vertices without edges. The edge property maps of the "edgelist" and "multiline_adjlist" formats are stored as a Python dictionary for each edge, whose values may also be the floating point values nan and inf (which Python writes as such, but which are not Python literals).

The values of the property maps of type python::object are stored as their pickle by the "gt" and "graphml" formats, and loaded as the original objects. In the "gt" format, an object that appears in several values is stored only once and loaded as a single object, and references to the graph itself are loaded as references to the loaded graph (see Sec. Python objects). The "dot", "gml", "gexf", and "pajek" formats store the base64 encoding of the pickles as text, loaded as strings. The "json" format stores the objects as JSON values, so that they must be representable in JSON (a ValueError is raised otherwise), and it does not restore a property map whose values are all None.

The "cytoscape_json", "adjacency_json", and "tree_json" formats store the property maps as the "json" format does, and identify the vertices by the values of the vertex property map value in the "cytoscape_json" format and id in the other two (or by their indices if there is no such property map), which are read back into these property maps unless they are the vertex indices. The "tree_json" format can only store directed trees whose edges point away from the root, and is loaded with the vertices numbered in depth-first order. The edges of a graph with parallel edges are stored by the "cytoscape_json" and "adjacency_json" formats with keys, which are the values of the edge property map key, if there is one, and otherwise the numbers of the previous edges with the same endpoints, so that they are read back into this property map only in the first case. The "network_text" format is a drawing of the graph as a forest of trees in text, drawn with box-drawing characters, where the vertices are labelled by the values of the vertex property map label, or by their indices, and the trees below the vertices with a true value of the vertex property map collapse are omitted; it cannot be loaded.

Warning

Unpickling can execute arbitrary code. Files with property maps of type python::object should therefore only be loaded from trusted sources.