GraphView#

class graph_tool.GraphView(g, vfilt=None, efilt=None, directed=None, reversed=False, skip_properties=False, skip_vfilt=False, skip_efilt=False)[git][source]#

Bases: Graph

A view of selected vertices or edges of another graph.

This class uses shared data from another Graph instance, but allows for local filtering of vertices and/or edges, edge directionality or reversal. See Graph views for more details and examples.

The existence of a GraphView object does not affect the original graph, except if the graph view is modified (addition or removal of vertices or edges), in which case the modification is directly reflected in the original graph (and vice-versa), since they both point to the same underlying data. Because of this, instances of PropertyMap can be used interchangeably with a graph and its views.

The argument g must be an instance of a Graph class. If specified, vfilt and efilt select which vertices and edges are filtered, respectively. These parameters can either be a boolean-valued PropertyMap or numpy.ndarray, which specify which vertices/edges are selected, or a unary function that returns True if a given vertex/edge is to be selected, or False otherwise.

The boolean parameter directed can be used to set the directionality of the graph view. If directed is None, the directionality is inherited from g.

If reversed == True, the direction of the edges is reversed.

If vfilt or efilt is anything other than a PropertyMap instance, the instantiation running time is \(O(V)\) and \(O(E)\), respectively. Otherwise, the running time is \(O(1)\).

If either skip_properties, skip_vfilt, or skip_efilt is True, then the internal properties, vertex filter, or edge filter of the original graph are ignored, respectively.

Methods

add_edge(source, target[, add_missing])

Add a new edge from source to target to the graph, and return it.

add_edge_list(edge_list[, hashed, ...])

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.

add_vertex([n])

Add a vertex to the graph, and return it.

clear()

Remove all vertices and edges from the graph.

clear_edges()

Remove all edges from the graph.

clear_filters()

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

clear_vertex(vertex)

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

copy()

Return a deep copy of self.

copy_property(src[, tgt, value_type, g, full])

Copy contents of src property to tgt property.

degree_property_map(deg[, weight])

Create and return a vertex property map containing the degree type given by deg, which can be any of "in", "out", or "total".

edge(s, t[, all_edges, add_missing])

Return the edge from vertex s to t, if it exists.

edges()

Return an iterator over the edges.

get_all_edges(v[, eprops])

Return a numpy.ndarray containing the in- and out-edges of vertex v, and optional edge properties list eprops.

get_all_neighbors(v[, vprops])

Return a numpy.ndarray containing the in-neighbors and out-neighbors of vertex v, and optional vertex properties list vprops.

get_all_neighbours(v[, vprops])

Return a numpy.ndarray containing the in-neighbors and out-neighbors of vertex v, and optional vertex properties list vprops.

get_edge_filter()

Return the edge filter property map.

get_edge_range(s, t, eprops)

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

get_edges([eprops])

Return a numpy.ndarray containing the edges, and optional edge properties list eprops.

get_fast_edge_lookup()

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

get_fast_edge_removal()

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

get_filter_state()

Return a copy of the filter state of the graph.

get_in_degrees(vs[, eweight])

Return a numpy.ndarray containing the in-degrees of vertex list vs.

get_in_edges(v[, eprops])

Return a numpy.ndarray containing the in-edges of vertex v, and optional edge properties list eprops.

get_in_neighbors(v[, vprops])

Return a numpy.ndarray containing the in-neighbors of vertex v, and optional vertex properties list vprops.

get_in_neighbours(v[, vprops])

Return a numpy.ndarray containing the in-neighbors of vertex v, and optional vertex properties list vprops.

get_out_degrees(vs[, eweight])

Return a numpy.ndarray containing the out-degrees of vertex list vs.

get_out_edges(v[, eprops])

Return a numpy.ndarray containing the out-edges of vertex v, and optional edge properties list eprops.

get_out_neighbors(v[, vprops])

Return a numpy.ndarray containing the out-neighbors of vertex v, and optional vertex properties list vprops.

get_out_neighbours(v[, vprops])

Return a numpy.ndarray containing the out-neighbors of vertex v, and optional vertex properties list vprops.

get_total_degrees(vs[, eweight])

Return a numpy.ndarray containing the total degrees (i.e. in- plus out-degree) of vertex list vs.

get_vertex_filter()

Return the vertex filter property.

get_vertices([vprops])

Return a numpy.ndarray containing the vertex indices, and optional vertex properties list vprops.

is_directed()

Get the directedness of the graph.

is_reversed()

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

iter_all_edges(v[, eprops])

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

iter_all_neighbors(v[, vprops])

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

iter_all_neighbours(v[, vprops])

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

iter_edge_range(s, t, eprops)

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

