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:
GraphA view of selected vertices or edges of another graph.
This class uses shared data from another
Graphinstance, 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
GraphViewobject 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 ofPropertyMapcan be used interchangeably with a graph and its views.The argument
gmust be an instance of aGraphclass. If specified,vfiltandefiltselect which vertices and edges are filtered, respectively. These parameters can either be a boolean-valuedPropertyMapornumpy.ndarray, which specify which vertices/edges are selected, or a unary function that returnsTrueif a given vertex/edge is to be selected, orFalseotherwise.The boolean parameter
directedcan 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
vfiltorefiltis anything other than aPropertyMapinstance, 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_efiltisTrue, 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
sourcetotargetto 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 bothsourceandtargetare vertex indices (or can be so converted), or anumpy.ndarrayof shape(E,2), whereEis 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.
Remove all edges from the graph.
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
srcproperty totgtproperty.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
stot, if it exists.edges()Return an
iteratorover the edges.get_all_edges(v[, eprops])Return a
numpy.ndarraycontaining the in- and out-edges of vertexv, and optional edge properties listeprops.get_all_neighbors(v[, vprops])Return a
numpy.ndarraycontaining the in-neighbors and out-neighbors of vertexv, and optional vertex properties listvprops.get_all_neighbours(v[, vprops])Return a
numpy.ndarraycontaining the in-neighbors and out-neighbors of vertexv, and optional vertex properties listvprops.Return the edge filter property map.
get_edge_range(s, t, eprops)Return a
numpy.ndarraycontaining the parallel edge propertiesepropsfor the parallel edges between verticessandt.get_edges([eprops])Return a
numpy.ndarraycontaining the edges, and optional edge properties listeprops.Return whether the fast \(O(1)\) lookup of edges is currently enabled.
Return whether the fast \(O(1)\) removal of edges is currently enabled.
Return a copy of the filter state of the graph.
get_in_degrees(vs[, eweight])Return a
numpy.ndarraycontaining the in-degrees of vertex listvs.get_in_edges(v[, eprops])Return a
numpy.ndarraycontaining the in-edges of vertexv, and optional edge properties listeprops.get_in_neighbors(v[, vprops])Return a
numpy.ndarraycontaining the in-neighbors of vertexv, and optional vertex properties listvprops.get_in_neighbours(v[, vprops])Return a
numpy.ndarraycontaining the in-neighbors of vertexv, and optional vertex properties listvprops.get_out_degrees(vs[, eweight])Return a
numpy.ndarraycontaining the out-degrees of vertex listvs.get_out_edges(v[, eprops])Return a
numpy.ndarraycontaining the out-edges of vertexv, and optional edge properties listeprops.get_out_neighbors(v[, vprops])Return a
numpy.ndarraycontaining the out-neighbors of vertexv, and optional vertex properties listvprops.get_out_neighbours(v[, vprops])Return a
numpy.ndarraycontaining the out-neighbors of vertexv, and optional vertex properties listvprops.get_total_degrees(vs[, eweight])Return a
numpy.ndarraycontaining the total degrees (i.e. in- plus out-degree) of vertex listvs.Return the vertex filter property.
get_vertices([vprops])Return a
numpy.ndarraycontaining the vertex indices, and optional vertex properties listvprops.Get the directedness of the graph.
Return
Trueif the edges are reversed, andFalseotherwise.iter_all_edges(v[, eprops])Return an iterator over the in- and out-edge
(source, target)pairs for vertexv, and optional edge properties listeprops.iter_all_neighbors(v[, vprops])Return an iterator over the in- and out-neighbors of vertex
v, and optional vertex properties listvprops.iter_all_neighbours(v[, vprops])Return an iterator over the in- and out-neighbors of vertex
v, and optional vertex properties listvprops.iter_edge_range(s, t, eprops)Return an iterator over the edge properties list
epropsfor parallel edges between verticessandt.iter_edges([eprops])Return an iterator over the edge
(source, target)pairs, and optional edge properties listeprops.iter_in_edges(v[, eprops])Return an iterator over the in-edge
(source, target)pairs for vertexv, and optional edge properties listeprops.iter_in_neighbors(v[, vprops])Return an iterator over the in-neighbors of vertex
v, and optional vertex properties listvprops.iter_in_neighbours(v[, vprops])Return an iterator over the in-neighbors of vertex
v, and optional vertex properties listvprops.iter_out_edges(v[, eprops])Return an iterator over the out-edge
(source, target)pairs for vertexv, and optional edge properties listeprops.iter_out_neighbors(v[, vprops])Return an iterator over the out-neighbors of vertex
v, and optional vertex properties listvprops.iter_out_neighbours(v[, vprops])Return an iterator over the out-neighbors of vertex
v, and optional vertex properties listvprops.iter_vertices([vprops])Return an iterator over the vertex indices, and optional vertex properties list
vprops.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, org), value typevalue_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.
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 == Truethe fast \(O(1)\) lookup of edges will be enabled.set_fast_edge_removal([fast])If
fast == Truethe 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_reversedisTrue, or maintain the original direction otherwise.set_vertex_filter(prop)Set the vertex boolean filter property.
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
iteratorover the vertices.Attributes
Base graph.
Edge index map.
The size of the range of edge indices.
Dictionary of internal edge properties.
Alias to
edge_properties.Alias to
graph_properties.Dictionary of internal graph properties.
Dictionary of internal properties.
Vertex index map.
Dictionary of internal vertex properties.
Alias to
vertex_properties.- add_edge(source, target, add_missing=True)[git]#
Add a new edge from
sourcetotargetto 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 bothsourceandtargetare vertex indices (or can be so converted), or anumpy.ndarrayof shape(E,2), whereEis 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_typewill determine the expected type used by the hash keys, and they can be any property map value type (seePropertyMap), unlessedge_listis anumpy.ndarray, in which case the value of this option is ignored, and the type is determined automatically.If
hashed == Falseand the target value of an edge corresponds to the maximum integer value (sys.maxsize, or the maximum integer type of thenumpy.ndarrayobject), or is anumpy.nanornumpy.infvalue, then only the source vertex will be added to the graph.If
hashed == True, and the target value corresponds toNone, then only the source vertex will be added to the graph.If given,
epropsshould 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,epropscan 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_listis anumpy.ndarray, andhashed == 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 ofedge_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_listis anumpy.ndarrayobject, 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,nvertices are inserted and an iterator over the new vertices is returned. This operation is \(O(n)\).
- 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.
- 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
srcproperty totgtproperty. Iftgtis None, then a new property map of the same type (or with the type given by the optionalvalue_typeparameter) is created, and returned. The optional parametergspecifies the source graph to copy properties from (defaults to the graph that ownssrc). Iffull == 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,weightshould be an edgeEdgePropertyMapcontaining the edge weights which should be summed.
- edge(s, t, all_edges=False, add_missing=False)[git]#
Return the edge from vertex
stot, if it exists. Ifall_edges=Truethen a list is returned with all the parallel edges fromstot, 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
iteratorover 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_indexproperty 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.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.ndarraycontaining the in- and out-edges of vertexv, and optional edge properties listeprops. The shape of the array will be(E, 2 + len(eprops)), whereEis 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.ndarraycontaining the in-neighbors and out-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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.ndarraycontaining the in-neighbors and out-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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_range(s, t, eprops)[git]#
Return a
numpy.ndarraycontaining the parallel edge propertiesepropsfor the parallel edges between verticessandt.The shape of the array will be
(m, len(eprops)), wheremis 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.ndarraycontaining the edges, and optional edge properties listeprops. The shape of the array will be(E, 2 + len(eprops)), whereEis 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_removal()[git]#
Return whether the fast \(O(1)\) removal of edges is currently enabled.
- get_in_degrees(vs, eweight=None)[git]#
Return a
numpy.ndarraycontaining the in-degrees of vertex listvs. If supplied, the degrees will be weighted according to the edgeEdgePropertyMapeweight.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.ndarraycontaining the in-edges of vertexv, and optional edge properties listeprops. The shape of the array will be(E, 2 + len(eprops)), whereEis 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.ndarraycontaining the in-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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.ndarraycontaining the in-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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.ndarraycontaining the out-degrees of vertex listvs. If supplied, the degrees will be weighted according to the edgeEdgePropertyMapeweight.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.ndarraycontaining the out-edges of vertexv, and optional edge properties listeprops. The shape of the array will be(E, 2 + len(eprops)), whereEis 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.ndarraycontaining the out-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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.ndarraycontaining the out-neighbors of vertexv, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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.ndarraycontaining the total degrees (i.e. in- plus out-degree) of vertex listvs. If supplied, the degrees will be weighted according to the edgeEdgePropertyMapeweight.Examples
>>> g = gt.collection.data["pgp-strong-2009"] >>> g.get_total_degrees([42, 666]) array([40, 77], dtype=uint64)
- get_vertices(vprops=[])[git]#
Return a
numpy.ndarraycontaining the vertex indices, and optional vertex properties listvprops. Ifvpropsis not empty, the shape of the array will be(V, 1 + len(vprops)), whereVis 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])
- iter_all_edges(v, eprops=[])[git]#
Return an iterator over the in- and out-edge
(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.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 listvprops.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 listvprops.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
epropsfor parallel edges between verticessandt.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 listeprops.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 vertexv, and optional edge properties listeprops.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 listvprops.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 listvprops.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 vertexv, and optional edge properties listeprops.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 listvprops.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 listvprops.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_name
stror file-like object Name of the file, or a file-like object (opened in binary mode).
- fmt
str(optional, default:"auto") File format, as given in the table below. If
"auto", the format is given by the extension offile_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.
- file_name
See also
load_graphLoad 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, iffmtis"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 ingraph-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.fmtExtension
Format
"gt".gtBinary format of
graph-tool(see Sec. The gt file format)"graphml".graphml,.xmlGraphML (
"xml"is a synonym)"dot".dot"gml".gml"gexf".gexfGEXF (Gephi)
"pajek".net"json".json"cytoscape_json".cyjs"adjacency_json""tree_json"JSON tree, of directed trees
"mtx".mtx"graph6".g6graph6 (nauty)
"sparse6".s6sparse6 (nauty)
"digraph6".d6digraph6 (nauty)
"metis".graph,.metis"paj".pajPajek project, with a network, partitions, and vectors
"ncol".ncolNCOL (Large Graph Layout)
"lgl".lglLGL (Large Graph Layout)
"edgelist".edgelist,.edges,.edge"adjlist".adjlist"multiline_adjlist""adjacency".adjAdjacency matrix as text
"dl".dlUCINET DL, in the
fullmatrix,edgelist1, andnodelist1formats"leda".gw,.leda,.lgr"graphdb".graphdbGraphDB, the binary format of the ARG database (DOI: 10.1016/S0167-8655(02)00253-2 [sci-hub, @tor])
"dimacs".dimacs,.max,.colDIMACS 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:fmtProperty 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_nameas the names of the verticesNone
"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 mapdirected, the vertex property mapid, and the edge property mapsid,source, andtarget, whose names are keys of the format and which cannot be savedNone
"gexf"The vertex and edge property maps, with their value types (the property maps
pos,color,size,thickness, andshapeas visualization data), and the graph property mapsdescriptionandkeywordsNone
"pajek"The vertex property maps
label,pos, andshape, the edge property mapweight, 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 shapeellipse, which is read back as well), and the graph property mapnameNone
"json"All, as JSON values that are read back as
bool,int64_t,double,string, vectors of these, orpython::objectNone
"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
sizeandweight, and the integer edge property mapweightNone
"paj"Those of
"pajek", with the integer and floating point vertex property maps as partitions and vectors, which are read back asint64_tanddoubleNone
"ncol","lgl"The vertex property map
name, as text, and the scalar edge property mapweight, which is read back asdoubleNone
"edgelist","multiline_adjlist"The vertex property map
name, as text, and the edge property maps whose values are Python literals, read back asbool,int64_t,double,string, vectors of these, orpython::objectNone
"adjlist"The vertex property map
name, as textNone
"adjacency"The sums of the values of the scalar edge property map
weight, or the numbers of edgesNone
"dl"The vertex property map
name, as text, and the scalar edge property mapweightNone
"leda"The vertex property map
label, and the edge property mapweight(orlabelif there is noweight), with scalar or string valuesNone
"graphdb"None
None
"dimacs"For directed graphs, the scalar edge property map
capacityand the graph property mapssourceandtarget, for undirected graphs, the scalar vertex property mapweightNone
"network_text"The vertex property maps
labelandcollapseNone
Filtered and reversed graphs
When a filtered graph is saved by
save()in the"gt"or"graphml"format withpreserve_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. Withpreserve_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 aValueError, 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 mapcapacity), 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 withset_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 mapweight, 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 mapname, 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 mapname, 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 valuesnanandinf(which Python writes as such, but which are not Python literals).Python objects
The values of the property maps of type
python::objectare stored as theirpickleby 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 (aValueErroris raised otherwise), and it does not restore a property map whose values are allNone.Warning
Unpickling can execute arbitrary code. Files with property maps of type
python::objectshould 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 mapvaluein the"cytoscape_json"format andidin 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 mapkey, 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 maplabel, or by their indices, and the trees below the vertices with a true value of the vertex property mapcollapseare 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 byvals, which should be a sequence in edge index order (the same asfa), or byvalwhich 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. Ifvalis 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, org), value typevalue_type, and return it. If provided, the values will be initialized byvals, which should be a sequence, or byvalwhich 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 byvals, which should be a sequence in vertex index order (the same asfa), or byvalwhich 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 == Trueis 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 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 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
vertexis an iterable, it should correspond to a sequence of vertices to be removed.Note
If the option
fast == Falseis 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
vertexwill 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
vertexparameter, 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_name
stror file-like object Name of the file, or a file-like object (opened in binary mode).
- fmt
str(optional, default:"auto") File format, as given in the table below. If
"auto", the format is given by the extension offile_name, or is"gt"for file-like objects.- preserve_filter
bool(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.- nthreads
int(optional, default:None) Number of threads of the xz and zstd compression. If
None, the number given byopenmp_get_num_threads()is used, or a single thread ifgraph-toolwas compiled without OpenMP.
- file_name
See also
load_graphLoad 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, iffmtis"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 ingraph-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.fmtExtension
Format
"gt".gtBinary format of
graph-tool(see Sec. The gt file format)"graphml".graphml,.xmlGraphML (
"xml"is a synonym)"dot".dot"gml".gml"gexf".gexfGEXF (Gephi)
"pajek".net"json".json"cytoscape_json".cyjs"adjacency_json""tree_json"JSON tree, of directed trees
"mtx".mtx"graph6".g6graph6 (nauty)
"sparse6".s6sparse6 (nauty)
"digraph6".d6digraph6 (nauty)
"metis".graph,.metis"paj".pajPajek project, with a network, partitions, and vectors
"ncol".ncolNCOL (Large Graph Layout)
"lgl".lglLGL (Large Graph Layout)
"edgelist".edgelist,.edges,.edge"adjlist".adjlist"multiline_adjlist""adjacency".adjAdjacency matrix as text
"dl".dlUCINET DL, in the
fullmatrix,edgelist1, andnodelist1formats"leda".gw,.leda,.lgr"graphdb".graphdbGraphDB, the binary format of the ARG database (DOI: 10.1016/S0167-8655(02)00253-2 [sci-hub, @tor])
"dimacs".dimacs,.max,.colDIMACS 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:fmtProperty 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_nameas the names of the verticesNone
"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 mapdirected, the vertex property mapid, and the edge property mapsid,source, andtarget, whose names are keys of the format and which cannot be savedNone
"gexf"The vertex and edge property maps, with their value types (the property maps
pos,color,size,thickness, andshapeas visualization data), and the graph property mapsdescriptionandkeywordsNone
"pajek"The vertex property maps
label,pos, andshape, the edge property mapweight, 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 shapeellipse, which is read back as well), and the graph property mapnameNone
"json"All, as JSON values that are read back as
bool,int64_t,double,string, vectors of these, orpython::objectNone
"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
sizeandweight, and the integer edge property mapweightNone
"paj"Those of
"pajek", with the integer and floating point vertex property maps as partitions and vectors, which are read back asint64_tanddoubleNone
"ncol","lgl"The vertex property map
name, as text, and the scalar edge property mapweight, which is read back asdoubleNone
"edgelist","multiline_adjlist"The vertex property map
name, as text, and the edge property maps whose values are Python literals, read back asbool,int64_t,double,string, vectors of these, orpython::objectNone
"adjlist"The vertex property map
name, as textNone
"adjacency"The sums of the values of the scalar edge property map
weight, or the numbers of edgesNone
"dl"The vertex property map
name, as text, and the scalar edge property mapweightNone
"leda"The vertex property map
label, and the edge property mapweight(orlabelif there is noweight), with scalar or string valuesNone
"graphdb"None
None
"dimacs"For directed graphs, the scalar edge property map
capacityand the graph property mapssourceandtarget, for undirected graphs, the scalar vertex property mapweightNone
"network_text"The vertex property maps
labelandcollapseNone
Filtered and reversed graphs
When a filtered graph is saved by
save()in the"gt"or"graphml"format withpreserve_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. Withpreserve_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 aValueError, 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 mapcapacity), 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 withset_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 mapweight, 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 mapname, 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 mapname, 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 valuesnanandinf(which Python writes as such, but which are not Python literals).Python objects
The values of the property maps of type
python::objectare stored as theirpickleby 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 (aValueErroris raised otherwise), and it does not restore a property map whose values are allNone.Warning
Unpickling can execute arbitrary code. Files with property maps of type
python::objectshould 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 mapvaluein the"cytoscape_json"format andidin 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 mapkey, 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 maplabel, or by their indices, and the trees below the vertices with a true value of the vertex property mapcollapseare 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
Falseare kept in the filtered graph. If the supplied property isNone, 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 == Truethe 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. Iffast == False, this data structure is destroyed.
- set_fast_edge_removal(fast=True)[git]#
If
fast == Truethe 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.
- set_filters(eprop, vprop)[git]#
Set the boolean properties for edge and vertex filters, respectively. Only the vertices and edges with value different than
Falseare kept in the filtered graph. If any of the supplied properties isNone, an empty filter is constructed which allows all edges or vertices. If both areNone, the graph is returned to the unfiltered state, as withclear_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_reversedisTrue, 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
Falseare kept in the filtered graph. If the supplied property isNone, 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. Ifuse_index=False, thei-th vertex is returned (which can differ from the vertex with indexiin 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
iteratorover the vertices.Note
The order of the vertices traversed by the iterator always corresponds to the vertex index ordering, as given by the
vertex_indexproperty 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)
- 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 aEdgePropertyMapclass, 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.
- ep[git]#
Alias to
edge_properties.
- gp[git]#
Alias to
graph_properties.
- 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 aVertexPropertyMapclass, which is immutable, and cannot be accessed as an array.
- vp[git]#
Alias to
vertex_properties.