graph_tool  efficient graph analysis and manipulation¶
Summary¶
Graph 
Generic multigraph class. 
GraphView 
A view of selected vertices or edges of another graph. 
Vertex 
Vertex descriptor. 
Edge 
Edge descriptor. 
PropertyMap 
This class provides a mapping from vertices, edges or whole graphs to arbitrary properties. 
PropertyArray 
This is a ndarray subclass which keeps a reference of its PropertyMap owner. 
load_graph 
Load a graph from file_name (which can be either a string or a filelike object). 
load_graph_from_csv 
Load a graph from a csv file containing a list of edges and edge properties. 
group_vector_property 
Group list of properties props into a vector property map of the same type. 
ungroup_vector_property 
Ungroup vector property map vprop into a list of individual property maps. 
map_property_values 
Map the values of src_prop to tgt_prop according to the mapping function map_func . 
infect_vertex_property 
Propagate the prop values of vertices with value val to all their outneighbours. 
edge_endpoint_property 
Return an edge property map corresponding to the vertex property prop of either the target and source of the edge, according to endpoint. 
incident_edges_op 
Return a vertex property map corresponding to a specific operation (sum, product, min or max) on the edge property eprop of incident edges on each vertex, following the direction given by direction. 
perfect_prop_hash 
Given a list of property maps props of the same type, a derived list of property maps with integral type htype is returned, where each value is replaced by a perfect (i.e. 
value_types 
Return a list of possible properties value types. 
show_config 
Show graph_tool build configuration. 
This module provides:
 A
Graph
class for graph representation and manipulation Property maps for Vertex, Edge or Graph.
 Fast algorithms implemented in C++.
How to use the documentation¶
Documentation is available in two forms: docstrings provided with the code, and the full documentation available in the graphtool homepage.
We recommend exploring the docstrings using IPython, an advanced Python shell with TABcompletion and introspection capabilities.
The docstring examples assume that graph_tool.all
has been imported as
gt
:
>>> import graph_tool.all as gt
Code snippets are indicated by three greaterthan signs:
>>> x = x + 1
Use the builtin help
function to view a function’s docstring:
>>> help(gt.Graph)
Contents¶

class
graph_tool.
Graph
(g=None, directed=True, prune=False, vorder=None)[source]¶ Generic multigraph class.
This class encapsulates either a directed multigraph (default or if
directed=True
) or an undirected multigraph (ifdirected=False
), with optional internal edge, vertex or graph properties.If
g
is specified, the graph (and its internal properties) will be copied.If
prune
is set toTrue
, andg
is specified, only the filtered graph will be copied, and the new graph object will not be filtered. Optionally, a tuple of three booleans can be passed as value toprune
, to specify a different behavior to vertex, edge, and reversal filters, respectively.If
vorder
is specified, it should correspond to a vertexPropertyMap
specifying the ordering of the vertices in the copied graph.The graph is implemented as an adjacency list, where both vertex and edge lists are C++ STL vectors.

copy
()[source]¶ Return a deep copy of self. All internal property maps are also copied.
Iterating over vertices and edgesSee Iterating over vertices and edges for more documentation and examples.

vertices
()[source]¶ Return an
iterator
over the vertices.Note
The order of the vertices traversed by the iterator always corresponds to the vertex index ordering, as given by the
vertex_index
property map.Examples
>>> g = gt.Graph() >>> vlist = list(g.add_vertex(5)) >>> vlist2 = [] >>> for v in g.vertices(): ... vlist2.append(v) ... >>> assert(vlist == vlist2)

edges
()[source]¶ Return an
iterator
over the edges.Note
The order of the edges traversed by the iterator does not necessarily correspond to the edge index ordering, as given by the
edge_index
property map. This will only happen afterreindex_edges()
is called, or in certain situations such as just after a graph is loaded from a file. However, further manipulation of the graph may destroy the ordering.
Obtaining vertex and edge descriptors
vertex
(i, use_index=True, add_missing=False)[source]¶ Return the vertex with index
i
. Ifuse_index=False
, thei
th vertex is returned (which can differ from the vertex with indexi
in case of filtered graphs).If
add_missing == True
, and the vertex does not exist in the graph, the necessary number of missing vertices are inserted, and the new vertex is returned.

edge
(s, t, all_edges=False, add_missing=False)[source]¶ Return the edge from vertex
s
tot
, if it exists. Ifall_edges=True
then a list is returned with all the parallel edges froms
tot
, otherwise only one edge is returned.If
add_missing == True
, a new edge is created and returned, if none currently exists.This operation will take \(O(min(k(s), k(t)))\) time, where \(k(s)\) and \(k(t)\) are the outdegree and indegree (or outdegree if undirected) of vertices \(s\) and \(t\).
Number of vertices and edges
num_vertices
(ignore_filter=False)[source]¶ Get the number of vertices.
If
ignore_filter == True
, vertex filters are ignored.Note
If the vertices are being filtered, and
ignore_filter == False
, this operation is \(O(V)\). Otherwise it is \(O(1)\).

num_edges
(ignore_filter=False)[source]¶ Get the number of edges.
If
ignore_filter == True
, edge filters are ignored.Note
If the edges are being filtered, and
ignore_filter == False
, this operation is \(O(E)\). Otherwise it is \(O(1)\).
Modifying vertices and edgesThe following functions allow for addition and removal of vertices in the graph.

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

remove_vertex
(vertex, fast=False)[source]¶ Remove a vertex from the graph. If
vertex
is an iterable, it should correspond to a sequence of vertices to be removed.Note
If the option
fast == False
is given, this operation is \(O(V + E)\) (this is the default). Otherwise it is \(O(k + k_{\text{last}})\), where \(k\) is the (total) degree of the vertex being deleted, and \(k_{\text{last}}\) is the (total) degree of the vertex with the largest index.Warning
This operation may invalidate vertex descriptors. Vertices are always indexed contiguously in the range \([0, N1]\), hence vertex descriptors with an index higher than
vertex
will be invalidated after removal (iffast == False
, otherwise only descriptors pointing to vertices with the largest index will be invalidated).Because of this, the only safe way to remove more than one vertex at once is to sort them in decreasing index order:
# 'del_list' is a list of vertex descriptors for v in reversed(sorted(del_list)): g.remove_vertex(v)
Alternatively (and preferably), a list (or iterable) may be passed directly as the
vertex
parameter, and the above is performed internally (in C++).Warning
If
fast == True
, the vertex being deleted is ‘swapped’ with the last vertex (i.e. with the largest index), which will in turn inherit the index of the vertex being deleted. All property maps associated with the graph will be properly updated, but the index ordering of the graph will no longer be the same.
The following functions allow for addition and removal of edges in the graph.

add_edge
(source, target, add_missing=True)[source]¶ Add a new edge from
source
totarget
to the graph, and return it. This operation is \(O(1)\).If
add_missing == True
, the source and target vertices are included in the graph if they don’t yet exist.

remove_edge
(edge)[source]¶ Remove an edge from the graph.
Note
This operation is normally \(O(k_s + k_t)\), where \(k_s\) and \(k_s\) are the total degrees of the source and target vertices, respectively. However, if
set_fast_edge_removal()
is set to True, this operation becomes \(O(1)\).Warning
The relative ordering of the remaining edges in the graph is kept unchanged, unless
set_fast_edge_removal()
is set to True, in which case it can change.

add_edge_list
(edge_list, hashed=False, string_vals=False, eprops=None)[source]¶ Add a list of edges to the graph, given by
edge_list
, which can be an iterator of(source, target)
pairs where bothsource
andtarget
are vertex indexes, or andarray
of shape(E,2)
, whereE
is the number of edges, and each line specifies a(source, target)
pair. If the list references vertices which do not exist in the graph, they will be created.Optionally, if
hashed == True
, the vertex values in the edge list are not assumed to correspond to vertex indices directly. In this case they will be mapped to vertex indices according to the order in which they are encountered, and a vertex property map with the vertex values is returned. Ifstring_vals == True
, the algorithm assumes that the vertex values are strings. Otherwise, they will be assumed to be numeric ifedge_list
is andarray
, or arbitrary python objects if it is not.If given,
eprops
specifies edge property maps that will be filled with the remaining values at each row, if there are more than two.

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

get_fast_edge_removal
()[source]¶ Return whether the fast \(O(1)\) removal of edges is currently enabled.
The following functions allow for easy removal of vertices and edges from the graph.
After the removal of many edges and/or vertices, the underlying containers may have a capacity that significantly exceeds the size of the graph. The function below corrects this.

shrink_to_fit
()[source]¶ Force the physical capacity of the underlying containers to match the graph’s actual size, potentially freeing memory back to the system.
Directedness and reversal of edgesNote
These functions do not actually modify the graph, and are fully reversible. They are also very cheap, and have an \(O(1)\) complexity.

set_reversed
(is_reversed)[source]¶ Reverse the direction of the edges, if
is_reversed
isTrue
, or maintain the original direction 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
org
), value typevalue_type
, and return it. If provided, the values will be initialized byvals
, which should be a sequence.

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

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

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

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

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

