graph_tool  efficient graph analysis and manipulation¶
Summary¶
Generic multigraph class. 

A view of selected vertices or edges of another graph. 

Vertex descriptor. 

Edge descriptor. 

This class provides a mapping from vertices to arbitrary properties. 

This class provides a mapping from edges to arbitrary properties. 

This class provides a mapping from graphs to arbitrary properties. 

This base class provides a mapping from vertices, edges or whole graphs to arbitrary properties. 

This is a 

Load a graph from 

Load a graph from a 

Group list of properties 

Ungroup vector property map 

Map the values of 

Propagate the prop values of vertices with value val to all their outneighbors. 

Return an edge property map corresponding to the vertex property prop of either the target and source of the edge, according to endpoint. 

Return a vertex property map corresponding to a specific operation (sum, product, min or max) on the edge property eprop of incident edges on each vertex, following the direction given by direction. 

Given a list of property maps props of the same type, a derived list of property maps with integral type htype is returned, where each value is replaced by a perfect (i.e. 

Return a list of possible properties value types. 

Return 

Return the number of OpenMP threads. 

Set the number of OpenMP threads. 

Return the runtime OpenMP schedule and chunk size. 

Set the runtime OpenMP schedule and chunk size. 

Show 
This module provides:
A
Graph
class for graph representation and manipulationProperty maps for Vertex, Edge or Graph.
Fast algorithms implemented in C++.
How to use the documentation¶
Documentation is available in two forms: docstrings provided with the code, and the full documentation available in the graphtool homepage.
We recommend exploring the docstrings using IPython, an advanced Python shell with TABcompletion and introspection capabilities.
The docstring examples assume that graph_tool.all
has been imported as
gt
:
>>> import graph_tool.all as gt
Code snippets are indicated by three greaterthan signs:
>>> x = x + 1
Use the builtin help
function to view a function’s docstring:
>>> help(gt.Graph)
Contents¶
Basic classes

class
graph_tool.
Graph
(g=None, directed=True, prune=False, vorder=None)[source]¶ Generic multigraph class.
This class encapsulates either a directed multigraph (default or if
directed=True
) or an undirected multigraph (ifdirected=False
), with optional internal edge, vertex or graph properties.If
g
is specified, the graph (and its internal properties) will be copied.If
prune
is set toTrue
, andg
is specified, 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 toprune
, to specify a different behavior to vertex, edge, and reversal filters, respectively.If
vorder
is specified, it should correspond to a vertexVertexPropertyMap
specifying the ordering of the vertices in the copied graph.The graph is implemented as an adjacency list, where both vertex and edge lists are C++ STL vectors.

copy
()[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.
Iteratorbased interface with descriptors:

vertices
()[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.Examples
>>> g = gt.Graph() >>> vlist = list(g.add_vertex(5)) >>> vlist2 = [] >>> for v in g.vertices(): ... vlist2.append(v) ... >>> assert(vlist == vlist2)

edges
()[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 afterreindex_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.
Iteratorbased interface without descriptors:

iter_vertices
(vprops=[])[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.Examples
>>> g = gt.Graph() >>> g.add_vertex(5) <...> >>> for v in g.iter_vertices(): ... print(v) 0 1 2 3 4

iter_edges
(eprops=[])[source]¶ Return an iterator over the edge
`(source, target)
pairs, and optional edge properties listeprops
.Note
This mode of iteration is more efficient than using
edges()
, as descriptor objects are not created.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=[])[source]¶ Return an iterator over the outedge
`(source, target)
pairs for vertexv
, and optional edge properties listeprops
.Note
This mode of iteration is more efficient than using
out_edges()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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=[])[source]¶ Return an iterator over the inedge
`(source, target)
pairs for vertexv
, and optional edge properties listeprops
.Note
This mode of iteration is more efficient than using
in_edges()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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=[])[source]¶ Return an iterator over the in and outedge
`(source, target)
pairs for vertexv
, and optional edge properties listeprops
.Note
This mode of iteration is more efficient than using
all_edges()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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=[])[source]¶ Return an iterator over the outneighbors of vertex
v
, and optional vertex properties listvprops
.Note
This mode of iteration is more efficient than using
out_neighbors()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> for u, i in g.iter_out_neighbors(66, [g.vp.uid]): ... print(u, i) 63 ['paul wilders <webmaster@wilders.org>'] 20369 ['ZhenXjell <zhenxjell@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=[])[source]¶ Return an iterator over the inneighbors of vertex
v
, and optional vertex properties listvprops
.Note
This mode of iteration is more efficient than using
in_neighbors()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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 ['ZhenXjell <zhenxjell@teamhelix.net>'] 38674 ['Howie L (howe81) <howe81@bigpond.net.au>']

iter_all_neighbors
(v, vprops=[])[source]¶ Return an iterator over the in and outneighbors of vertex
v
, and optional vertex properties listvprops
.Note
This mode of iteration is more efficient than using
all_neighbors()
, as descriptor objects are not created.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> for u, i in g.iter_all_neighbors(66, [g.vp.uid]): ... print(u, i) 63 ['paul wilders <webmaster@wilders.org>'] 20369 ['ZhenXjell <zhenxjell@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 ['ZhenXjell <zhenxjell@teamhelix.net>'] 38674 ['Howie L (howe81) <howe81@bigpond.net.au>']
Arraybased interface:

get_vertices
(vprops=[])[source]¶ Return a
numpy.ndarray
containing the vertex indices, and optional vertex properties listvprops
. Ifvprops
is not empty, the shape of the array will be(V, 1 + len(vprops))
, whereV
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=[])[source]¶ Return a
numpy.ndarray
containing the edges, and optional edge properties listeprops
. The shape of the array will be(E, 2 + len(eprops))
, whereE
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([[0, 3, 2], [1, 4, 1], [2, 5, 0]])

get_out_edges
(v, eprops=[])[source]¶ Return a
numpy.ndarray
containing the outedges of vertexv
, and optional edge properties listeprops
. The shape of the array will be(E, 2 + len(eprops))
, whereE
is the number of edges, and each line will contain the source, target and the edge property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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=[])[source]¶ Return a
numpy.ndarray
containing the inedges of vertexv
, and optional edge properties listeprops
. The shape of the array will be(E, 2 + len(eprops))
, whereE
is the number of edges, and each line will contain the source, target and the edge property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_in_edges(66, [g.edge_index]) array([[ 8687, 66, 179681], [ 20369, 66, 255033], [ 38674, 66, 300230]])

get_all_edges
(v, eprops=[])[source]¶ Return a
numpy.ndarray
containing the in and outedges of vertex v, and optional edge properties listeprops
. The shape of the array will be(E, 2 + len(eprops))
, whereE
is the number of edges, and each line will contain the source, target and the edge property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> 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=[])[source]¶ Return a
numpy.ndarray
containing the outneighbors of vertexv
, and optional vertex properties listvprops
. Ifvprops
is not empty, the shape of the array will be(V, 1 + len(eprops))
, whereV
is the number of vertices, and each line will contain a vertex and its property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_out_neighbors(66) array([ 63, 20369, 13980, 8687, 38674])

get_in_neighbors
(v, vprops=[])[source]¶ Return a
numpy.ndarray
containing the inneighbors of vertexv
, and optional vertex properties listvprops
. Ifvprops
is not empty, the shape of the array will be(V, 1 + len(eprops))
, whereV
is the number of vertices, and each line will contain a vertex and its property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_in_neighbors(66) array([ 8687, 20369, 38674])

get_all_neighbors
(v, vprops=[])[source]¶ Return a
numpy.ndarray
containing the inneighbors and outneighbors of vertexv
, and optional vertex properties listvprops
. Ifvprops
is not empty, the shape of the array will be(V, 1 + len(eprops))
, whereV
is the number of vertices, and each line will contain a vertex and its property values.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_all_neighbors(66) array([ 63, 20369, 13980, 8687, 38674, 8687, 20369, 38674])

get_out_degrees
(vs, eweight=None)[source]¶ Return a
numpy.ndarray
containing the outdegrees of vertex listvs
. If supplied, the degrees will be weighted according to the edgeEdgePropertyMap
eweight
.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_out_degrees([42, 666]) array([20, 38], dtype=uint64)

get_in_degrees
(vs, eweight=None)[source]¶ Return a
numpy.ndarray
containing the indegrees of vertex listvs
. If supplied, the degrees will be weighted according to the edgeEdgePropertyMap
eweight
.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_in_degrees([42, 666]) array([20, 39], dtype=uint64)

get_total_degrees
(vs, eweight=None)[source]¶ Return a
numpy.ndarray
containing the total degrees (i.e. in plus outdegree) of vertex listvs
. If supplied, the degrees will be weighted according to the edgeEdgePropertyMap
eweight
.Examples
>>> g = gt.collection.data["pgpstrong2009"] >>> g.get_total_degrees([42, 666]) array([40, 77], dtype=uint64)
Obtaining vertex and edge descriptors

vertex
(i, use_index=True, add_missing=False)[source]¶ Return the vertex with index
i
. Ifuse_index=False
, thei
th vertex is returned (which can differ from the vertex with indexi
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)[source]¶ Return the edge from vertex
s
tot
, if it exists. Ifall_edges=True
then a list is returned with all the parallel edges froms
tot
, otherwise only one edge is returned.If
add_missing == True
, a new edge is created and returned, if none currently exists.This operation will take \(O(min(k(s), k(t)))\) time, where \(k(s)\) and \(k(t)\) are the outdegree and indegree (or outdegree if undirected) of vertices \(s\) and \(t\).
Number of vertices and edges

num_vertices
(ignore_filter=False)[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)[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)[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)[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, N1]\), hence vertex descriptors with an index higher than
vertex
will be invalidated after removal (iffast == 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)[source]¶ Add a new edge from
source
totarget
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)[source]¶ Remove an edge from the graph.
Note
This operation is normally \(O(k_s + k_t)\), where \(k_s\) and \(k_s\) 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)[source]¶ Add a list of edges to the graph, given by
edge_list
, which can be an iterator of(source, target)
pairs where bothsource
andtarget
are vertex indexes, or anumpy.ndarray
of shape(E,2)
, whereE
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 optionhash_type
will determine the expected type used by the hash keys, and they can be any property map value type (seePropertyMap
), unlessedge_list
is anumpy.ndarray
, in which case the value of this option is ignored, and the type is determined automatically.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.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)[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. Iffast == False
, this data structure is destroyed.

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

set_reversed
(is_reversed)[source]¶ Reverse the direction of the edges, if
is_reversed
isTrue
, 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.
Creation of new property maps

new_property
(key_type, value_type, vals=None)[source]¶ Create a new (uninitialized) vertex property map of key type
key_type
(v
,e
org
), value typevalue_type
, and return it. If provided, the values will be initialized byvals
, which should be a sequence.

new_vertex_property
(value_type, vals=None, val=None)[source]¶ Create a new vertex property map of type
value_type
, and return it. If provided, the values will be initialized byvals
, which should be sequence or byval
which should be a single value.

new_vp
(value_type, vals=None, val=None)¶ Alias to
new_vertex_property()
.

new_edge_property
(value_type, vals=None, val=None)[source]¶ Create a new edge property map of type
value_type
, and return it. If provided, the values will be initialized byvals
, which should be sequence or byval
which should be a single value.

new_ep
(value_type, vals=None, val=None)¶ Alias to
new_edge_property()
.

new_graph_property
(value_type, val=None)[source]¶ Create a new graph property map of type
value_type
, and return it. Ifval
is not None, the property is initialized to its value.

new_gp
(value_type, val=None)¶ 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)[source]¶ Copy contents of
src
property totgt
property. Iftgt
is None, then a new property map of the same type (or with the type given by the optionalvalue_type
parameter) is created, and returned. The optional parameterg
specifies the source graph to copy properties from (defaults to the graph than owns src). Iffull == False
, then in the case of filtered graphs only the unmasked values are copied (with the remaining ones taking the typedependent 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 indexes. 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)[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 edgeEdgePropertyMap
containing the edge weights which should be summed.
Index property maps

vertex_index
¶ Vertex index map.
It maps for each vertex in the graph an unique integer in the range [0,
num_vertices()
 1].Note
Like
edge_index
, this is a special instance of aVertexPropertyMap
class, which is immutable, and cannot be accessed as an array.

edge_index
¶ Edge index map.
It maps for each edge in the graph an unique integer.
Note
Like
vertex_index
, this is a special instance of aEdgePropertyMap
class, which is immutable, and cannot be accessed as an array.Additionally, the indexes 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
¶ The size of the range of edge indexes.

reindex_edges
()[source]¶ Reset the edge indexes so that they lie in the [0,
num_edges()
 1] range. The index ordering will be compatible with the sequence returned by theedges()
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 indexes, 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 oneway proxy to the internallykept properties. If you modify this object, the change will be propagated to the internal dictionary, but not viceversa. Keep this in mind if you intend to keep a copy of the returned object.

properties
¶ Dictionary of internal properties. Keys must always be a tuple, where the first element if 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
¶ Dictionary of internal vertex properties. The keys are the property names.

vp
¶ Alias to
vertex_properties
.

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

ep
¶ Alias to
edge_properties
.

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

gp
¶ Alias to
graph_properties
.

list_properties
()[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, inverted_edges=False, inverted_vertices=False)[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 either theinverted_edges
orinverted_vertex
options are supplied with the valueTrue
, only the edges or vertices with valueFalse
are kept. If any of the supplied property isNone
, an empty filter is constructed which allows all edges or vertices.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, inverted=False)[source]¶ Set the vertex boolean filter property. Only the vertices with value different than
False
are kept in the filtered graph. If theinverted
option is supplied with valueTrue
, only the vertices with valueFalse
are kept. If the supplied property isNone
, the filter is replaced by an 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
()[source]¶ Return a tuple with the vertex filter property and bool value indicating whether or not it is inverted.

set_edge_filter
(prop, inverted=False)[source]¶ Set the edge boolean filter property. Only the edges with value different than
False
are kept in the filtered graph. If theinverted
option is supplied with valueTrue
, only the edges with valueFalse
are kept. If the supplied property isNone
, the filter is replaced by an 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
()[source]¶ Return a tuple with the edge filter property and bool value indicating whether or not it is inverted.

clear_filters
()[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)[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 reindex 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.

purge_edges
()[source]¶ Remove all edges of the graph which are currently being filtered out. This operation is not reversible.
I/O operations
See Graph I/O for more details.

load
(file_name, fmt='auto', ignore_vp=None, ignore_ep=None, ignore_gp=None)[source]¶ Load graph from
file_name
(which can be either a string or a filelike object). The format is guessed fromfile_name
, or can be specified byfmt
, which can be either “gt”, “graphml”, “xml”, “dot” or “gml”. (Note that “graphml” and “xml” are synonyms).If provided, the parameters
ignore_vp
,ignore_ep
andignore_gp
, should contain a list of property names (vertex, edge or graph, respectively) which should be ignored when reading the file.Warning
The only file formats which are capable of perfectly preserving the internal property maps are “gt” and “graphml”. Because of this, they should be preferred over the other formats whenever possible.

save
(file_name, fmt='auto')[source]¶ Save graph to
file_name
(which can be either a string or a filelike object). The format is guessed from thefile_name
, or can be specified byfmt
, which can be either “gt”, “graphml”, “xml”, “dot” or “gml”. (Note that “graphml” and “xml” are synonyms).Warning
The only file formats which are capable of perfectly preserving the internal property maps are “gt” and “graphml”. Because of this, they should be preferred over the other formats whenever possible.


class
graph_tool.
GraphView
(g, vfilt=None, efilt=None, directed=None, reversed=False, skip_properties=False, skip_vfilt=False, skip_efilt=False)[source]¶ Bases:
graph_tool.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 viceversa), since they both point to the same underlying data. Because of this, instances ofPropertyMap
can be used interchangeably with a graph and its views.The argument
g
must be an instance of aGraph
class. If specified,vfilt
andefilt
select which vertices and edges are filtered, respectively. These parameters can either be a booleanvaluedPropertyMap
ornumpy.ndarray
, which specify which vertices/edges are selected, or an unary function that returnsTrue
if a given vertex/edge is to be selected, orFalse
otherwise.The boolean parameter
directed
can be used to set the directionality of the graph view. Ifdirected is None
, the directionality is inherited fromg
.If
reversed == True
, the direction of the edges is reversed.If
vfilt
orefilt
is anything other than aPropertyMap
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
orskip_efilt
isTrue
, then the internal properties, vertex filter or edge filter of the original graph are ignored, respectively.
property
base
¶ Base graph.

property

class
graph_tool.
Vertex
¶ Vertex descriptor.
This class represents a vertex in a
Graph
instance.Vertex
instances are hashable, and are convertible to integers, corresponding to its index (seevertex_index
).Raises an exception This class cannot be instantiated from Python

all_edges
()¶ Return an iterator over all edges (both in or out).

all_neighbors
()¶ Return an iterator over all neighbors (both in or out).

in_degree
(weight=None)¶ Return the indegree of the vertex. If provided,
weight
should be a scalar edgeEdgePropertyMap
, and the indegree will correspond to the sum of the weights of the inedges.

in_edges
()¶ Return an iterator over the inedges.

in_neighbors
()¶ Return an iterator over the inneighbors.

is_valid
()¶ Returns
True
if the descriptor corresponds to an existing vertex in the graph,False
otherwise.

out_degree
(weight=None)¶ Return the outdegree of the vertex. If provided,
weight
should be a scalar edgeEdgePropertyMap
, and the outdegree will correspond to the sum of the weights of the outedges.

out_edges
()¶ Return an iterator over the outedges.

out_neighbors
()¶ Return an iterator over the outneighbors.


class
graph_tool.
Edge
¶ Edge descriptor.
This class represents an edge in a
Graph
.Edge
instances are hashable, iterable and thus are convertible to a tuple, which contains the source and target vertices.Raises an exception This class cannot be instantiated from Python

is_valid
()¶ Returns
True
if the descriptor corresponds to an existing edge in the graph,False
otherwise.


class
graph_tool.
PropertyMap
(pmap, g, key_type)[source]¶ This base class provides a mapping from vertices, edges or whole graphs to arbitrary properties.
See Property maps for more details.
The possible property value types are listed below.
Type name
Alias
bool
uint8_t
int16_t
short
int32_t
int
int64_t
long
,long long
double
float
long double
string
vector<bool>
vector<uint8_t>
vector<int16_t>
short
vector<int32_t>
vector<int>
vector<int64_t>
vector<long>
,vector<long long>
vector<double>
vector<float>
vector<long double>
vector<string>
python::object
object

copy
(value_type=None, full=True)[source]¶ Return a copy of the property map. If
value_type
is specified, the value type is converted to the chosen type. Iffull == False
, in the case of filtered graphs only the unmasked values are copied (with the remaining ones taking the typedependent default value).

coerce_type
(full=True)[source]¶ Return a copy of the property map with the most appropriate type, i.e. the simplest type necessary to accomodate all the values exactly. If
full == False
, in the case of filtered graphs only the unmasked values are copied (with the remaining ones taking the typedependent default value).

get_array
()[source]¶ Get a
numpy.ndarray
subclass (PropertyArray
) with the property values.Note
An array is returned only if the value type of the property map is a scalar. For vector, string or object types,
None
is returned instead. For vector and string objects, indirect array access is provided via theget_2d_array()
andset_2d_array()
member functions.Warning
The returned array does not own the data, which belongs to the property map. Therefore, if the graph changes, the array may become invalid. Do not store the array if the graph is to be modified; store a copy instead.

property
a
¶ Shortcut to the
get_array()
method as an attribute. This makes assignments more convenient, e.g.:>>> g = gt.Graph() >>> g.add_vertex(10) <...> >>> prop = g.new_vertex_property("double") >>> prop.a = np.random.random(10) # Assignment from array

property
fa
¶ The same as the
a
attribute, but instead an indexed array is returned, which contains only entries for vertices/edges which are not filtered out. If there are no filters in place, the array is not indexed, and is identical to thea
attribute.Note that because advanced indexing is triggered, a copy of the array is returned, not a view, as for the
a
attribute. Nevertheless, the assignment of values to the whole array at once works as expected.

property
ma
¶ The same as the
a
attribute, but instead anumpy.ma.MaskedArray
object is returned, which contains only entries for vertices/edges which are not filtered out. If there are no filters in place, a regularPropertyArray
is returned, which is identical to thea
attribute.

get_2d_array
(pos)[source]¶ Return a twodimensional array of shape
(M,N)
, whereN
is the number of vertices or edges, andM
is the size of each property vector, with contains a copy of all entries of the vectorvalued property map. The parameterpos
must be a sequence of integers which specifies the indexes of the property values which will be copied.

set_2d_array
(a, pos=None)[source]¶ Set the entries of the vectorvalued property map from a twodimensional array
a
of shape(M,N)
, whereN
is the number of vertices or edges, andM
is the size of each property vector. If given, the parameterpos
must be a sequence of integers which specifies the indexes of the property values which will be set (i.e. rows if thea
matrix).

reserve
(size)[source]¶ Reserve enough space for
size
elements in underlying container. If the original size is already equal or larger, nothing will happen.


class
graph_tool.
VertexPropertyMap
(pmap, g)[source]¶ Bases:
graph_tool.PropertyMap
This class provides a mapping from vertices to arbitrary properties.
See Property maps and
PropertyMap
for more details.

class
graph_tool.
EdgePropertyMap
(pmap, g)[source]¶ Bases:
graph_tool.PropertyMap
This class provides a mapping from edges to arbitrary properties.
See Property maps and
PropertyMap
for more details.

class
graph_tool.
GraphPropertyMap
(pmap, g)[source]¶ Bases:
graph_tool.PropertyMap
This class provides a mapping from graphs to arbitrary properties.
See Property maps and
PropertyMap
for more details.

class
graph_tool.
PropertyArray
(input_array, prop_map)[source]¶ Bases:
numpy.ndarray
This is a
numpy.ndarray
subclass which keeps a reference of itsPropertyMap
owner.
property
prop_map
¶ PropertyMap
owner instance.

property
I/O functions

graph_tool.
load_graph
(file_name, fmt='auto', ignore_vp=None, ignore_ep=None, ignore_gp=None)[source]¶ Load a graph from
file_name
(which can be either a string or a filelike object).The format is guessed from
file_name
, or can be specified byfmt
, which can be either “gt”, “graphml”, “xml”, “dot” or “gml”. (Note that “graphml” and “xml” are synonyms).If provided, the parameters
ignore_vp
,ignore_ep
andignore_gp
, should contain a list of property names (vertex, edge or graph, respectively) which should be ignored when reading the file.Warning
The only file formats which are capable of perfectly preserving the internal property maps are “gt” and “graphml”. Because of this, they should be preferred over the other formats whenever possible.

graph_tool.
load_graph_from_csv
(file_name, directed=False, eprop_types=None, eprop_names=None, hashed=True, hash_type='string', skip_first=False, strip_whitespace=True, ecols=(0, 1), csv_options={'delimiter': ',', 'quotechar': '"'})[source]¶ Load a graph from a
csv
file containing a list of edges and edge properties. Parameters
 file_name
str
or filelike object File in :mod:
csv
format, with edges given in each row. directed
bool
(optional, default:False
) Whether or not the graph is directed.
 eprop_typeslist of
str
(optional, default:None
) List of edge property types to be read from remaining columns (if this is
None
, all properties will be of typestring
. eprop_nameslist of
str
(optional, default:None
) List of edge property names to be used for the remaining columns (if this is
None
, andskip_first
isTrue
their values will be obtained from the first line, otherwise they will be calledc1, c2, ...
). hashed
bool
(optional, default:True
) If
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. hash_type
str
(optional, default:string
) If
hashed == True
, this will determined the type of the vertex values. It can be any property map value type (seePropertyMap
). skip_first
bool
(optional, default:False
) If
True
the first line of the file will be skipped. strip_whitespace
bool
(optional, default:True
) If
True
whitespace will be striped from the start and end of values, before processing them. ecolspair of
int
(optional, default:(0,1)
) Line columns used as source and target for the edges.
 csv_options
dict
(optional, default:{"delimiter": ",", "quotechar": '"'}
) Options to be passed to the
csv.reader()
parser.
 file_name
 Returns
 g
Graph
The loaded graph. It will contain additional columns in the file as internal edge property maps. If
hashed == True
, it will also contain an internal vertex property map with the vertex names.
 g
Property map operations

graph_tool.
group_vector_property
(props, value_type=None, vprop=None, pos=None)[source]¶ Group list of properties
props
into a vector property map of the same type. Parameters
 propslist of
PropertyMap
Properties to be grouped.
 value_typestring (optional, default: None)
If supplied, defines the value type of the grouped property.
 vprop
PropertyMap
(optional, default: None) If supplied, the properties are grouped into this property map.
 poslist of ints (optional, default: None)
If supplied, should contain a list of indexes where each corresponding element of
props
should be inserted.
 propslist of
 Returns
 vprop
PropertyMap
A vector property map with the grouped values of each property map in
props
.
 vprop
Examples
>>> from numpy.random import seed, randint >>> from numpy import array >>> seed(42) >>> gt.seed_rng(42) >>> g = gt.random_graph(100, lambda: (3, 3)) >>> props = [g.new_vertex_property("int") for i in range(3)] >>> for i in range(3): ... props[i].a = randint(0, 100, g.num_vertices()) >>> gprop = gt.group_vector_property(props) >>> print(gprop[g.vertex(0)].a) [51 25 8] >>> print(array([p[g.vertex(0)] for p in props])) [51 25 8]

graph_tool.
ungroup_vector_property
(vprop, pos, props=None)[source]¶ Ungroup vector property map
vprop
into a list of individual property maps. Parameters
 vprop
PropertyMap
Vector property map to be ungrouped.
 poslist of ints
A list of indexes corresponding to where each element of
vprop
should be inserted into the ungrouped list. propslist of
PropertyMap
(optional, default: None) If supplied, should contain a list of property maps to which
vprop
should be ungroupped.
 vprop
 Returns
 propslist of
PropertyMap
A list of property maps with the ungrouped values of
vprop
.
 propslist of
Examples
>>> from numpy.random import seed, randint >>> from numpy import array >>> seed(42) >>> gt.seed_rng(42) >>> g = gt.random_graph(100, lambda: (3, 3)) >>> prop = g.new_vertex_property("vector<int>") >>> for v in g.vertices(): ... prop[v] = randint(0, 100, 3) >>> uprops = gt.ungroup_vector_property(prop, [0, 1, 2]) >>> print(prop[g.vertex(0)].a) [51 92 14] >>> print(array([p[g.vertex(0)] for p in uprops])) [51 92 14]

graph_tool.
map_property_values
(src_prop, tgt_prop, map_func)[source]¶ Map the values of
src_prop
totgt_prop
according to the mapping functionmap_func
. Parameters
 src_prop
PropertyMap
Source property map.
 tgt_prop
PropertyMap
Target property map.
 map_funcfunction or callable object
Function mapping values of
src_prop
to values oftgt_prop
.
 src_prop
 Returns
 None
Examples
>>> g = gt.collection.data["lesmis"] >>> label_len = g.new_vertex_property("int64_t") >>> gt.map_property_values(g.vp.label, label_len, ... lambda x: len(x)) >>> print(label_len.a) [ 6 8 14 11 12 8 12 8 5 6 7 7 10 6 7 7 9 9 7 11 9 6 7 7 13 10 7 6 12 10 8 8 11 6 5 12 6 10 11 9 12 7 7 6 14 7 9 9 8 12 6 16 12 11 14 6 9 6 8 10 9 7 10 7 7 4 9 14 9 5 10 12 9 6 6 6 12]

graph_tool.
infect_vertex_property
(g, prop, vals=None)[source]¶ Propagate the prop values of vertices with value val to all their outneighbors.
 Parameters
 prop
VertexPropertyMap
Property map to be modified.
 valslist (optional, default: None)
List of values to be propagated. If not provided, all values will be propagated.
 prop
 Returns
 None
None
 None
Examples
>>> from numpy.random import seed >>> seed(42) >>> gt.seed_rng(42) >>> g = gt.random_graph(100, lambda: (3, 3)) >>> prop = g.vertex_index.copy("int32_t") >>> gt.infect_vertex_property(g, prop, [10]) >>> print(sum(prop.a == 10)) 4

graph_tool.
edge_endpoint_property
(g, prop, endpoint, eprop=None)[source]¶ Return an edge property map corresponding to the vertex property prop of either the target and source of the edge, according to endpoint.
 Parameters
 prop
VertexPropertyMap
Vertex property map to be used to propagated to the edge.
 endpoint“source” or “target”
Edge endpoint considered. If the graph is undirected, the source is always the vertex with the lowest index.
 eprop
EdgePropertyMap
(optional, default: None) If provided, the resulting edge properties will be stored here.
 prop
 Returns
 eprop
EdgePropertyMap
Propagated edge property.
 eprop
Examples
>>> gt.seed_rng(42) >>> g = gt.random_graph(100, lambda: (3, 3)) >>> esource = gt.edge_endpoint_property(g, g.vertex_index, "source") >>> print(esource.a) [ 0 0 0 96 96 96 92 92 92 88 88 88 84 84 84 80 80 80 76 76 76 72 72 72 68 68 68 64 64 64 60 60 60 56 56 56 52 52 52 48 48 48 44 44 44 40 40 40 36 36 36 32 32 32 28 28 28 24 24 24 20 20 20 16 16 16 12 12 12 8 8 8 4 4 4 99 99 99 1 1 1 2 2 2 3 3 3 5 5 5 6 6 6 7 7 7 9 9 9 10 10 10 14 14 14 19 19 19 25 25 25 30 30 30 35 35 35 41 41 41 46 46 46 51 51 51 57 57 57 62 62 62 67 67 67 73 73 73 78 78 78 83 83 83 89 89 89 94 94 94 11 11 11 98 98 98 97 97 97 95 95 95 93 93 93 91 91 91 90 90 90 87 87 87 86 86 86 85 85 85 82 82 82 81 81 81 79 79 79 77 77 77 75 75 75 74 74 74 71 71 71 69 69 69 61 61 61 54 54 54 47 47 47 39 39 39 33 33 33 26 26 26 18 18 18 70 70 70 13 13 13 15 15 15 17 17 17 21 21 21 22 22 22 23 23 23 27 27 27 29 29 29 31 31 31 34 34 34 37 37 37 38 38 38 42 42 42 43 43 43 45 45 45 49 49 49 50 50 50 53 53 53 55 55 55 58 58 58 59 59 59 63 63 63 65 65 65 66 66 66]

graph_tool.
incident_edges_op
(g, direction, op, eprop, vprop=None)[source]¶ Return a vertex property map corresponding to a specific operation (sum, product, min or max) on the edge property eprop of incident edges on each vertex, following the direction given by direction.
 Parameters
 direction“in” or “out”
Direction of the incident edges.
 op“sum”, “prod”, “min” or “max”
Operation performed on incident edges.
 eprop
EdgePropertyMap
Edge property map to be summed.
 vprop
VertexPropertyMap
(optional, default: None) If provided, the resulting vertex properties will be stored here.
 Returns
 vprop
VertexPropertyMap
Resulting vertex property.
 vprop
Examples
>>> gt.seed_rng(42) >>> g = gt.random_graph(100, lambda: (3, 3)) >>> vsum = gt.incident_edges_op(g, "out", "sum", g.edge_index) >>> print(vsum.a) [ 3 237 246 255 219 264 273 282 210 291 300 453 201 687 309 696 192 705 669 318 183 714 723 732 174 327 660 741 165 750 336 759 156 651 768 345 147 777 786 642 138 354 795 804 129 813 363 633 120 822 831 372 111 840 624 849 102 381 858 867 93 615 390 876 84 885 894 399 75 606 678 597 66 408 588 579 57 570 417 561 48 552 543 426 39 534 525 516 30 435 507 498 21 489 444 480 12 471 462 228]

graph_tool.
perfect_prop_hash
(props, htype='int32_t')[source]¶ Given a list of property maps props of the same type, a derived list of property maps with integral type htype is returned, where each value is replaced by a perfect (i.e. unique) hash value.
Note
The hash value is deterministic, but it will not be necessarily the same for different values of props.
OpenMP control

graph_tool.
openmp_get_schedule
()[source]¶ Return the runtime OpenMP schedule and chunk size. The schedule can by any of:
"static"
,"dynamic"
,"guided"
,"auto"
.

graph_tool.
openmp_set_schedule
(schedule, chunk=0)[source]¶ Set the runtime OpenMP schedule and chunk size. The schedule can by any of:
"static"
,"dynamic"
,"guided"
,"auto"
.
Misc
Available subpackages¶
graph_tool.centrality
 Centrality measuresgraph_tool.clustering
 Clustering coefficientsgraph_tool.collection
 Dataset collectiongraph_tool.correlations
 Correlationsgraph_tool.dynamics
 Dynamical processesgraph_tool.draw
 Graph drawing and layoutgraph_tool.flow
 Maximum flow algorithmsgraph_tool.generation
 Random graph generationgraph_tool.inference
 Statistical inference of generative network modelsgraph_tool.search
 Search algorithmsgraph_tool.spectral
 Spectral propertiesgraph_tool.stats
 Miscellaneous statisticsgraph_tool.topology
 Assessing graph topologygraph_tool.util
 Graph utilities