Graph#

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

General multigraph class.

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

If g is specified, it can be one of:

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

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

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

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

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

    This is equivalent to calling add_edge_list() as such:

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

    Note

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

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

    This is equivalent to calling add_edge_list() as such:

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

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

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

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

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

The value of set_fast_edge_removal is passed to set_fast_edge_removal().

Note

The graph is implemented internally 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.

Iterator-based 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 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.

Iterator-based 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 list eprops.

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

Examples

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

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

Note

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

Examples

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

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

Note

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

Examples

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

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

Note

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

Examples

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

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

Note

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

Examples

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

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

Note

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

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

Array-based interface:

get_vertices(vprops=[])[source]#

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

Note

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

Examples

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

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

Note

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

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

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

Examples

>>> g = gt.collection.data["pgp-strong-2009"]
>>> g.get_total_degrees([42, 666])
array([40, 77], dtype=uint64)

Obtaining vertex and edge descriptors

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

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

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

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

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

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

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

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, N-1]\), hence vertex descriptors with an index higher than vertex will be invalidated after removal (if fast == False, otherwise only descriptors pointing to vertices with the largest index will be invalidated).

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

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

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

Warning

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

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

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

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

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

remove_edge(edge)[source]#

Remove an edge from the graph.

Note

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

Warning

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

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

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

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

If hashed == False and the target value of an edge corresponds to the maximum interger 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 dege property maps will be created with the corresponding name name and value type.

Note

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

Examples

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

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

get_fast_edge_removal()[source]#

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

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

clear()[source]#

Remove all vertices and edges from the graph.

clear_vertex(vertex)[source]#

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

clear_edges()[source]#

Remove all edges from the graph.

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

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

is_directed()[source]#

Get the directedness of the graph.

set_reversed(is_reversed)[source]#

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

Note

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

Warning

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

is_reversed()[source]#

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

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 or g), value type value_type, and return it. If provided, the values will be initialized by vals, 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 by vals, which should be sequence or by val 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 by vals, which should be sequence or by val 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. If val 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 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 than 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)[source]#

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

Index property maps

vertex_index#

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 a VertexPropertyMap 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 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#

The size of the range of edge indices.

reindex_edges()[source]#

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

Warning

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

Internal property maps

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

Note

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

properties#

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.

own_property(prop)[source]#

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

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 the inverted_edges or inverted_vertex options are supplied with the value True, only the edges or vertices with value False are kept. If any of the supplied property is None, 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 the inverted option is supplied with value True, only the vertices with value False are kept. If the supplied property is None, 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 the inverted option is supplied with value True, only the edges with value False are kept. If the supplied property is None, 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 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.

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 file-like object). The format is guessed from file_name, or can be specified by fmt, 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 and ignore_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 file-like object). The format is guessed from the file_name, or can be specified by fmt, 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.