new_gp
(value_type, val=None)¶ Alias to
new_graph_property()
.
New property maps can be created by copying already existing ones.

copy_property
(src, tgt=None, value_type=None, g=None, full=True)[source]¶ Copy contents of
src
property totgt
property. Iftgt
is None, then a new property map of the same type (or with the type given by the optionalvalue_type
parameter) is created, and returned. The optional parameterg
specifies the source graph to copy properties from (defaults to self). Iffull == False
, in the case of filtered graphs only the unmasked values are copied (with the remaining ones taking the typedependent default value).

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 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 aPropertyMap
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 aPropertyMap
class, which is immutable, and cannot be accessed as an array.Additionally, the indexes may not necessarily lie in the range [0,
num_edges()
 1]. However this will always happen whenever no edges are deleted from the graph.

edge_index_range
¶ The size of the range of edge indexes.

reindex_edges
()[source]¶ Reset the edge indexes so that they lie in the [0,
num_edges()
 1] range. The index ordering will be compatible with the sequence returned by theedges()
function.Warning
Calling this function will invalidate all existing edge property maps, if the index ordering is modified! The property maps will still be usable, but their contents will still be tied to the old indexes, and thus may become scrambled.
Internal property mapsInternal property maps are just like regular property maps, with the only exception that they are saved and loaded to/from files together with the graph itself. See internal property maps for more details.
Note
All dictionaries below are mutable. However, any dictionary returned below is only an oneway proxy to the internallykept properties. If you modify this object, the change will be propagated to the internal dictionary, but not viceversa. Keep this in mind if you intend to keep a copy of the returned object.