iter_edges([eprops])

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

iter_in_edges(v[, eprops])

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

iter_in_neighbors(v[, vprops])

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

iter_in_neighbours(v[, vprops])

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

iter_out_edges(v[, eprops])

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

iter_out_neighbors(v[, vprops])

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

iter_out_neighbours(v[, vprops])

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

iter_vertices([vprops])

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

list_properties()

Print a list of all internal properties.

load(file_name[, fmt, ignore_vp, ignore_ep, ...])

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

new_edge_property(value_type[, vals, val])

Create a new edge property map of type value_type, and return it.

new_ep(value_type[, vals, val])

Alias to new_edge_property().

new_gp(value_type[, val])

Alias to new_graph_property().

new_graph_property(value_type[, val])

Create a new graph property map of type value_type, and return it.

new_property(key_type, value_type[, vals, val])

Create a new (uninitialized) property map of key type key_type (v, e, or g), value type value_type, and return it.

new_vertex_property(value_type[, vals, val])

Create a new vertex property map of type value_type, and return it.

new_vp(value_type[, vals, val])

Alias to new_vertex_property().

num_edges([ignore_filter])

Get the number of edges.

num_vertices([ignore_filter])

Get the number of vertices.

own_property(prop)

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

purge_edges([parallel])

Remove all edges of the graph which are currently being filtered out.

purge_vertices([in_place, parallel])

Remove all vertices of the graph which are currently being filtered out.

reindex_edges()

Reset the edge indices so that they lie in the [0, num_edges() - 1] range.

remove_edge(edge)

Remove an edge from the graph.

remove_vertex(vertex[, fast])

Remove a vertex from the graph.

save(file_name[, fmt, preserve_filter, nthreads])

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

set_directed(is_directed)

Set the directedness of the graph.

set_edge_filter(prop)

Set the edge boolean filter property.

set_fast_edge_lookup([fast])

If fast == True the fast \(O(1)\) lookup of edges will be enabled.

set_fast_edge_removal([fast])

If fast == True the fast \(O(1)\) removal of edges will be enabled.

set_filter_state(state)

Set the filter state of the graph.

set_filters(eprop, vprop)

Set the boolean properties for edge and vertex filters, respectively.

set_reversed(is_reversed)

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

set_vertex_filter(prop)

Set the vertex boolean filter property.

shrink_to_fit()

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

vertex(i[, use_index, add_missing])

Return the vertex with index i.

vertices()

Return an iterator over the vertices.

Attributes

base

Base graph.

edge_index

Edge index map.

edge_index_range

The size of the range of edge indices.

edge_properties

Dictionary of internal edge properties.

ep

Alias to edge_properties.

gp

Alias to graph_properties.

graph_properties

Dictionary of internal graph properties.

properties

Dictionary of internal properties.

vertex_index

Vertex index map.

vertex_properties

Dictionary of internal vertex properties.

vp

Alias to vertex_properties.

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

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.

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

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 by several threads (if OpenMP is enabled), otherwise they are inserted one by one. The resulting graph is the same in both cases, and does not depend on the number of threads: the edges are given the indices, and the positions in the adjacency lists, that they would get if they were inserted one by one in the order of edge_list (if the graph has no free edge indices left by removed edges, the edge indices are therefore the positions in the list, counted from the previous number of edges).

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]])
add_vertex(n=1)[git]#

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)\).

clear()[git]#

Remove all vertices and edges from the graph.

clear_edges()[git]#

Remove all edges from the graph.

clear_filters()[git]#

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.

clear_vertex(vertex)[git]#

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

copy()[git]#

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

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

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]#

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.

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

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)\).

edges()[git]#

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.

get_all_edges(v, eprops=[])[git]#

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_all_neighbors(v, vprops=[])[git]#

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_all_neighbours(v, vprops=[])[git]#

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_edge_filter()[git]#

Return the edge filter property map.

get_edge_range(s, t, eprops)[git]#

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]])
get_edges(eprops=[])[git]#

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_fast_edge_lookup()[git]#

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

get_fast_edge_removal()[git]#

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

get_filter_state()[git]#

Return a copy of the filter state of the graph.

get_in_degrees(vs, eweight=None)[git]#

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_in_edges(v, eprops=[])[git]#

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_in_neighbors(v, vprops=[])[git]#

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_in_neighbours(v, vprops=[])[git]#

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_out_degrees(vs, eweight=None)[git]#

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_out_edges(v, eprops=[])[git]#

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_out_neighbors(v, vprops=[])[git]#

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_out_neighbours(v, vprops=[])[git]#

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_total_degrees(vs, eweight=None)[git]#

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_vertex_filter()[git]#