properties
¶ Dictionary of internal properties. Keys must always be a tuple, where the first element if a string from the set {‘v’, ‘e’, ‘g’}, representing a vertex, edge or graph property, respectively, and the second element is the name of the property map.
Examples
>>> g = gt.Graph() >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>") >>> del g.properties[("e", "foo")]

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

vp
¶ Alias to
vertex_properties
.

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

ep
¶ Alias to
edge_properties
.

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

gp
¶ Alias to
graph_properties
.

list_properties
()[source]¶ Print a list of all internal properties.
Examples
>>> g = gt.Graph() >>> g.properties[("e", "foo")] = g.new_edge_property("vector<double>") >>> g.vertex_properties["foo"] = g.new_vertex_property("double") >>> g.vertex_properties["bar"] = g.new_vertex_property("python::object") >>> g.graph_properties["gnat"] = g.new_graph_property("string", "hi there!") >>> g.list_properties() gnat (graph) (type: string, val: hi there!) bar (vertex) (type: python::object) foo (vertex) (type: double) foo (edge) (type: vector<double>)
Filtering of vertices and edges.See Graph filtering for more details.
Note
These functions do not actually modify the graph, and are fully reversible. They are also very cheap, and have an \(O(1)\) complexity.

set_filters
(eprop, vprop, inverted_edges=False, inverted_vertices=False)[source]¶ Set the boolean properties for edge and vertex filters, respectively. Only the vertices and edges with value different than
False
are kept in the filtered graph. If either theinverted_edges
orinverted_vertex
options are supplied with the valueTrue
, only the edges or vertices with valueFalse
are kept. If any of the supplied property isNone
, an empty filter is constructed which allows all edges or vertices.

set_vertex_filter
(prop, inverted=False)[source]¶ Set the vertex boolean filter property. Only the vertices with value different than
False
are kept in the filtered graph. If theinverted
option is supplied with valueTrue
, only the vertices with valueFalse
are kept. If the supplied property isNone
, the filter is replaced by an uniform filter allowing all vertices.

get_vertex_filter
()[source]¶ Return a tuple with the vertex filter property and bool value indicating whether or not it is inverted.

set_edge_filter
(prop, inverted=False)[source]¶ Set the edge boolean filter property. Only the edges with value different than
False
are kept in the filtered graph. If theinverted
option is supplied with valueTrue
, only the edges with valueFalse
are kept. If the supplied property isNone
, the filter is replaced by an uniform filter allowing all edges.

get_edge_filter
()[source]¶ Return a tuple with the edge filter property and bool value indicating whether or not it is inverted.
Warning
The purge functions below irreversibly remove the filtered vertices or edges from the graph. Note that, contrary to the functions above, these are \(O(V)\) and \(O(E)\) operations, respectively.

purge_vertices
(in_place=False)[source]¶ Remove all vertices of the graph which are currently being filtered out. This operation is not reversible.
If the option
in_place == True
is given, the algorithm will remove the filtered vertices and reindex all property maps which are tied with the graph. This is a slow operation which has an \(O(V^2)\) complexity.If
in_place == False
, the graph and its vertex and edge property maps are temporarily copied to a new unfiltered graph, which will replace the contents of the original graph. This is a fast operation with an \(O(V + E)\) complexity. This is the default behaviour if no option is given.

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

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

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


class
graph_tool.
GraphView
(g, vfilt=None, efilt=None, directed=None, reversed=False, skip_properties=False, skip_vfilt=False, skip_efilt=False)[source]¶ Bases:
graph_tool.Graph
A view of selected vertices or edges of another graph.
This class uses shared data from another
Graph
instance, but allows for local filtering of vertices and/or edges, edge directionality or reversal. See Graph views for more details and examples.The existence of a
GraphView
object does not affect the original graph, except if the graph view is modified (addition or removal of vertices or edges), in which case the modification is directly reflected in the original graph (and viceversa), since they both point to the same underlying data. Because of this, instances ofPropertyMap
can be used interchangeably with a graph and its views.The argument
g
must be an instance of aGraph
class. If specified,vfilt
andefilt
select which vertices and edges are filtered, respectively. These parameters can either be a booleanvaluedPropertyMap
or andarray
, which specify which vertices/edges are selected, or an unary function that returnsTrue
if a given vertex/edge is to be selected, orFalse
otherwise.The boolean parameter
directed
can be used to set the directionality of the graph view. Ifdirected is None
, the directionality is inherited fromg
.If
reversed == True
, the direction of the edges is reversed.If
vfilt
orefilt
is anything other than aPropertyMap
instance, the instantiation running time is \(O(V)\) and \(O(E)\), respectively. Otherwise, the running time is \(O(1)\).If either
skip_properties
,skip_vfilt
orskip_efilt
isTrue
, then the internal properties, vertex filter or edge filter of the original graph are ignored, respectively.
base
¶ Base graph.


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

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

all_neighbours
()¶ Return an iterator over all neighbours (both in or out).

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

in_neighbours
()¶ Return an iterator over the inneighbours.

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

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

out_neighbours
()¶ Return an iterator over the outneighbours.


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

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


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

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

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

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

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

ma
¶ The same as the
a
attribute, but instead aMaskedArray
object is returned, which contains only entries for vertices/edges which are not filtered out. If there are no filters in place, a regular:class:`~graph_tool.PropertyArray`
is returned, which is identical to thea
attribute.

get_2d_array
(pos)[source]¶ Return a twodimensional array with a copy of the entries of the vectorvalued property map. The parameter
pos
must be a sequence of integers which specifies the indexes of the property values which will be used.

set_2d_array
(a, pos=None)[source]¶ Set the entries of the vectorvalued property map from a twodimensional array
a
. If given, the parameterpos
must be a sequence of integers which specifies the indexes of the property values which will be set.

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


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


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

graph_tool.
load_graph_from_csv
(file_name, directed=True, eprop_types=None, eprop_names=None, string_vals=True, hashed=False, skip_first=False, ecols=(0, 1), csv_options={'quotechar': '"', 'delimiter': ', '})[source]¶ Load a graph from a
csv
file containing a list of edges and edge properties.Parameters: file_name :
str
or filelike objectFile in :mod:
csv
format, with edges given in each row.directed :
bool
(optional, default:False
)Whether or not the graph is directed.
eprop_types : list of
str
(optional, default:None
)List of edge property types to be read from remaining columns (if this is
None
, all properties will be of typestring
.eprop_names : list of
str
(optional, default:None
)List of edge property names to be used for the remaining columns (if this is
None
, the properties will be called “c1, c2, ...”).string_vals :
bool
(optional, default:False
)If
True
, the vertex values are assumed to be arbitrary strings, otherwise they will be assumed to correspond to integers.hashed :
bool
(optional, default:False
)If
True
andstring_vals == False
, 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. Ifstring_vals == True
, this automatically meanshashed = True
.skip_first :
bool
(optional, default:False
)If
True
the first line of the file will be skipped.ecols : pair of
int
(optional, default:(0,1)
)Line columns used as source and target for the edges.
csv_options :
dict
(optional, default:{"delimiter": ",", "quotechar": '"'}
)Options to be passed to the
csv.reader()
parser.Returns: g :
Graph
The loaded graph. It will contain additional columns in the file as internal edge property maps. If
hashed == True
, it will also contain an internal vertex property map with the vertex names.

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

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

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

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

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

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

graph_tool.
perfect_prop_hash
(props, htype='int32_t')[source]¶ Given a list of property maps props of the same type, a derived list of property maps with integral type htype is returned, where each value is replaced by a perfect (i.e. unique) hash value.
Note
The hash value is deterministic, but it will not be necessarily the same for different values of props.
Available subpackages¶
graph_tool.centrality
 Centrality measuresgraph_tool.clustering
 Clustering coefficientsgraph_tool.collection
 Dataset collectiongraph_tool.correlations
 Correlationsgraph_tool.draw
 Graph drawing and layoutgraph_tool.flow
 Maximum flow algorithmsgraph_tool.generation
 Random graph generationgraph_tool.inference
 Statistical inference of generative network modelsgraph_tool.search
 Search algorithmsgraph_tool.spectral
 Spectral propertiesgraph_tool.stats
 Miscellaneous statisticsgraph_tool.topology
 Assessing graph topologygraph_tool.util
 Graph utilities