Return the vertex filter property.

get_vertices(vprops=[])[git]#

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])
is_directed()[git]#

Get the directedness of the graph.

is_reversed()[git]#

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

iter_all_edges(v, eprops=[])[git]#

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_all_neighbors(v, vprops=[])[git]#

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_all_neighbours(v, vprops=[])[git]#

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]#

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]
iter_edges(eprops=[])[git]#

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_in_edges(v, eprops=[])[git]#

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_in_neighbors(v, vprops=[])[git]#

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_in_neighbours(v, vprops=[])[git]#

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_out_edges(v, eprops=[])[git]#

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_out_neighbors(v, vprops=[])[git]#

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_out_neighbours(v, vprops=[])[git]#

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_vertices(vprops=[])[git]#

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
list_properties()[git]#

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>)
load(file_name, fmt='auto', ignore_vp=None, ignore_ep=None, ignore_gp=None)[git]#

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.

Note

Only the "gt" and "graphml" formats preserve all the data of a graph in graph-tool: every vertex, edge, and graph property map, with its value type, and the filtering state of the graph (its vertex and edge filters, and whether it is reversed). The other formats store only part of the property maps, and none of the filtering state, as summarized in the second table below, so that a graph saved in them and loaded again is in general not identical to the original.

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

Compression

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.

Stored data

The "gt" and "graphml" formats also store whether fast edge removal and lookup are enabled (see Sec. Reserved property maps), and the "gt" format is the fastest and most compact one. What each format stores is summarized in the following table, where “all” stands for the vertex, edge, and graph property maps in the second column, and for the vertex and edge filters and the reversal in the third:

fmt

Property maps

Filtering 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

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

Filtered and reversed graphs

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.

Restrictions of the formats

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.

Formats without the direction of the graph

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.

Vertex identifiers

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. In the files of the "edgelist" and "multiline_adjlist" formats, the values of the edge property maps are written for each edge as a Python dictionary, whose keys are the names of the property maps, and which is read back into one edge property map per key; the values may also be the floating point values nan and inf (which Python writes as such, but which are not Python literals).

Python objects

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.

Warning

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

JSON and text formats

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.

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

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_gp(value_type, val=None)[git]#

Alias to new_graph_property().

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

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_property(key_type, value_type, vals=None, val=None)[git]#

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]#

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().

num_edges(ignore_filter=False)[git]#

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)\).

num_vertices(ignore_filter=False)[git]#

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)\).

own_property(prop)[git]#

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

purge_edges(parallel=True)[git]#

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().

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

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().

reindex_edges()[git]#

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.

remove_edge(edge)[git]#

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.

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

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.

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

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.

Note

Only the "gt" and "graphml" formats preserve all the data of a graph in graph-tool: every vertex, edge, and graph property map, with its value type, and the filtering state of the graph (its vertex and edge filters, and whether it is reversed). The other formats store only part of the property maps, and none of the filtering state, as summarized in the second table below, so that a graph saved in them and loaded again is in general not identical to the original.

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

Compression

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.

Stored data

The "gt" and "graphml" formats also store whether fast edge removal and lookup are enabled (see Sec. Reserved property maps), and the "gt" format is the fastest and most compact one. What each format stores is summarized in the following table, where “all” stands for the vertex, edge, and graph property maps in the second column, and for the vertex and edge filters and the reversal in the third:

fmt

Property maps

Filtering 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

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

Filtered and reversed graphs

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.

Restrictions of the formats

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.

Formats without the direction of the graph

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.

Vertex identifiers

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. In the files of the "edgelist" and "multiline_adjlist" formats, the values of the edge property maps are written for each edge as a Python dictionary, whose keys are the names of the property maps, and which is read back into one edge property map per key; the values may also be the floating point values nan and inf (which Python writes as such, but which are not Python literals).

Python objects

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.

Warning

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

JSON and text formats

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.

set_directed(is_directed)[git]#

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.

set_edge_filter(prop)[git]#

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.

set_fast_edge_lookup(fast=True)[git]#

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.

set_fast_edge_removal(fast=True)[git]#

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.

set_filter_state(state)[git]#

Set the filter state of the graph.

set_filters(eprop, vprop)[git]#

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_reversed(is_reversed)[git]#

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.

set_vertex_filter(prop)[git]#

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.

shrink_to_fit()[git]#

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

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

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.

vertices()[git]#

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)
base[git]#

Base graph.

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.

edge_properties[git]#

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

ep[git]#

Alias to edge_properties.

gp[git]#

Alias to graph_properties.

graph_properties[git]#

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

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_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.

vertex_properties[git]#

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

vp[git]#

Alias to vertex_properties.