Professional Documents
Culture Documents
Release 1.9.1
1 Overview 1
1.1 Who uses NetworkX? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 The Python programming language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 Free software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2 Introduction 3
2.1 NetworkX Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Nodes and Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3 Graph types 9
3.1 Which graph class should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Basic graph types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
4 Algorithms 127
4.1 Approximation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
4.2 Assortativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4.3 Bipartite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
4.4 Blockmodeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
4.5 Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
4.6 Centrality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
4.7 Chordal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
4.8 Clique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
4.9 Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
4.10 Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
4.11 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
4.12 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
4.13 Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
4.14 Cycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
4.15 Directed Acyclic Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
4.16 Distance Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
4.17 Distance-Regular Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
4.18 Dominating Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
4.19 Eulerian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
4.20 Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
4.21 Graphical degree sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
4.22 Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
4.23 Isolates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
4.24 Isomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
4.25 Link Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
i
4.26 Link Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
4.27 Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
4.28 Maximal independent set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
4.29 Minimum Spanning Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
4.30 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
4.31 Rich Club . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
4.32 Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
4.33 Simple Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
4.34 Swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
4.35 Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
4.36 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
4.37 Vitality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
5 Functions 339
5.1 Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
5.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
5.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
5.4 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
5.5 Freezing graph structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
ii
9.4 GEXF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
9.5 GML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431
9.6 Pickle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
9.7 GraphML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
9.8 JSON . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
9.9 LEDA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
9.10 YAML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
9.11 SparseGraph6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
9.12 Pajek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
9.13 GIS Shapefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
10 Drawing 455
10.1 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
10.2 Graphviz AGraph (dot) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
10.3 Graphviz with pydot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
10.4 Graph Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
11 Exceptions 473
12 Utilities 475
12.1 Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
12.2 Data Structures and Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
12.3 Random Sequence Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
12.4 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
12.5 Cuthill-Mckee Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
12.6 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
13 License 485
14 Citing 487
15 Credits 489
16 Glossary 491
Bibliography 493
Index 505
iii
iv
CHAPTER
ONE
OVERVIEW
NetworkX is a Python language software package for the creation, manipulation, and study of the structure, dynamics,
and function of complex networks.
With NetworkX you can load and store networks in standard and nonstandard data formats, generate many types of
random and classic networks, analyze network structure, build network models, design new network algorithms, draw
networks, and much more.
The potential audience for NetworkX includes mathematicians, physicists, biologists, computer scientists, and social
scientists. Good reviews of the state-of-the-art in the science of complex networks are presented in Albert and Barabási
[BA02], Newman [Newman03], and Dorogovtsev and Mendes [DM03]. See also the classic texts [Bollobas01],
[Diestel97] and [West01] for graph theoretic results and terminology. For basic graph algorithms, we recommend the
texts of Sedgewick, e.g. [Sedgewick01] and [Sedgewick02] and the survey of Brandes and Erlebach [BE05].
1.2 Goals
Python is a powerful programming language that allows simple and flexible representations of networks, and clear and
concise expressions of network algorithms (and other algorithms too). Python has a vibrant and growing ecosystem
of packages that NetworkX uses to provide more features such as numerical linear algebra and drawing. In addition
Python is also an excellent “glue” language for putting together pieces of software from other languages which allows
reuse of legacy code and engineering of high-performance algorithms [Langtangen04].
Equally important, Python is free, well-supported, and a joy to use.
1
NetworkX Reference, Release 1.9.1
In order to make the most out of NetworkX you will want to know how to write basic programs in Python. Among
the many guides to Python, we recommend the documentation at http://www.python.org and the text by Alex Martelli
[Martelli03].
NetworkX is free software; you can redistribute it and/or modify it under the terms of the BSD License. We welcome
contributions from the community. Information on NetworkX development is found at the NetworkX Developer Zone
at Github https://github.com/networkx/networkx
1.5 History
NetworkX was born in May 2002. The original version was designed and written by Aric Hagberg, Dan Schult, and
Pieter Swart in 2002 and 2003. The first public release was in April 2005.
Many people have contributed to the success of NetworkX. Some of the contributors are listed in the credits.
• A Brief Tour
• Installing
• Reference
• Examples
2 Chapter 1. Overview
CHAPTER
TWO
INTRODUCTION
The structure of NetworkX can be seen by the organization of its source code. The package provides classes for graph
objects, generators to create standard graphs, IO routines for reading in existing datasets, algorithms to analyse the
resulting networks and some basic drawing tools.
Most of the NetworkX API is provided by functions which take a graph object as an argument. Methods of the graph
object are limited to basic manipulation and reporting. This provides modularity of code and documentation. It also
makes it easier for newcomers to learn about the package in stages. The source code for each module is meant to be
easy to read and reading this Python code is actually a good way to learn more about network algorithms, but we have
put a lot of effort into making the documentation sufficient and friendly. If you have suggestions or questions please
contact us by joining the NetworkX Google group.
Classes are named using CamelCase (capital letters at the start of each word). functions, methods and variable names
are lower_case_underscore (lowercase with an underscore representing a space between words).
After starting Python, import the networkx module with (the recommended way)
>>> import networkx as nx
To save repetition, in the documentation we assume that NetworkX has been imported this way.
If importing networkx fails, it means that Python cannot find the installed module. Check your installation and your
PYTHONPATH.
The following basic graph types are provided as Python classes:
Graph This class implements an undirected graph. It ignores multiple edges between two nodes. It does allow
self-loop edges between a node and itself.
DiGraph Directed graphs, that is, graphs with directed edges. Operations common to directed graphs, (a subclass of
Graph).
MultiGraph A flexible graph class that allows multiple undirected edges between pairs of nodes. The additional
flexibility leads to some degradation in performance, though usually not significant.
MultiDiGraph A directed version of a MultiGraph.
Empty graph-like objects are created with
>>> G=nx.Graph()
>>> G=nx.DiGraph()
>>> G=nx.MultiGraph()
>>> G=nx.MultiDiGraph()
3
NetworkX Reference, Release 1.9.1
All graph classes allow any hashable object as a node. Hashable objects include strings, tuples, integers, and more.
Arbitrary edge attributes such as weights and labels can be associated with an edge.
The graph internal data structures are based on an adjacency list representation and implemented using Python dic-
tionary datastructures. The graph adjaceny structure is implemented as a Python dictionary of dictionaries; the outer
dictionary is keyed by nodes to values that are themselves dictionaries keyed by neighboring node to the edge at-
tributes associated with that edge. This “dict-of-dicts” structure allows fast addition, deletion, and lookup of nodes
and neighbors in large graphs. The underlying datastructure is accessed directly by methods (the programming in-
terface “API”) in the class definitions. All functions, on the other hand, manipulate graph-like objects solely via
those API methods and not by acting directly on the datastructure. This design allows for possible replacement of the
‘dicts-of-dicts’-based datastructure with an alternative datastructure that implements the same methods.
2.1.1 Graphs
The first choice to be made when using NetworkX is what type of graph object to use. A graph (network) is a collection
of nodes together with a collection of edges that are pairs of nodes. Attributes are often associated with nodes and/or
edges. NetworkX graph objects come in different flavors depending on two main properties of the network:
• Directed: Are the edges directed? Does the order of the edge pairs (u,v) matter? A directed graph is specified
by the “Di” prefix in the class name, e.g. DiGraph(). We make this distinction because many classical graph
properties are defined differently for directed graphs.
• Multi-edges: Are multiple edges allowed between each pair of nodes? As you might imagine, multiple edges
requires a different data structure, though tricky users could design edge data objects to support this function-
ality. We provide a standard data structure and interface for this type of graph using the prefix “Multi”, e.g.
MultiGraph().
The basic graph classes are named: Graph, DiGraph, MultiGraph, and MultiDiGraph
The next choice you have to make when specifying a graph is what kinds of nodes and edges to use.
If the topology of the network is all you care about then using integers or strings as the nodes makes sense and you
need not worry about edge data. If you have a data structure already in place to describe nodes you can simply use
that structure as your nodes provided it is hashable. If it is not hashable you can use a unique identifier to represent
the node and assign the data as a node attribute.
Edges often have data associated with them. Arbitrary data can associated with edges as an edge attribute. If the data
is numeric and the intent is to represent a weighted graph then use the ‘weight’ keyword for the attribute. Some of the
graph algorithms, such as Dijkstra’s shortest path algorithm, use this attribute name to get the weight for each edge.
Other attributes can be assigned to an edge by using keyword/value pairs when adding edges. You can use any keyword
except ‘weight’ to name your attribute and can then easily query the edge data by that attribute keyword.
Once you’ve decided how to encode the nodes and edges, and whether you have an undirected/directed graph with or
without multiedges you are ready to build your network.
4 Chapter 2. Introduction
NetworkX Reference, Release 1.9.1
Class methods are used for the basic reporting functions neighbors, edges and degree. Reporting of lists is often needed
only to iterate through that list so we supply iterator versions of many property reporting methods. For example edges()
and nodes() have corresponding methods edges_iter() and nodes_iter(). Using these methods when you can will save
memory and often time as well.
The basic graph relationship of an edge can be obtained in two basic ways. One can look for neighbors of a node or
one can look for edges incident to a node. We jokingly refer to people who focus on nodes/neighbors as node-centric
and people who focus on edges as edge-centric. The designers of NetworkX tend to be node-centric and view edges
as a relationship between nodes. You can see this by our avoidance of notation like G[u,v] in favor of G[u][v]. Most
data structures for sparse graphs are essentially adjacency lists and so fit this perspective. In the end, of course, it
doesn’t really matter which way you examine the graph. G.edges() removes duplicate representations of each edge
while G.neighbors(n) or G[n] is slightly faster but doesn’t remove duplicates.
Any properties that are more complicated than edges, neighbors and degree are provided by functions. For example
nx.triangles(G,n) gives the number of triangles which include node n as a vertex. These functions are grouped in the
code and documentation under the term algorithms.
2.2.3 Algorithms
A number of graph algorithms are provided with NetworkX. These include shortest path, and breadth first search (see
traversal), clustering and isomorphism algorithms and others. There are many that we have not developed yet too. If
you implement a graph algorithm that might be useful for others please let us know through the NetworkX Google
group or the Github Developer Zone.
As an example here is code to use Dijkstra’s algorithm to find the shortest weighted path:
>>> G=nx.Graph()
>>> e=[('a','b',0.3),('b','c',0.9),('a','c',0.5),('c','d',1.2)]
>>> G.add_weighted_edges_from(e)
>>> print(nx.dijkstra_path(G,'a','d'))
['a', 'c', 'd']
2.2.4 Drawing
While NetworkX is not designed as a network layout tool, we provide a simple interface to drawing packages and some
simple layout algorithms. We interface to the excellent Graphviz layout tools like dot and neato with the (suggested)
pygraphviz package or the pydot interface. Drawing can be done using external programs or the Matplotlib Python
package. Interactive GUI interfaces are possible though not provided. The drawing tools are provided in the module
drawing.
The basic drawing functions essentially place the nodes on a scatterplot using the positions in a dictionary or computed
with a layout function. The edges are then lines between those dots.
>>> G=nx.cubical_graph()
>>> nx.draw(G) # default spring_layout
>>> nx.draw(G,pos=nx.spectral_layout(G), nodecolor='r',edge_color='b')
NetworkX uses a “dictionary of dictionaries of dictionaries” as the basic network data structure. This allows fast
lookup with reasonable storage for large sparse networks. The keys are nodes so G[u] returns an adjacency dictionary
keyed by neighbor to the edge attribute dictionary. The expression G[u][v] returns the edge attribute dictionary itself.
A dictionary of lists would have also been possible, but not allowed fast edge detection nor convenient storage of edge
data.
Advantages of dict-of-dicts-of-dicts data structure:
• Find edges and remove edges with two dictionary look-ups.
• Prefer to “lists” because of fast lookup with sparse storage.
• Prefer to “sets” since data can be attached to edge.
• G[u][v] returns the edge attribute dictionary.
• n in G tests if node n is in graph G.
• for n in G: iterates through the graph.
• for nbr in G[n]: iterates through neighbors.
As an example, here is a representation of an undirected graph with the edges (‘A’,’B’), (‘B’,’C’)
>>> G=nx.Graph()
>>> G.add_edge('A','B')
>>> G.add_edge('B','C')
>>> print(G.adj)
{'A': {'B': {}}, 'C': {'B': {}}, 'B': {'A': {}, 'C': {}}}
The data structure gets morphed slightly for each base graph class. For DiGraph two dict-of-dicts-of-dicts structures
are provided, one for successors and one for predecessors. For MultiGraph/MultiDiGraph we use a dict-of-dicts-of-
6 Chapter 2. Introduction
NetworkX Reference, Release 1.9.1
dicts-of-dicts 1 where the third dictionary is keyed by an edge key identifier to the fourth dictionary which contains
the edge attributes for that edge between the two nodes.
Graphs use a dictionary of attributes for each edge. We use a dict-of-dicts-of-dicts data structure with the inner
dictionary storing “name-value” relationships for that edge.
>>> G=nx.Graph()
>>> G.add_edge(1,2,color='red',weight=0.84,size=300)
>>> print(G[1][2]['size'])
300
8 Chapter 2. Introduction
CHAPTER
THREE
GRAPH TYPES
Overview
Graph(data=None, **attr)
Base class for undirected graphs.
A Graph stores nodes and edges with optional data, or attributes.
Graphs hold undirected edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.
Edges are represented as links between nodes with optional key/value attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
9
NetworkX Reference, Release 1.9.1
See also:
DiGraph, MultiGraph, MultiDiGraph
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.Graph()
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2,3])
>>> G.add_nodes_from(range(100,110))
>>> H=nx.Graph()
>>> H.add_path([0,1,2,3,4,5,6,7,8,9])
>>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1,2),(1,3)])
or a collection of edges,
>>> G.add_edges_from(H.edges())
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.Graph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Shortcuts:
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n<3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
The fastest way to traverse all edges of a graph is via adjacency_iter(), but the edges() method is often more
convenient.
>>> for n,nbrsdict in G.adjacency_iter():
... for nbr,eattr in nbrsdict.items():
... if 'weight' in eattr:
... (n,nbr,eattr['weight'])
(1, 2, 4)
(2, 1, 4)
(2, 3, 8)
(3, 2, 8)
>>> [ (u,v,edata['weight']) for u,v,edata in G.edges(data=True) if 'weight' in edata ]
[(1, 2, 4), (2, 3, 8)]
Reporting:
Simple graph information is obtained using methods. Iterator versions of many reporting methods exist for
efficiency. Methods exist for reporting nodes(), edges(), neighbors() and degree() as well as the number of
nodes and edges.
For details on these and other miscellaneous methods, see below.
__init__
Graph.__init__(data=None, **attr)
Initialize a graph with edges, name, graph attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
name : string, optional (default=’‘)
An optional name for the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
convert
Examples
add_node
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
Examples
add_nodes_from
Graph.add_nodes_from(nodes, **attr)
Add multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple
take precedence over attributes specified generally.
See also:
add_node
Examples
remove_node
Graph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n : node
A node in the graph
Raises NetworkXError
If n is not in the graph.
See also:
remove_nodes_from
Examples
remove_nodes_from
Graph.remove_nodes_from(nodes)
Remove multiple nodes.
Examples
add_edge
Notes
Examples
add_edges_from
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in edges as a tuple take precedence over attributes specified generally.
Examples
add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
remove_edge
Graph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u,v: nodes
Remove the edge between nodes u and v.
Raises NetworkXError
If there is not an edge between u and v.
See also:
Examples
remove_edges_from
Graph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can
be:
• 2-tuples (u,v) edge between u and v.
• 3-tuples (u,v,k) where k is ignored.
See also:
Notes
Examples
add_star
Graph.add_star(nodes, **attr)
Add a star.
The first node in nodes is the middle of the star. It is connected to all other nodes.
Parameters nodes : iterable container
A container of nodes.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in star.
See also:
add_path, add_cycle
Examples
add_path
Graph.add_path(nodes, **attr)
Add a path.
Parameters nodes : iterable container
A container of nodes. A path will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in path.
See also:
add_star, add_cycle
Examples
add_cycle
Graph.add_cycle(nodes, **attr)
Add a cycle.
Parameters nodes: iterable container
A container of nodes. A cycle will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in cycle.
See also:
add_path, add_star
Examples
clear
Graph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
nodes
Graph.nodes(data=False)
Return a list of the nodes in the graph.
Parameters data : boolean, optional (default=False)
If False return a list of nodes. If True return a two-tuple of node and node data dictionary
Returns nlist : list
A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary).
Examples
>>> G.nodes(data=True)
[(0, {}), (1, {'time': '5pm'}), (2, {})]
nodes_iter
Graph.nodes_iter(data=False)
Return an iterator over the nodes.
Parameters data : boolean, optional (default=False)
If False the iterator returns nodes. If True return a two-tuple of node and node data
dictionary
Returns niter : iterator
An iterator over nodes. If data=True the iterator gives two-tuples containing (node, node
data, dictionary)
Notes
If the node data is not required it is simpler and equivalent to use the expression ‘for n in G’.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
Examples
__iter__
Graph.__iter__()
Iterate over the nodes. Use the expression ‘for n in G’.
Returns niter : iterator
An iterator over all nodes in the graph.
Examples
edges
Graph.edges(nbunch=None, data=False)
Return a list of edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
Return two tuples (u,v) (False) or three-tuples (u,v,data) (True).
Returns edge_list: list of edge tuples
Edges that are adjacent to any node in nbunch, or a list of all edges if nbunch is not
specified.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
edges_iter
Graph.edges_iter(nbunch=None, data=False)
Return an iterator over the edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
If True, return edge attribute dict in 3-tuple (u,v,data).
Returns edge_iter : iterator
An iterator of (u,v) or (u,v,d) tuples of edges.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
get_edge_data
Graph.get_edge_data(u, v, default=None)
Return the attribute dictionary associated with edge (u,v).
Parameters u,v : nodes
default: any Python object (default=None)
Value to return if the edge (u,v) is not found.
Returns edge_dict : dictionary
The edge attribute dictionary.
Notes
Warning: Assigning G[u][v] corrupts the graph data structure. But it is safe to assign attributes to that dictionary,
>>> G[0][1]['weight'] = 7
>>> G[0][1]['weight']
7
>>> G[1][0]['weight']
7
Examples
neighbors
Graph.neighbors(n)
Return a list of the nodes connected to the node n.
Parameters n : node
A node in the graph
Returns nlist : list
A list of nodes that are adjacent to n.
Raises NetworkXError
If the node n is not in the graph.
Notes
It is usually more convenient (and faster) to access the adjacency dictionary as G[n]:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge('a','b',weight=7)
>>> G['a']
{'b': {'weight': 7}}
Examples
neighbors_iter
Graph.neighbors_iter(n)
Return an iterator over all neighbors of node n.
Notes
Examples
__getitem__
Graph.__getitem__(n)
Return a dict of neighbors of node n. Use the expression ‘G[n]’.
Parameters n : node
A node in the graph.
Returns adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
Notes
G[n] is similar to G.neighbors(n) but the internal data dictionary is returned instead of a list.
Assigning G[n] will corrupt the internal graph data structure. Use G[n] for reading data only.
Examples
adjacency_list
Graph.adjacency_list()
Return an adjacency list representation of the graph.
The output adjacency list is in the order of G.nodes(). For directed graphs, only outgoing adjacencies are
included.
Returns adj_list : lists of lists
The adjacency structure of the graph as a list of lists.
See also:
adjacency_iter
Examples
adjacency_iter
Graph.adjacency_iter()
Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included.
Returns adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in the graph.
See also:
adjacency_list
Examples
nbunch_iter
Graph.nbunch_iter(nbunch=None)
Return an iterator of nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
Returns niter : iterator
An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate
over all nodes in the graph.
Raises NetworkXError
If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
See also:
Graph.__iter__
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if any
object in nbunch is not hashable, a NetworkXError is raised.
has_node
Graph.has_node(n)
Return True if the graph contains the node n.
Parameters n : node
Examples
__contains__
Graph.__contains__(n)
Return True if n is a node, False otherwise. Use the expression ‘n in G’.
Examples
has_edge
Graph.has_edge(u, v)
Return True if the edge (u,v) is in the graph.
Parameters u,v : nodes
Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None)
Python objects.
Returns edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
Can be called either using two nodes u,v or edge tuple (u,v)
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.has_edge(0,1) # using two nodes
True
>>> e = (0,1)
>>> G.has_edge(*e) # e is a 2-tuple (u,v)
True
>>> e = (0,1,{'weight':7})
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u,v,data_dictionary)
True
order
Graph.order()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
number_of_nodes, __len__
number_of_nodes
Graph.number_of_nodes()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
order, __len__
Examples
__len__
Graph.__len__()
Return the number of nodes. Use the expression ‘len(G)’.
Returns nnodes : int
The number of nodes in the graph.
Examples
degree
Graph.degree(nbunch=None, weight=None)
Return the degree of a node or nodes.
The node degree is the number of edges adjacent to that node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and degree as values or a number if a single node is
specified.
Examples
degree_iter
Graph.degree_iter(nbunch=None, weight=None)
Return an iterator for (node, degree).
The node degree is the number of edges adjacent to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See also:
degree
Examples
size
Graph.size(weight=None)
Return the number of edges.
Parameters weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns nedges : int
The number of edges or sum of edge weights in the graph.
See also:
number_of_edges
Examples
number_of_edges
Graph.number_of_edges(u=None, v=None)
Return the number of edges between two nodes.
Parameters u,v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between u and v. Otherwise return
the total number of all edges.
Returns nedges : int
The number of edges in the graph. If nodes u and v are specified return the number of
edges between those nodes.
See also:
size
Examples
nodes_with_selfloops
Graph.nodes_with_selfloops()
Return a list of nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Examples
selfloop_edges
Graph.selfloop_edges(data=False)
Return a list of selfloop edges.
A selfloop edge has the same node at both ends.
Parameters data : bool, optional (default=False)
Return selfloop edges as two tuples (u,v) (data=False) or three-tuples (u,v,data)
(data=True)
Returns edgelist : list of edge tuples
A list of all selfloop edges.
See also:
nodes_with_selfloops, number_of_selfloops
Examples
number_of_selfloops
Graph.number_of_selfloops()
Return the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns nloops : int
The number of selfloops.
See also:
nodes_with_selfloops, selfloop_edges
Examples
copy
Graph.copy()
Return a copy of the graph.
Returns G : Graph
A copy of the graph.
See also:
Notes
This makes a complete copy of the graph including all of the node or edge attributes.
Examples
to_undirected
Graph.to_undirected()
Return an undirected copy of the graph.
Returns G : Graph/MultiGraph
A deepcopy of the graph.
See also:
copy, add_edge, add_edges_from
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
to_directed
Graph.to_directed()
Return a directed representation of the graph.
Returns G : DiGraph
A directed graph with the same name, same nodes, and with each edge (u,v,data) re-
placed by two directed edges (u,v,data) and (v,u,data).
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
subgraph
Graph.subgraph(nbunch)
Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes.
Parameters nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns G : Graph
A subgraph of the graph with the same edge attributes.
Notes
The graph, edge or node attributes just point to the original graph. So changes to the node or edge structure will
not be reflected in the original graph while changes to the attributes will.
To create a subgraph with its own copy of the edge/node attributes use: nx.Graph(G.subgraph(nbunch))
If edge attributes are containers, a deep copy can be obtained using: G.subgraph(nbunch).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([ n in G if n
not in set(nbunch)])
Examples
Overview
DiGraph(data=None, **attr)
Base class for directed graphs.
A DiGraph stores nodes and edges with optional data, or attributes.
DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.
Edges are represented as links between nodes with optional key/value attributes.
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.DiGraph()
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2,3])
>>> G.add_nodes_from(range(100,110))
>>> H=nx.Graph()
>>> H.add_path([0,1,2,3,4,5,6,7,8,9])
>>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1,2),(1,3)])
or a collection of edges,
>>> G.add_edges_from(H.edges())
If some edges connect nodes not yet in the graph, the nodes are added automatically. There are no errors when
adding nodes or edges that already exist.
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.DiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Shortcuts:
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n<3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
The fastest way to traverse all edges of a graph is via adjacency_iter(), but the edges() method is often more
convenient.
>>> for n,nbrsdict in G.adjacency_iter():
... for nbr,eattr in nbrsdict.items():
... if 'weight' in eattr:
... (n,nbr,eattr['weight'])
(1, 2, 4)
(2, 3, 8)
>>> [ (u,v,edata['weight']) for u,v,edata in G.edges(data=True) if 'weight' in edata ]
[(1, 2, 4), (2, 3, 8)]
Reporting:
Simple graph information is obtained using methods. Iterator versions of many reporting methods exist for
efficiency. Methods exist for reporting nodes(), edges(), neighbors() and degree() as well as the number of
nodes and edges.
For details on these and other miscellaneous methods, see below.
__init__
DiGraph.__init__(data=None, **attr)
Initialize a graph with edges, name, graph attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
name : string, optional (default=’‘)
An optional name for the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
convert
Examples
add_node
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
Examples
add_nodes_from
DiGraph.add_nodes_from(nodes, **attr)
Add multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple
take precedence over attributes specified generally.
See also:
add_node
Examples
remove_node
DiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n : node
A node in the graph
Raises NetworkXError
If n is not in the graph.
See also:
remove_nodes_from
Examples
>>> G.edges()
[]
remove_nodes_from
DiGraph.remove_nodes_from(nbunch)
Remove multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it
is silently ignored.
See also:
remove_node
Examples
add_edge
Notes
Examples
add_edges_from
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in edges as a tuple take precedence over attributes specified generally.
Examples
add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
remove_edge
DiGraph.remove_edge(u, v)
Remove the edge between u and v.
Parameters u,v: nodes
Remove the edge between nodes u and v.
Raises NetworkXError
Examples
remove_edges_from
DiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can
be:
• 2-tuples (u,v) edge between u and v.
• 3-tuples (u,v,k) where k is ignored.
See also:
Notes
Examples
add_star
DiGraph.add_star(nodes, **attr)
Add a star.
The first node in nodes is the middle of the star. It is connected to all other nodes.
Parameters nodes : iterable container
A container of nodes.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in star.
See also:
add_path, add_cycle
Examples
add_path
DiGraph.add_path(nodes, **attr)
Add a path.
Parameters nodes : iterable container
A container of nodes. A path will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in path.
See also:
add_star, add_cycle
Examples
add_cycle
DiGraph.add_cycle(nodes, **attr)
Add a cycle.
Parameters nodes: iterable container
A container of nodes. A cycle will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in cycle.
See also:
add_path, add_star
Examples
clear
DiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
nodes
DiGraph.nodes(data=False)
Return a list of the nodes in the graph.
Parameters data : boolean, optional (default=False)
If False return a list of nodes. If True return a two-tuple of node and node data dictionary
Returns nlist : list
A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary).
Examples
nodes_iter
DiGraph.nodes_iter(data=False)
Return an iterator over the nodes.
Parameters data : boolean, optional (default=False)
If False the iterator returns nodes. If True return a two-tuple of node and node data
dictionary
Returns niter : iterator
An iterator over nodes. If data=True the iterator gives two-tuples containing (node, node
data, dictionary)
Notes
If the node data is not required it is simpler and equivalent to use the expression ‘for n in G’.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
Examples
__iter__
DiGraph.__iter__()
Iterate over the nodes. Use the expression ‘for n in G’.
Returns niter : iterator
An iterator over all nodes in the graph.
Examples
edges
DiGraph.edges(nbunch=None, data=False)
Return a list of edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
Return two tuples (u,v) (False) or three-tuples (u,v,data) (True).
Returns edge_list: list of edge tuples
Edges that are adjacent to any node in nbunch, or a list of all edges if nbunch is not
specified.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
edges_iter
DiGraph.edges_iter(nbunch=None, data=False)
Return an iterator over the edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
If True, return edge attribute dict in 3-tuple (u,v,data).
Returns edge_iter : iterator
An iterator of (u,v) or (u,v,d) tuples of edges.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
out_edges
DiGraph.out_edges(nbunch=None, data=False)
Return a list of edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
Return two tuples (u,v) (False) or three-tuples (u,v,data) (True).
Returns edge_list: list of edge tuples
Edges that are adjacent to any node in nbunch, or a list of all edges if nbunch is not
specified.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
out_edges_iter
DiGraph.out_edges_iter(nbunch=None, data=False)
Return an iterator over the edges.
Edges are returned as tuples with optional data in the order (node, neighbor, data).
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
If True, return edge attribute dict in 3-tuple (u,v,data).
Returns edge_iter : iterator
An iterator of (u,v) or (u,v,d) tuples of edges.
See also:
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
in_edges
DiGraph.in_edges(nbunch=None, data=False)
Return a list of the incoming edges.
See also:
in_edges_iter
DiGraph.in_edges_iter(nbunch=None, data=False)
Return an iterator over the incoming edges.
Parameters nbunch : iterable container, optional (default= all nodes)
A container of nodes. The container will be iterated through once.
data : bool, optional (default=False)
If True, return edge attribute dict in 3-tuple (u,v,data).
Returns in_edge_iter : iterator
An iterator of (u,v) or (u,v,d) tuples of incoming edges.
See also:
get_edge_data
DiGraph.get_edge_data(u, v, default=None)
Return the attribute dictionary associated with edge (u,v).
Parameters u,v : nodes
default: any Python object (default=None)
Value to return if the edge (u,v) is not found.
Returns edge_dict : dictionary
The edge attribute dictionary.
Notes
Warning: Assigning G[u][v] corrupts the graph data structure. But it is safe to assign attributes to that dictionary,
>>> G[0][1]['weight'] = 7
>>> G[0][1]['weight']
7
>>> G[1][0]['weight']
7
Examples
neighbors
DiGraph.neighbors(n)
Return a list of successor nodes of n.
neighbors() and successors() are the same function.
neighbors_iter
DiGraph.neighbors_iter(n)
Return an iterator over successor nodes of n.
neighbors_iter() and successors_iter() are the same.
__getitem__
DiGraph.__getitem__(n)
Return a dict of neighbors of node n. Use the expression ‘G[n]’.
Parameters n : node
A node in the graph.
Returns adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
Notes
G[n] is similar to G.neighbors(n) but the internal data dictionary is returned instead of a list.
Assigning G[n] will corrupt the internal graph data structure. Use G[n] for reading data only.
Examples
successors
DiGraph.successors(n)
Return a list of successor nodes of n.
neighbors() and successors() are the same function.
successors_iter
DiGraph.successors_iter(n)
Return an iterator over successor nodes of n.
neighbors_iter() and successors_iter() are the same.
predecessors
DiGraph.predecessors(n)
Return a list of predecessor nodes of n.
predecessors_iter
DiGraph.predecessors_iter(n)
Return an iterator over predecessor nodes of n.
adjacency_list
DiGraph.adjacency_list()
Return an adjacency list representation of the graph.
The output adjacency list is in the order of G.nodes(). For directed graphs, only outgoing adjacencies are
included.
Returns adj_list : lists of lists
The adjacency structure of the graph as a list of lists.
See also:
adjacency_iter
Examples
adjacency_iter
DiGraph.adjacency_iter()
Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included.
Returns adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in the graph.
See also:
adjacency_list
Examples
nbunch_iter
DiGraph.nbunch_iter(nbunch=None)
Return an iterator of nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
Returns niter : iterator
An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate
over all nodes in the graph.
Raises NetworkXError
If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
See also:
Graph.__iter__
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if any
object in nbunch is not hashable, a NetworkXError is raised.
has_node
DiGraph.has_node(n)
Return True if the graph contains the node n.
Parameters n : node
Examples
__contains__
DiGraph.__contains__(n)
Return True if n is a node, False otherwise. Use the expression ‘n in G’.
Examples
has_edge
DiGraph.has_edge(u, v)
Return True if the edge (u,v) is in the graph.
Parameters u,v : nodes
Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None)
Python objects.
Returns edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
Can be called either using two nodes u,v or edge tuple (u,v)
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2,3])
>>> G.has_edge(0,1) # using two nodes
True
>>> e = (0,1)
>>> G.has_edge(*e) # e is a 2-tuple (u,v)
True
>>> e = (0,1,{'weight':7})
>>> G.has_edge(*e[:2]) # e is a 3-tuple (u,v,data_dictionary)
True
order
DiGraph.order()
Return the number of nodes in the graph.
Returns nnodes : int
number_of_nodes
DiGraph.number_of_nodes()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
order, __len__
Examples
__len__
DiGraph.__len__()
Return the number of nodes. Use the expression ‘len(G)’.
Returns nnodes : int
The number of nodes in the graph.
Examples
degree
DiGraph.degree(nbunch=None, weight=None)
Return the degree of a node or nodes.
The node degree is the number of edges adjacent to that node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and degree as values or a number if a single node is
specified.
Examples
degree_iter
DiGraph.degree_iter(nbunch=None, weight=None)
Return an iterator for (node, degree).
The node degree is the number of edges adjacent to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See also:
degree, in_degree, out_degree, in_degree_iter, out_degree_iter
Examples
in_degree
DiGraph.in_degree(nbunch=None, weight=None)
Return the in-degree of a node or nodes.
Examples
in_degree_iter
DiGraph.in_degree_iter(nbunch=None, weight=None)
Return an iterator for (node, in-degree).
The node in-degree is the number of edges pointing in to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, in-degree).
See also:
degree, in_degree, out_degree, out_degree_iter
Examples
>>> G = nx.DiGraph()
>>> G.add_path([0,1,2,3])
>>> list(G.in_degree_iter(0)) # node 0 with degree 0
[(0, 0)]
>>> list(G.in_degree_iter([0,1]))
[(0, 0), (1, 1)]
out_degree
DiGraph.out_degree(nbunch=None, weight=None)
Return the out-degree of a node or nodes.
The node out-degree is the number of edges pointing out of the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and out-degree as values or a number if a single node
is specified.
Examples
out_degree_iter
DiGraph.out_degree_iter(nbunch=None, weight=None)
Return an iterator for (node, out-degree).
The node out-degree is the number of edges pointing out of the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree, out_degree, in_degree_iter
Examples
>>> G = nx.DiGraph()
>>> G.add_path([0,1,2,3])
>>> list(G.out_degree_iter(0)) # node 0 with degree 1
[(0, 1)]
>>> list(G.out_degree_iter([0,1]))
[(0, 1), (1, 1)]
size
DiGraph.size(weight=None)
Return the number of edges.
Parameters weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns nedges : int
The number of edges or sum of edge weights in the graph.
See also:
number_of_edges
Examples
number_of_edges
DiGraph.number_of_edges(u=None, v=None)
Return the number of edges between two nodes.
Parameters u,v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between u and v. Otherwise return
the total number of all edges.
Examples
nodes_with_selfloops
DiGraph.nodes_with_selfloops()
Return a list of nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Returns nodelist : list
A list of nodes with self loops.
See also:
selfloop_edges, number_of_selfloops
Examples
selfloop_edges
DiGraph.selfloop_edges(data=False)
Return a list of selfloop edges.
A selfloop edge has the same node at both ends.
Parameters data : bool, optional (default=False)
Return selfloop edges as two tuples (u,v) (data=False) or three-tuples (u,v,data)
(data=True)
Returns edgelist : list of edge tuples
Examples
number_of_selfloops
DiGraph.number_of_selfloops()
Return the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns nloops : int
The number of selfloops.
See also:
nodes_with_selfloops, selfloop_edges
Examples
copy
DiGraph.copy()
Return a copy of the graph.
Returns G : Graph
Notes
This makes a complete copy of the graph including all of the node or edge attributes.
Examples
to_undirected
DiGraph.to_undirected(reciprocal=False)
Return an undirected representation of the digraph.
Parameters reciprocal : bool (optional)
If True only keep edges that appear in both directions in the original digraph.
Returns G : Graph
An undirected graph with the same name and nodes and with edge (u,v,data) if either
(u,v,data) or (v,u,data) is in the digraph. If both edges exist in digraph and their edge
data is different, only one edge is created with an arbitrary choice of which edge data to
use. You must check and correct for this manually if desired.
Notes
If edges in both directions (u,v) and (v,u) exist in the graph, attributes for the new undirected edge will be a
combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the
edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
to_directed
DiGraph.to_directed()
Return a directed copy of the graph.
Returns G : DiGraph
A deepcopy of the graph.
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
subgraph
DiGraph.subgraph(nbunch)
Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes.
Parameters nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns G : Graph
A subgraph of the graph with the same edge attributes.
Notes
The graph, edge or node attributes just point to the original graph. So changes to the node or edge structure will
not be reflected in the original graph while changes to the attributes will.
To create a subgraph with its own copy of the edge/node attributes use: nx.Graph(G.subgraph(nbunch))
If edge attributes are containers, a deep copy can be obtained using: G.subgraph(nbunch).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([ n in G if n
not in set(nbunch)])
Examples
reverse
DiGraph.reverse(copy=True)
Return the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy : bool optional (default=True)
If True, return a new DiGraph holding the reversed edges. If False, reverse the reverse
graph is created using the original graph (this changes the original graph).
3.2.3 MultiGraph - Undirected graphs with self loops and parallel edges
Overview
MultiGraph(data=None, **attr)
An undirected graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiGraph holds undirected edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.
Edges are represented as links between nodes with optional key/value attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
Graph, DiGraph, MultiDiGraph
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.MultiGraph()
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2,3])
>>> G.add_nodes_from(range(100,110))
>>> H=nx.Graph()
>>> H.add_path([0,1,2,3,4,5,6,7,8,9])
>>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1,2),(1,3)])
or a collection of edges,
>>> G.add_edges_from(H.edges())
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.
>>> G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))])
>>> G[4]
{3: {0: {}}, 5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}}
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.MultiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}
>>> G.nodes(data=True)
[(1, {'time': '5pm'}), (3, {'time': '2pm'})]
Shortcuts:
Many common graph features allow python syntax to speed reporting.
>>> 1 in G # check if node in graph
True
>>> [n for n in G if n<3] # iterate through nodes
[1, 2]
>>> len(G) # number of nodes in graph
5
>>> G[1] # adjacency dict keyed by neighbor to edge attributes
... # Note: you should not change this dict manually!
{2: {0: {'weight': 4}, 1: {'color': 'blue'}}}
The fastest way to traverse all edges of a graph is via adjacency_iter(), but the edges() method is often more
convenient.
>>> for n,nbrsdict in G.adjacency_iter():
... for nbr,keydict in nbrsdict.items():
... for key,eattr in keydict.items():
... if 'weight' in eattr:
... (n,nbr,eattr['weight'])
(1, 2, 4)
(2, 1, 4)
(2, 3, 8)
(3, 2, 8)
>>> [ (u,v,edata['weight']) for u,v,edata in G.edges(data=True) if 'weight' in edata ]
[(1, 2, 4), (2, 3, 8)]
Reporting:
Simple graph information is obtained using methods. Iterator versions of many reporting methods exist for
efficiency. Methods exist for reporting nodes(), edges(), neighbors() and degree() as well as the number of
nodes and edges.
For details on these and other miscellaneous methods, see below.
__init__
MultiGraph.__init__(data=None, **attr)
Initialize a graph with edges, name, graph attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
name : string, optional (default=’‘)
An optional name for the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
convert
Examples
add_node
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
Examples
add_nodes_from
MultiGraph.add_nodes_from(nodes, **attr)
Add multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple
take precedence over attributes specified generally.
See also:
add_node
Examples
remove_node
MultiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n : node
A node in the graph
Raises NetworkXError
If n is not in the graph.
See also:
remove_nodes_from
Examples
remove_nodes_from
MultiGraph.remove_nodes_from(nodes)
Remove multiple nodes.
Examples
add_edge
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Examples
add_edges_from
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in edges as a tuple take precedence over attributes specified generally.
Examples
add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
remove_edge
MultiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters u,v: nodes
Remove an edge between nodes u and v.
key : hashable identifier, optional (default=None)
Used to distinguish multiple edges between a pair of nodes. If None remove a single
(abritrary) edge between u and v.
Raises NetworkXError
If there is not an edge between u and v, or if there is no edge with the specified key.
See also:
Examples
>>> G = nx.MultiGraph()
>>> G.add_path([0,1,2,3])
>>> G.remove_edge(0,1)
>>> e = (1,2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
remove_edges_from
MultiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can
be:
• 2-tuples (u,v) All edges between u and v are removed.
• 3-tuples (u,v,key) The edge identified by key is removed.
• 4-tuples (u,v,key,data) where data is ignored.
See also:
Notes
Examples
add_star
MultiGraph.add_star(nodes, **attr)
Add a star.
The first node in nodes is the middle of the star. It is connected to all other nodes.
Parameters nodes : iterable container
A container of nodes.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in star.
See also:
add_path, add_cycle
Examples
add_path
MultiGraph.add_path(nodes, **attr)
Add a path.
Parameters nodes : iterable container
A container of nodes. A path will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in path.
See also:
add_star, add_cycle
Examples
add_cycle
MultiGraph.add_cycle(nodes, **attr)
Add a cycle.
Parameters nodes: iterable container
A container of nodes. A cycle will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in cycle.
See also:
add_path, add_star
Examples
clear
MultiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
nodes
MultiGraph.nodes(data=False)
Return a list of the nodes in the graph.
Parameters data : boolean, optional (default=False)
If False return a list of nodes. If True return a two-tuple of node and node data dictionary
Returns nlist : list
A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary).
Examples
nodes_iter
MultiGraph.nodes_iter(data=False)
Return an iterator over the nodes.
Parameters data : boolean, optional (default=False)
If False the iterator returns nodes. If True return a two-tuple of node and node data
dictionary
Returns niter : iterator
An iterator over nodes. If data=True the iterator gives two-tuples containing (node, node
data, dictionary)
Notes
If the node data is not required it is simpler and equivalent to use the expression ‘for n in G’.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
Examples
__iter__
MultiGraph.__iter__()
Iterate over the nodes. Use the expression ‘for n in G’.
Returns niter : iterator
An iterator over all nodes in the graph.
Examples
edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
edges_iter
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
get_edge_data
Notes
Warning: Assigning G[u][v][key] corrupts the graph data structure. But it is safe to assign attributes to that
dictionary,
>>> G[0][1]['a']['weight'] = 10
>>> G[0][1]['a']['weight']
10
>>> G[1][0]['a']['weight']
10
Examples
neighbors
MultiGraph.neighbors(n)
Return a list of the nodes connected to the node n.
Parameters n : node
A node in the graph
Returns nlist : list
A list of nodes that are adjacent to n.
Raises NetworkXError
If the node n is not in the graph.
Notes
It is usually more convenient (and faster) to access the adjacency dictionary as G[n]:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge('a','b',weight=7)
>>> G['a']
{'b': {'weight': 7}}
Examples
neighbors_iter
MultiGraph.neighbors_iter(n)
Return an iterator over all neighbors of node n.
Notes
Examples
__getitem__
MultiGraph.__getitem__(n)
Return a dict of neighbors of node n. Use the expression ‘G[n]’.
Parameters n : node
A node in the graph.
Returns adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
Notes
G[n] is similar to G.neighbors(n) but the internal data dictionary is returned instead of a list.
Assigning G[n] will corrupt the internal graph data structure. Use G[n] for reading data only.
Examples
adjacency_list
MultiGraph.adjacency_list()
Return an adjacency list representation of the graph.
The output adjacency list is in the order of G.nodes(). For directed graphs, only outgoing adjacencies are
included.
Returns adj_list : lists of lists
The adjacency structure of the graph as a list of lists.
See also:
adjacency_iter
Examples
adjacency_iter
MultiGraph.adjacency_iter()
Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included.
Returns adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in the graph.
See also:
adjacency_list
Examples
nbunch_iter
MultiGraph.nbunch_iter(nbunch=None)
Return an iterator of nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
Returns niter : iterator
An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate
over all nodes in the graph.
Raises NetworkXError
If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
See also:
Graph.__iter__
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if any
object in nbunch is not hashable, a NetworkXError is raised.
has_node
MultiGraph.has_node(n)
Return True if the graph contains the node n.
Parameters n : node
Examples
__contains__
MultiGraph.__contains__(n)
Return True if n is a node, False otherwise. Use the expression ‘n in G’.
Examples
has_edge
MultiGraph.has_edge(u, v, key=None)
Return True if the graph has an edge between nodes u and v.
Parameters u,v : nodes
Nodes can be, for example, strings or numbers.
key : hashable identifier, optional (default=None)
If specified return True only if the edge with key is found.
Returns edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
Can be called either using two nodes u,v, an edge tuple (u,v), or an edge tuple (u,v,key).
>>> G = nx.MultiGraph() # or MultiDiGraph
>>> G.add_path([0,1,2,3])
>>> G.has_edge(0,1) # using two nodes
True
>>> e = (0,1)
>>> G.has_edge(*e) # e is a 2-tuple (u,v)
True
>>> G.add_edge(0,1,key='a')
>>> G.has_edge(0,1,key='a') # specify key
True
>>> e=(0,1,'a')
>>> G.has_edge(*e) # e is a 3-tuple (u,v,'a')
True
order
MultiGraph.order()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
number_of_nodes, __len__
number_of_nodes
MultiGraph.number_of_nodes()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
order, __len__
Examples
__len__
MultiGraph.__len__()
Return the number of nodes. Use the expression ‘len(G)’.
Returns nnodes : int
The number of nodes in the graph.
Examples
degree
MultiGraph.degree(nbunch=None, weight=None)
Return the degree of a node or nodes.
The node degree is the number of edges adjacent to that node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Examples
degree_iter
MultiGraph.degree_iter(nbunch=None, weight=None)
Return an iterator for (node, degree).
The node degree is the number of edges adjacent to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, degree).
See also:
degree
Examples
size
MultiGraph.size(weight=None)
Return the number of edges.
Parameters weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns nedges : int
The number of edges or sum of edge weights in the graph.
See also:
number_of_edges
Examples
number_of_edges
MultiGraph.number_of_edges(u=None, v=None)
Return the number of edges between two nodes.
Parameters u,v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between u and v. Otherwise return
the total number of all edges.
Returns nedges : int
The number of edges in the graph. If nodes u and v are specified return the number of
edges between those nodes.
See also:
size
Examples
nodes_with_selfloops
MultiGraph.nodes_with_selfloops()
Return a list of nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Returns nodelist : list
A list of nodes with self loops.
See also:
selfloop_edges, number_of_selfloops
Examples
selfloop_edges
MultiGraph.selfloop_edges(data=False, keys=False)
Return a list of selfloop edges.
A selfloop edge has the same node at both ends.
Parameters data : bool, optional (default=False)
Return selfloop edges as two tuples (u,v) (data=False) or three-tuples (u,v,data)
(data=True)
keys : bool, optional (default=False)
If True, return edge keys with each edge.
Returns edgelist : list of edge tuples
A list of all selfloop edges.
See also:
nodes_with_selfloops, number_of_selfloops
Examples
number_of_selfloops
MultiGraph.number_of_selfloops()
Return the number of selfloop edges.
A selfloop edge has the same node at both ends.
Returns nloops : int
The number of selfloops.
See also:
nodes_with_selfloops, selfloop_edges
Examples
copy
MultiGraph.copy()
Return a copy of the graph.
Returns G : Graph
A copy of the graph.
See also:
Notes
This makes a complete copy of the graph including all of the node or edge attributes.
Examples
to_undirected
MultiGraph.to_undirected()
Return an undirected copy of the graph.
Returns G : Graph/MultiGraph
A deepcopy of the graph.
See also:
copy, add_edge, add_edges_from
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
to_directed
MultiGraph.to_directed()
Return a directed representation of the graph.
Returns G : MultiDiGraph
A directed graph with the same name, same nodes, and with each edge (u,v,data) re-
placed by two directed edges (u,v,data) and (v,u,data).
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
subgraph
MultiGraph.subgraph(nbunch)
Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes.
Parameters nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns G : Graph
A subgraph of the graph with the same edge attributes.
Notes
The graph, edge or node attributes just point to the original graph. So changes to the node or edge structure will
not be reflected in the original graph while changes to the attributes will.
To create a subgraph with its own copy of the edge/node attributes use: nx.Graph(G.subgraph(nbunch))
If edge attributes are containers, a deep copy can be obtained using: G.subgraph(nbunch).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([ n in G if n
not in set(nbunch)])
Examples
3.2.4 MultiDiGraph - Directed graphs with self loops and parallel edges
Overview
MultiDiGraph(data=None, **attr)
A directed graph class that can store multiedges.
Multiedges are multiple edges between two nodes. Each edge can hold optional data or attributes.
A MultiDiGraph holds directed edges. Self loops are allowed.
Nodes can be arbitrary (hashable) Python objects with optional key/value attributes.
Edges are represented as links between nodes with optional key/value attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
Graph, DiGraph, MultiGraph
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.MultiDiGraph()
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
>>> G.add_nodes_from([2,3])
>>> G.add_nodes_from(range(100,110))
>>> H=nx.Graph()
>>> H.add_path([0,1,2,3,4,5,6,7,8,9])
>>> G.add_nodes_from(H)
In addition to strings and integers any hashable Python object (except None) can represent a node, e.g. a
customized node object, or even another Graph.
>>> G.add_node(H)
Edges:
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge(1, 2)
a list of edges,
>>> G.add_edges_from([(1,2),(1,3)])
or a collection of edges,
>>> G.add_edges_from(H.edges())
If some edges connect nodes not yet in the graph, the nodes are added automatically. If an edge already exists,
an additional edge is created and stored using a key to identify the edge. By default the key is the lowest unused
integer.
>>> G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))])
>>> G[4]
{5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}}
Attributes:
Each graph, node, and edge can hold key/value attribute pairs in an associated attribute dictionary (the keys
must be hashable). By default these are empty, but can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named graph, node and edge respectively.
>>> G = nx.MultiDiGraph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Shortcuts:
Many common graph features allow python syntax to speed reporting.
The fastest way to traverse all edges of a graph is via adjacency_iter(), but the edges() method is often more
convenient.
>>> for n,nbrsdict in G.adjacency_iter():
... for nbr,keydict in nbrsdict.items():
... for key,eattr in keydict.items():
... if 'weight' in eattr:
... (n,nbr,eattr['weight'])
(1, 2, 4)
(2, 3, 8)
>>> [ (u,v,edata['weight']) for u,v,edata in G.edges(data=True) if 'weight' in edata ]
[(1, 2, 4), (2, 3, 8)]
Reporting:
Simple graph information is obtained using methods. Iterator versions of many reporting methods exist for
efficiency. Methods exist for reporting nodes(), edges(), neighbors() and degree() as well as the number of
nodes and edges.
For details on these and other miscellaneous methods, see below.
__init__
MultiDiGraph.__init__(data=None, **attr)
Initialize a graph with edges, name, graph attributes.
Parameters data : input graph
Data to initialize graph. If data=None (default) an empty graph is created. The data can
be an edge list, or any NetworkX graph object. If the corresponding optional Python
packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse
matrix, or a PyGraphviz graph.
name : string, optional (default=’‘)
An optional name for the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to graph as key=value pairs.
See also:
convert
Examples
add_node
Notes
A hashable object is one that can be used as a key in a Python dictionary. This includes strings, numbers, tuples
of strings and numbers, etc.
On many platforms hashable items also include mutables such as NetworkX Graphs, though one should be
careful that the hash doesn’t change on mutables.
Examples
add_nodes_from
MultiDiGraph.add_nodes_from(nodes, **attr)
Add multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples.
Node attributes are updated using the attribute dict.
attr : keyword arguments, optional (default= no attributes)
Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple
take precedence over attributes specified generally.
See also:
add_node
Examples
remove_node
MultiDiGraph.remove_node(n)
Remove node n.
Removes the node n and all adjacent edges. Attempting to remove a non-existent node will raise an exception.
Parameters n : node
A node in the graph
Raises NetworkXError
If n is not in the graph.
See also:
remove_nodes_from
Examples
remove_nodes_from
MultiDiGraph.remove_nodes_from(nbunch)
Remove multiple nodes.
Parameters nodes : iterable container
A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it
is silently ignored.
See also:
remove_node
Examples
add_edge
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge
will be created.
NetworkX algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear
how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph
algorithms.
Examples
add_edges_from
Notes
Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.
Edge attributes specified in edges as a tuple take precedence over attributes specified generally.
Examples
add_weighted_edges_from
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
remove_edge
MultiDiGraph.remove_edge(u, v, key=None)
Remove an edge between u and v.
Parameters u,v: nodes
Remove an edge between nodes u and v.
key : hashable identifier, optional (default=None)
Used to distinguish multiple edges between a pair of nodes. If None remove a single
(abritrary) edge between u and v.
Raises NetworkXError
If there is not an edge between u and v, or if there is no edge with the specified key.
See also:
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> G.remove_edge(0,1)
>>> e = (1,2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(1,2),(1,2),(1,2)])
>>> G.remove_edge(1,2) # remove a single (arbitrary) edge
remove_edges_from
MultiDiGraph.remove_edges_from(ebunch)
Remove all edges specified in ebunch.
Parameters ebunch: list or container of edge tuples
Each edge given in the list or container will be removed from the graph. The edges can
be:
• 2-tuples (u,v) All edges between u and v are removed.
• 3-tuples (u,v,key) The edge identified by key is removed.
• 4-tuples (u,v,key,data) where data is ignored.
See also:
Notes
Examples
add_star
MultiDiGraph.add_star(nodes, **attr)
Add a star.
The first node in nodes is the middle of the star. It is connected to all other nodes.
Parameters nodes : iterable container
A container of nodes.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in star.
See also:
add_path, add_cycle
Examples
add_path
MultiDiGraph.add_path(nodes, **attr)
Add a path.
Parameters nodes : iterable container
A container of nodes. A path will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in path.
See also:
add_star, add_cycle
Examples
add_cycle
MultiDiGraph.add_cycle(nodes, **attr)
Add a cycle.
Parameters nodes: iterable container
A container of nodes. A cycle will be constructed from the nodes (in order) and added
to the graph.
attr : keyword arguments, optional (default= no attributes)
Attributes to add to every edge in cycle.
See also:
add_path, add_star
Examples
clear
MultiDiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
nodes
MultiDiGraph.nodes(data=False)
Return a list of the nodes in the graph.
Parameters data : boolean, optional (default=False)
If False return a list of nodes. If True return a two-tuple of node and node data dictionary
Returns nlist : list
A list of nodes. If data=True a list of two-tuples containing (node, node data dictionary).
Examples
nodes_iter
MultiDiGraph.nodes_iter(data=False)
Return an iterator over the nodes.
Parameters data : boolean, optional (default=False)
If False the iterator returns nodes. If True return a two-tuple of node and node data
dictionary
Returns niter : iterator
An iterator over nodes. If data=True the iterator gives two-tuples containing (node, node
data, dictionary)
Notes
If the node data is not required it is simpler and equivalent to use the expression ‘for n in G’.
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_path([0,1,2])
Examples
__iter__
MultiDiGraph.__iter__()
Iterate over the nodes. Use the expression ‘for n in G’.
Returns niter : iterator
An iterator over all nodes in the graph.
Examples
edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
edges_iter
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> [e for e in G.edges_iter()]
[(0, 1), (1, 2), (2, 3)]
>>> list(G.edges_iter(data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {})]
>>> list(G.edges_iter([0,2]))
out_edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs edges() is the same as
out_edges().
out_edges_iter
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> [e for e in G.edges_iter()]
[(0, 1), (1, 2), (2, 3)]
>>> list(G.edges_iter(data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {})]
>>> list(G.edges_iter([0,2]))
[(0, 1), (2, 3)]
>>> list(G.edges_iter(0))
[(0, 1)]
in_edges
in_edges_iter
get_edge_data
Notes
Warning: Assigning G[u][v][key] corrupts the graph data structure. But it is safe to assign attributes to that
dictionary,
>>> G[0][1]['a']['weight'] = 10
>>> G[0][1]['a']['weight']
10
>>> G[1][0]['a']['weight']
10
Examples
neighbors
MultiDiGraph.neighbors(n)
Return a list of successor nodes of n.
neighbors() and successors() are the same function.
neighbors_iter
MultiDiGraph.neighbors_iter(n)
Return an iterator over successor nodes of n.
neighbors_iter() and successors_iter() are the same.
__getitem__
MultiDiGraph.__getitem__(n)
Return a dict of neighbors of node n. Use the expression ‘G[n]’.
Parameters n : node
A node in the graph.
Returns adj_dict : dictionary
The adjacency dictionary for nodes connected to n.
Notes
G[n] is similar to G.neighbors(n) but the internal data dictionary is returned instead of a list.
Assigning G[n] will corrupt the internal graph data structure. Use G[n] for reading data only.
Examples
successors
MultiDiGraph.successors(n)
Return a list of successor nodes of n.
neighbors() and successors() are the same function.
successors_iter
MultiDiGraph.successors_iter(n)
Return an iterator over successor nodes of n.
neighbors_iter() and successors_iter() are the same.
predecessors
MultiDiGraph.predecessors(n)
Return a list of predecessor nodes of n.
predecessors_iter
MultiDiGraph.predecessors_iter(n)
Return an iterator over predecessor nodes of n.
adjacency_list
MultiDiGraph.adjacency_list()
Return an adjacency list representation of the graph.
The output adjacency list is in the order of G.nodes(). For directed graphs, only outgoing adjacencies are
included.
Returns adj_list : lists of lists
The adjacency structure of the graph as a list of lists.
See also:
adjacency_iter
Examples
adjacency_iter
MultiDiGraph.adjacency_iter()
Return an iterator of (node, adjacency dict) tuples for all nodes.
This is the fastest way to look at every edge. For directed graphs, only outgoing adjacencies are included.
Returns adj_iter : iterator
An iterator of (node, adjacency dictionary) for all nodes in the graph.
See also:
adjacency_list
Examples
nbunch_iter
MultiDiGraph.nbunch_iter(nbunch=None)
Return an iterator of nodes contained in nbunch that are also in the graph.
The nodes in nbunch are checked for membership in the graph and if not are silently ignored.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
Returns niter : iterator
An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate
over all nodes in the graph.
Raises NetworkXError
If nbunch is not a node or or sequence of nodes. If a node in nbunch is not hashable.
See also:
Graph.__iter__
Notes
When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when
nbunch is exhausted.
To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.
If nbunch is not a node or a (possibly empty) sequence/iterator or None, a NetworkXError is raised. Also, if any
object in nbunch is not hashable, a NetworkXError is raised.
has_node
MultiDiGraph.has_node(n)
Return True if the graph contains the node n.
Parameters n : node
Examples
__contains__
MultiDiGraph.__contains__(n)
Return True if n is a node, False otherwise. Use the expression ‘n in G’.
Examples
has_edge
MultiDiGraph.has_edge(u, v, key=None)
Return True if the graph has an edge between nodes u and v.
Parameters u,v : nodes
Nodes can be, for example, strings or numbers.
key : hashable identifier, optional (default=None)
If specified return True only if the edge with key is found.
Returns edge_ind : bool
True if edge is in the graph, False otherwise.
Examples
Can be called either using two nodes u,v, an edge tuple (u,v), or an edge tuple (u,v,key).
order
MultiDiGraph.order()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
number_of_nodes, __len__
number_of_nodes
MultiDiGraph.number_of_nodes()
Return the number of nodes in the graph.
Returns nnodes : int
The number of nodes in the graph.
See also:
order, __len__
Examples
__len__
MultiDiGraph.__len__()
Return the number of nodes. Use the expression ‘len(G)’.
Returns nnodes : int
The number of nodes in the graph.
Examples
degree
MultiDiGraph.degree(nbunch=None, weight=None)
Return the degree of a node or nodes.
The node degree is the number of edges adjacent to that node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and degree as values or a number if a single node is
specified.
Examples
degree_iter
MultiDiGraph.degree_iter(nbunch=None, weight=None)
Return an iterator for (node, degree).
The node degree is the number of edges adjacent to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> list(G.degree_iter(0)) # node 0 with degree 1
[(0, 1)]
>>> list(G.degree_iter([0,1]))
[(0, 1), (1, 2)]
in_degree
MultiDiGraph.in_degree(nbunch=None, weight=None)
Return the in-degree of a node or nodes.
The node in-degree is the number of edges pointing in to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and in-degree as values or a number if a single node is
specified.
See also:
degree, out_degree, in_degree_iter
Examples
in_degree_iter
MultiDiGraph.in_degree_iter(nbunch=None, weight=None)
Return an iterator for (node, in-degree).
The node in-degree is the number of edges pointing in to the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, in-degree).
See also:
degree, in_degree, out_degree, out_degree_iter
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> list(G.in_degree_iter(0)) # node 0 with degree 0
[(0, 0)]
>>> list(G.in_degree_iter([0,1]))
[(0, 0), (1, 1)]
out_degree
MultiDiGraph.out_degree(nbunch=None, weight=None)
Return the out-degree of a node or nodes.
The node out-degree is the number of edges pointing out of the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights adjacent to the node.
Returns nd : dictionary, or number
A dictionary with nodes as keys and out-degree as values or a number if a single node
is specified.
Examples
out_degree_iter
MultiDiGraph.out_degree_iter(nbunch=None, weight=None)
Return an iterator for (node, out-degree).
The node out-degree is the number of edges pointing out of the node.
Parameters nbunch : iterable container, optional (default=all nodes)
A container of nodes. The container will be iterated through once.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1. The degree is the sum of the edge weights.
Returns nd_iter : an iterator
The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree, out_degree, in_degree_iter
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1,2,3])
>>> list(G.out_degree_iter(0)) # node 0 with degree 1
[(0, 1)]
>>> list(G.out_degree_iter([0,1]))
[(0, 1), (1, 1)]
size
MultiDiGraph.size(weight=None)
Return the number of edges.
Parameters weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns nedges : int
The number of edges or sum of edge weights in the graph.
See also:
number_of_edges
Examples
number_of_edges
MultiDiGraph.number_of_edges(u=None, v=None)
Return the number of edges between two nodes.
Parameters u,v : nodes, optional (default=all edges)
If u and v are specified, return the number of edges between u and v. Otherwise return
the total number of all edges.
Returns nedges : int
The number of edges in the graph. If nodes u and v are specified return the number of
edges between those nodes.
See also:
size
Examples
nodes_with_selfloops
MultiDiGraph.nodes_with_selfloops()
Return a list of nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Returns nodelist : list
A list of nodes with self loops.
See also:
selfloop_edges, number_of_selfloops
Examples
selfloop_edges
MultiDiGraph.selfloop_edges(data=False, keys=False)
Return a list of selfloop edges.
A selfloop edge has the same node at both ends.
Parameters data : bool, optional (default=False)
Return selfloop edges as two tuples (u,v) (data=False) or three-tuples (u,v,data)
(data=True)
keys : bool, optional (default=False)
If True, return edge keys with each edge.
Returns edgelist : list of edge tuples
A list of all selfloop edges.
See also:
nodes_with_selfloops, number_of_selfloops
Examples
number_of_selfloops
MultiDiGraph.number_of_selfloops()
Return the number of selfloop edges.
A selfloop edge has the same node at both ends.
Examples
copy
MultiDiGraph.copy()
Return a copy of the graph.
Returns G : Graph
A copy of the graph.
See also:
Notes
This makes a complete copy of the graph including all of the node or edge attributes.
Examples
to_undirected
MultiDiGraph.to_undirected(reciprocal=False)
Return an undirected representation of the digraph.
Notes
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
to_directed
MultiDiGraph.to_directed()
Return a directed copy of the graph.
Returns G : MultiDiGraph
A deepcopy of the graph.
Notes
If edges in both directions (u,v) and (v,u) exist in the graph, attributes for the new undirected edge will be a
combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the
edges are encountered. For more customized control of the edge attributes use add_edge().
This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the
data and references.
This is in contrast to the similar G=DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies,
http://docs.python.org/library/copy.html.
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_path([0,1])
>>> H = G.to_directed()
>>> H.edges()
[(0, 1)]
subgraph
MultiDiGraph.subgraph(nbunch)
Return the subgraph induced on nodes in nbunch.
The induced subgraph of the graph contains the nodes in nbunch and the edges between those nodes.
Parameters nbunch : list, iterable
A container of nodes which will be iterated through once.
Returns G : Graph
A subgraph of the graph with the same edge attributes.
Notes
The graph, edge or node attributes just point to the original graph. So changes to the node or edge structure will
not be reflected in the original graph while changes to the attributes will.
To create a subgraph with its own copy of the edge/node attributes use: nx.Graph(G.subgraph(nbunch))
If edge attributes are containers, a deep copy can be obtained using: G.subgraph(nbunch).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([ n in G if n
not in set(nbunch)])
Examples
reverse
MultiDiGraph.reverse(copy=True)
Return the reverse of the graph.
The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.
Parameters copy : bool optional (default=True)
If True, return a new DiGraph holding the reversed edges. If False, reverse the reverse
graph is created using the original graph (this changes the original graph).
FOUR
ALGORITHMS
4.1 Approximation
4.1.1 Clique
Cliques.
max_clique
max_clique(G)
Find the Maximum Clique
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set in the worst case.
Parameters G : NetworkX graph
Undirected graph
Returns clique : set
The apx-maximum clique of the graph
Notes
A clique in an undirected graph G = (V, E) is a subset of the vertex set 𝐶 ⊆ 𝑉 , such that for every two vertices
in C, there exists an edge connecting the two. This is equivalent to saying that the subgraph induced by C is
complete (in some cases, the term clique may also refer to the subgraph).
A maximum clique is a clique of the largest possible size in a given graph. The clique number 𝜔(𝐺) of a graph
G is the number of vertices in a maximum clique in G. The intersection number of G is the smallest number of
cliques that together cover all edges of G.
http://en.wikipedia.org/wiki/Maximum_clique
References
[R142]
127
NetworkX Reference, Release 1.9.1
clique_removal
clique_removal(G)
Repeatedly remove cliques from the graph.
Results in a 𝑂(|𝑉 |/(log |𝑉 |)2 ) approximation of maximum clique & independent set. Returns the largest inde-
pendent set found, along with found maximal cliques.
Parameters G : NetworkX graph
Undirected graph
Returns max_ind_cliques : (set, list) tuple
Maximal independent set and list of maximal cliques (sets) in the graph.
References
[R141]
4.1.2 Clustering
average_clustering
average_clustering(G, trials=1000)
Estimates the average clustering coefficient of G.
The local clustering of each node in 𝐺 is the fraction of triangles that actually exist over all possible triangles in
its neighborhood. The average clustering coefficient of a graph 𝐺 is the mean of local clusterings.
This function finds an approximate average clustering coefficient for G by repeating 𝑛 times (defined in 𝑡𝑟𝑖𝑎𝑙𝑠)
the following experiment: choose a node at random, choose two of its neighbors at random, and check if they
are connected. The approximate coefficient is the fraction of triangles found over the number of trials [R143].
Parameters G : NetworkX graph
trials : integer
Number of trials to perform (default 1000).
Returns c : float
Approximated average clustering coefficient.
References
[R143]
A dominating set for a graph G = (V, E) is a subset D of V such that every vertex not in D is joined to at least one
member of D by some edge. The domination number gamma(G) is the number of vertices in a smallest dominating
set for G. Given a graph G = (V, E) find a minimum weight dominating set V’.
http://en.wikipedia.org/wiki/Dominating_set
An edge dominating set for a graph G = (V, E) is a subset D of E such that every edge not in D is adjacent to at least
one edge in D.
http://en.wikipedia.org/wiki/Edge_dominating_set
min_weighted_dominating_set
min_weighted_dominating_set(G, weight=None)
Return minimum weight vertex dominating set.
Parameters G : NetworkX graph
Undirected graph
weight : None or string, optional (default = None)
If None, every edge has weight/distance/weight 1. If a string, use this edge attribute as
the edge weight. Any edge attribute not present defaults to 1.
Returns min_weight_dominating_set : set
Returns a set of vertices whose weight sum is no more than log w(V) * OPT
Notes
This algorithm computes an approximate minimum weighted dominating set for the graph G. The upper-bound
on the size of the solution is log w(V) * OPT. Runtime of the algorithm is 𝑂(|𝐸|).
References
[R144]
min_edge_dominating_set
min_edge_dominating_set(G)
Return minimum cardinality edge dominating set.
Parameters G : NetworkX graph
Undirected graph
Returns min_edge_dominating_set : set
Returns a set of dominating edges whose size is no more than 2 * OPT.
Notes
The algorithm computes an approximate solution to the edge dominating set problem. The result is no more
than 2 * OPT in terms of size of the set. Runtime of the algorithm is 𝑂(|𝐸|).
Independent Set
Independent set or stable set is a set of vertices in a graph, no two of which are adjacent. That is, it is a set I of vertices
such that for every two vertices in I, there is no edge connecting the two. Equivalently, each edge in the graph has at
most one endpoint in I. The size of an independent set is the number of vertices it contains.
A maximum independent set is a largest independent set for a given graph G and its size is denoted 𝛼(G). The problem
of finding such a set is called the maximum independent set problem and is an NP-hard optimization problem. As
such, it is unlikely that there exists an efficient algorithm for finding a maximum independent set of a graph.
http://en.wikipedia.org/wiki/Independent_set_(graph_theory)
Independent set algorithm is based on the following paper:
𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of maximum clique/independent set.
Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding subgraphs. BIT
Numerical Mathematics, 32(2), 180–196. Springer. doi:10.1007/BF01994876
maximum_independent_set
maximum_independent_set(G)
Return an approximate maximum independent set.
Parameters G : NetworkX graph
Undirected graph
Returns iset : Set
The apx-maximum independent set
Notes
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of independent set in the worst case.
References
[R145]
4.1.5 Matching
Given a graph G = (V,E), a matching M in G is a set of pairwise non-adjacent edges; that is, no two edges share a
common vertex.
http://en.wikipedia.org/wiki/Matching_(graph_theory)
min_maximal_matching
min_maximal_matching(G)
Returns the minimum maximal matching of G. That is, out of all maximal matchings of the graph G, the smallest
is returned.
Parameters G : NetworkX graph
Undirected graph
Returns min_maximal_matching : set
Returns a set of edges such that no two edges share a common endpoint and every edge
not in the set shares some common endpoint in the set. Cardinality will be 2*OPT in
the worst case.
Notes
The algorithm computes an approximate solution fo the minimum maximal cardinality matching problem. The
solution is no more than 2 * OPT in size. Runtime is 𝑂(|𝐸|).
References
[R146]
4.1.6 Ramsey
Ramsey numbers.
ramsey_R2
ramsey_R2(G)
Approximately computes the Ramsey number 𝑅(2; 𝑠, 𝑡) for graph.
Parameters G : NetworkX graph
Undirected graph
Returns max_pair : (set, set) tuple
Maximum clique, Maximum independent set.
Given an undirected graph 𝐺 = (𝑉, 𝐸) and a function w assigning nonnegative weights to its vertices, find a minimum
weight subset of V such that each edge in E is incident to at least one vertex in the subset.
http://en.wikipedia.org/wiki/Vertex_cover
min_weighted_vertex_cover(G[, weight]) 2-OPT Local Ratio for Minimum Weighted Vertex Cover
min_weighted_vertex_cover
min_weighted_vertex_cover(G, weight=None)
2-OPT Local Ratio for Minimum Weighted Vertex Cover
Find an approximate minimum weighted vertex cover of a graph.
Parameters G : NetworkX graph
Undirected graph
weight : None or string, optional (default = None)
If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the
edge weight. Any edge attribute not present defaults to 1.
Returns min_weighted_cover : set
Returns a set of vertices whose weight sum is no more than 2 * OPT.
Notes
Local-Ratio algorithm for computing an approximate vertex cover. Algorithm greedily reduces the costs over
edges and iteratively builds a cover. Worst-case runtime is 𝑂(|𝐸|).
References
[R147]
4.2 Assortativity
4.2.1 Assortativity
degree_assortativity_coefficient
Notes
This computes Eq. (21) in Ref. [R151] , where e is the joint probability distribution (mixing matrix) of the
degrees. If G is directed than the matrix e is the joint probability of the user-specified degree type for the source
and target.
References
[R151], [R152]
Examples
>>> G=nx.path_graph(4)
>>> r=nx.degree_assortativity_coefficient(G)
>>> print("%3.1f"%r)
-0.5
attribute_assortativity_coefficient
Notes
This computes Eq. (2) in Ref. [R148] , trace(M)-sum(M))/(1-sum(M), where M is the joint probability distribu-
tion (mixing matrix) of the specified attribute.
References
[R148]
Examples
>>> G=nx.Graph()
>>> G.add_nodes_from([0,1],color='red')
>>> G.add_nodes_from([2,3],color='blue')
>>> G.add_edges_from([(0,1),(2,3)])
>>> print(nx.attribute_assortativity_coefficient(G,'color'))
1.0
numeric_assortativity_coefficient
Notes
This computes Eq. (21) in Ref. [R156] , for the mixing matrix of of the specified attribute.
References
[R156]
Examples
>>> G=nx.Graph()
>>> G.add_nodes_from([0,1],size=2)
>>> G.add_nodes_from([2,3],size=3)
>>> G.add_edges_from([(0,1),(2,3)])
>>> print(nx.numeric_assortativity_coefficient(G,'size'))
1.0
degree_pearson_correlation_coefficient
Notes
References
[R153], [R154]
Examples
>>> G=nx.path_graph(4)
>>> r=nx.degree_pearson_correlation_coefficient(G)
>>> print("%3.1f"%r)
-0.5
average_neighbor_degree(G[, source, target, ...]) Returns the average degree of the neighborhood of each node.
average_neighbor_degree
where 𝑁 (𝑖) are the neighbors of node 𝑖 and 𝑘𝑗 is the degree of node 𝑗 which belongs to 𝑁 (𝑖). For weighted
graphs, an analogous measure can be defined [R150],
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where 𝑠𝑖 is the weighted degree of node 𝑖, 𝑤𝑖𝑗 is the weight of the edge that links 𝑖 and 𝑗 and 𝑁 (𝑖) are the
neighbors of node 𝑖.
Parameters G : NetworkX graph
source : string (“in”|”out”)
Directed graphs only. Use “in”- or “out”-degree for source node.
target : string (“in”|”out”)
Directed graphs only. Use “in”- or “out”-degree for target node.
nodes : list or iterable, optional
Compute neighbor degree for specified nodes. The default is all nodes in the graph.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns d: dict
A dictionary keyed by node with average neighbors degree value.
See also:
average_degree_connectivity
Notes
For directed graphs you can also specify in-degree or out-degree by passing keyword arguments.
References
[R150]
Examples
>>> G=nx.path_graph(4)
>>> G.edge[0][1]['weight'] = 5
>>> G.edge[2][3]['weight'] = 3
>>> nx.average_neighbor_degree(G)
{0: 2.0, 1: 1.5, 2: 1.5, 3: 2.0}
>>> nx.average_neighbor_degree(G, weight='weight')
{0: 2.0, 1: 1.1666666666666667, 2: 1.25, 3: 2.0}
>>> G=nx.DiGraph()
>>> G.add_path([0,1,2,3])
>>> nx.average_neighbor_degree(G, source='in', target='in')
{0: 1.0, 1: 1.0, 2: 1.0, 3: 0.0}
average_degree_connectivity
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where 𝑠𝑖 is the weighted degree of node 𝑖, 𝑤𝑖𝑗 is the weight of the edge that links 𝑖 and 𝑗, and 𝑁 (𝑖) are the
neighbors of node 𝑖.
Parameters G : NetworkX graph
source : “in”|”out”|”in+out” (default:”in+out”)
Directed graphs only. Use “in”- or “out”-degree for source node.
target : “in”|”out”|”in+out” (default:”in+out”
Directed graphs only. Use “in”- or “out”-degree for target node.
nodes: list or iterable (optional)
Compute neighbor connectivity for these nodes. The default is all nodes.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns d: dict
A dictionary keyed by degree k with the value of average connectivity.
See also:
neighbors_average_degree
Notes
This algorithm is sometimes called “k nearest neighbors’ and is also available as 𝑘𝑛 𝑒𝑎𝑟𝑒𝑠𝑡𝑛 𝑒𝑖𝑔ℎ𝑏𝑜𝑟𝑠.
References
[R149]
Examples
>>> G=nx.path_graph(4)
>>> G.edge[1][2]['weight'] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight='weight')
{1: 2.0, 2: 1.75}
k_nearest_neighbors
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where 𝑠𝑖 is the weighted degree of node 𝑖, 𝑤𝑖𝑗 is the weight of the edge that links 𝑖 and 𝑗, and 𝑁 (𝑖) are the
neighbors of node 𝑖.
Parameters G : NetworkX graph
source : “in”|”out”|”in+out” (default:”in+out”)
Directed graphs only. Use “in”- or “out”-degree for source node.
target : “in”|”out”|”in+out” (default:”in+out”
Directed graphs only. Use “in”- or “out”-degree for target node.
nodes: list or iterable (optional)
Compute neighbor connectivity for these nodes. The default is all nodes.
weight : string or None, optional (default=None)
The edge attribute that holds the numerical value used as a weight. If None, then each
edge has weight 1.
Returns d: dict
A dictionary keyed by degree k with the value of average connectivity.
See also:
neighbors_average_degree
Notes
This algorithm is sometimes called “k nearest neighbors’ and is also available as 𝑘𝑛 𝑒𝑎𝑟𝑒𝑠𝑡𝑛 𝑒𝑖𝑔ℎ𝑏𝑜𝑟𝑠.
References
[R155]
Examples
>>> G=nx.path_graph(4)
>>> G.edge[1][2]['weight'] = 3
>>> nx.k_nearest_neighbors(G)
{1: 2.0, 2: 1.5}
>>> nx.k_nearest_neighbors(G, weight='weight')
{1: 2.0, 2: 1.75}
4.2.4 Mixing
attribute_mixing_matrix
Mapping from node attribute to integer index in matrix. If not specified, an arbitrary
ordering will be used.
normalized : bool (default=False)
Return counts if False or probabilities if True.
Returns m: numpy array
Counts or joint probability of occurrence of attribute pairs.
degree_mixing_matrix
degree_mixing_dict
attribute_mixing_dict
Examples
>>> G=nx.Graph()
>>> G.add_nodes_from([0,1],color='red')
>>> G.add_nodes_from([2,3],color='blue')
>>> G.add_edge(1,3)
>>> d=nx.attribute_mixing_dict(G,'color')
>>> print(d['red']['blue'])
1
>>> print(d['blue']['red']) # d symmetric for undirected graphs
1
4.3 Bipartite
This module provides functions and operations for bipartite graphs. Bipartite graphs 𝐵 = (𝑈, 𝑉, 𝐸) have two node
sets 𝑈, 𝑉 and edges in 𝐸 that only connect nodes from opposite sets. It is common in the literature to use an spatial
analogy referring to the two node sets as top and bottom nodes.
The bipartite algorithms are not imported into the networkx namespace at the top level so the easiest way to use them
is with:
>>> import networkx as nx
>>> from networkx.algorithms import bipartite
NetworkX does not have a custom bipartite graph class but the Graph() or DiGraph() classes can be used to represent
bipartite graphs. However, you have to keep track of which set each node belongs to, and make sure that there is no
edge between nodes of the same set. The convention used in NetworkX is to use a node attribute named “bipartite”
with values 0 or 1 to identify the sets each node belongs to.
For example:
>>> B = nx.Graph()
>>> B.add_nodes_from([1,2,3,4], bipartite=0) # Add the node attribute "bipartite"
>>> B.add_nodes_from(['a','b','c'], bipartite=1)
>>> B.add_edges_from([(1,'a'), (1,'b'), (2,'b'), (2,'c'), (3,'c'), (4,'a')])
Many algorithms of the bipartite module of NetworkX require, as an argument, a container with all the nodes that
belong to one set, in addition to the bipartite graph 𝐵. If 𝐵 is connected, you can find the node sets using a two-
coloring algorithm:
>>> nx.is_connected(B)
True
>>> bottom_nodes, top_nodes = bipartite.sets(B)
All bipartite graph generators in NetworkX build bipartite graphs with the “bipartite” node attribute. Thus, you can
use the same approach:
>>> RB = nx.bipartite_random_graph(5, 7, 0.2)
>>> RB_top = set(n for n,d in RB.nodes(data=True) if d['bipartite']==0)
>>> RB_bottom = set(RB) - RB_top
>>> list(RB_top)
[0, 1, 2, 3, 4]
>>> list(RB_bottom)
[5, 6, 7, 8, 9, 10, 11]
For other bipartite graph generators see the bipartite section of Graph generators.
is_bipartite
is_bipartite(G)
Returns True if graph G is bipartite, False if not.
Parameters G : NetworkX graph
See also:
color, is_bipartite_node_set
Examples
is_bipartite_node_set
is_bipartite_node_set(G, nodes)
Returns True if nodes and G/nodes are a bipartition of G.
Parameters G : NetworkX graph
nodes: list or container
Check if nodes are a one of a bipartite set.
Notes
For connected graphs the bipartite sets are unique. This function handles disconnected graphs.
Examples
sets
sets(G)
Returns bipartite node sets of graph G.
Raises an exception if the graph is not bipartite.
Parameters G : NetworkX graph
Returns (X,Y) : two-tuple of sets
One set of nodes for each part of the bipartite graph.
See also:
color
Examples
color
color(G)
Returns a two-coloring of the graph.
Raises an exception if the graph is not bipartite.
Parameters G : NetworkX graph
Returns color : dictionary
A dictionary keyed by node with a 1 or 0 as data for each node color.
Raises NetworkXError if the graph is not two-colorable.
Examples
You can use this to set a node attribute indicating the biparite set:
>>> nx.set_node_attributes(G, 'bipartite', c)
>>> print(G.node[0]['bipartite'])
1
>>> print(G.node[1]['bipartite'])
0
density
density(B, nodes)
Return density of bipartite graph B.
Parameters G : NetworkX graph
nodes: list or container
Nodes in one set of the bipartite graph.
Returns d : float
The bipartite density
See also:
color
Examples
degrees
Examples
biadjacency_matrix
Notes
References
[1] http://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
4.3.2 Projections
projected_graph(B, nodes[, multigraph]) Returns the projection of B onto one of its node sets.
weighted_projected_graph(B, nodes[, ratio]) Returns a weighted projection of B onto one of its node sets.
collaboration_weighted_projected_graph(B, nodes) Newman’s weighted projection of B onto one of its node sets.
overlap_weighted_projected_graph(B, nodes[, ...]) Overlap weighted projection of B onto one of its node sets.
generic_weighted_projected_graph(B, nodes[, ...]) Weighted projection of B with a user-specified weight function.
projected_graph
Notes
No attempt is made to verify that the input graph B is bipartite. Returns a simple graph that is the projection of
the bipartite graph B onto the set of nodes given in list nodes. If multigraph=True then a multigraph is returned
with an edge for every shared neighbor.
Directed graphs are allowed as input. The output will also then be a directed graph with edges if there is a
directed path between the nodes.
The graph and node properties are (shallow) copied to the projected graph.
Examples
>>> print(G.nodes())
[1, 3]
>>> print(G.edges())
[(1, 3)]
If nodes 𝑎, and 𝑏 are connected through both nodes 1 and 2 then building a multigraph results in two edges in
the projection onto [𝑎,‘b‘]:
>>> B = nx.Graph()
>>> B.add_edges_from([('a', 1), ('b', 1), ('a', 2), ('b', 2)])
>>> G = bipartite.projected_graph(B, ['a', 'b'], multigraph=True)
>>> print([sorted((u,v)) for u,v in G.edges()])
[['a', 'b'], ['a', 'b']]
weighted_projected_graph
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
References
[R166]
Examples
collaboration_weighted_projected_graph
collaboration_weighted_projected_graph(B, nodes)
Newman’s weighted projection of B onto one of its node sets.
The collaboration weighted projection is the projection of the bipartite network B onto the specified nodes with
weights assigned using Newman’s collaboration model [R164]:
∑︁ 𝛿 𝑤 𝛿 𝑘
𝑣 𝑤
𝑤𝑣,𝑢 =
𝑘𝑤 − 1
𝑘
where 𝑣 and 𝑢 are nodes from the same bipartite node set, and 𝑤 is a node of the opposite node set. The value
𝑘𝑤 is the degree of node 𝑤 in the bipartite network and 𝛿𝑣𝑤 is 1 if node 𝑣 is linked to node 𝑤 in the original
bipartite graph or 0 otherwise.
The nodes retain their attributes and are connected in the resulting graph if have an edge to a common node in
the original bipartite graph.
Parameters B : NetworkX graph
The input graph should be bipartite.
nodes : list or iterable
Nodes to project onto (the “bottom” nodes).
Returns Graph : NetworkX graph
A graph that is the projection onto the given nodes.
See also:
is_bipartite, is_bipartite_node_set, sets, weighted_projected_graph,
overlap_weighted_projected_graph, generic_weighted_projected_graph,
projected_graph
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
References
[R164]
Examples
overlap_weighted_projected_graph
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
References
[R165]
Examples
generic_weighted_projected_graph
Notes
No attempt is made to verify that the input graph B is bipartite. The graph and node properties are (shallow)
copied to the projected graph.
Examples
4.3.3 Spectral
spectral_bipartivity
Notes
This implementation uses Numpy (dense) matrices which are not efficient for storing large sparse graphs.
References
[R168]
Examples
4.3.4 Clustering
clustering
𝑚𝑖𝑛:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
𝑚𝑎𝑥:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
Parameters G : graph
A bipartite graph
nodes : list or iterable (optional)
Compute bipartite clustering for these nodes. The default is all nodes in G.
mode : string
The pariwise bipartite clustering method to be used in the computation. It must be “dot”,
“max”, or “min”.
Returns clustering : dictionary
A dictionary keyed by node with the clustering coefficient value.
See also:
robins_alexander_clustering, square_clustering, average_clustering
References
[R161]
Examples
average_clustering
Similar measures for the two bipartite sets can be defined [R160]
1 ∑︁
𝐶𝑋 = 𝑐𝑣 ,
|𝑋|
𝑣∈𝑋
Notes
The container of nodes passed to this function must contain all of the nodes in one of the bipartite sets (“top” or
“bottom”) in order to compute the correct average bipartite clustering coefficients.
References
[R160]
Examples
latapy_clustering
The bipartie clustering coefficient is a measure of local density of connections defined as [R162]:
∑︀
𝑣∈𝑁 (𝑁 (𝑣)) 𝑐𝑢𝑣
𝑐𝑢 =
|𝑁 (𝑁 (𝑢))|
where 𝑁 (𝑁 (𝑢)) are the second order neighbors of 𝑢 in 𝐺 excluding 𝑢, and 𝑐𝑢𝑣 is the pairwise clustering
coefficient between nodes 𝑢 and 𝑣.
The mode selects the function for 𝑐𝑢𝑣 which can be:
𝑑𝑜𝑡:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
𝑚𝑖𝑛:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
𝑚𝑎𝑥:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
Parameters G : graph
A bipartite graph
nodes : list or iterable (optional)
Compute bipartite clustering for these nodes. The default is all nodes in G.
mode : string
The pariwise bipartite clustering method to be used in the computation. It must be “dot”,
“max”, or “min”.
Returns clustering : dictionary
A dictionary keyed by node with the clustering coefficient value.
See also:
robins_alexander_clustering, square_clustering, average_clustering
References
[R162]
Examples
robins_alexander_clustering
robins_alexander_clustering(G)
Compute the bipartite clustering of G.
Robins and Alexander [R163] defined bipartite clustering coefficient as four times the number of four cycles 𝐶4
divided by the number of three paths 𝐿3 in a bipartite graph:
4 * 𝐶4
𝐶𝐶4 =
𝐿3
Parameters G : graph
a bipartite graph
Returns clustering : float
The Robins and Alexander bipartite clustering for the input graph.
See also:
latapy_clustering, square_clustering
References
[R163]
Examples
4.3.5 Redundancy
node_redundancy
node_redundancy(G, nodes=None)
Compute bipartite node redundancy coefficient.
The redundancy coefficient of a node 𝑣 is the fraction of pairs of neighbors of 𝑣 that are both linked to other
nodes. In a one-mode projection these nodes would be linked together even if 𝑣 were not there.
|{{𝑢, 𝑤} ⊆ 𝑁 (𝑣), ∃𝑣 ′ ̸= 𝑣, (𝑣 ′ , 𝑢) ∈ 𝐸 and (𝑣 ′ , 𝑤) ∈ 𝐸}|
𝑟𝑐(𝑣) = |𝑁 (𝑣)|(|𝑁 (𝑣)|−1)
2
References
[R167]
Examples
4.3.6 Centrality
closeness_centrality(G, nodes[, normalized]) Compute the closeness centrality for nodes in a bipartite network.
degree_centrality(G, nodes) Compute the degree centrality for nodes in a bipartite network.
betweenness_centrality(G, nodes) Compute betweenness centrality for nodes in a bipartite network.
closeness_centrality
Notes
The nodes input parameter must conatin all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets.
Closeness centrality is normalized by the minimum distance possible. In the bipartite case the minimum distance
for a node in one bipartite node set is 1 from all nodes in the other node set and 2 from all other nodes in its
own set [R158]. Thus the closeness centrality for node 𝑣 in the two bipartite sets 𝑈 with 𝑛 nodes and 𝑉 with 𝑚
nodes is
𝑚 + 2(𝑛 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑈,
𝑑
𝑛 + 2(𝑚 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑉,
𝑑
where 𝑑 is the sum of the distances from 𝑣 to all other nodes.
Higher values of closeness indicate higher centrality.
As in the unipartite case, setting normalized=True causes the values to normalized further to n-1 / size(G)-1
where n is the number of nodes in the connected part of graph containing the node. If the graph is not completely
connected, this algorithm computes the closeness centrality for each connected part separately.
References
[R158]
degree_centrality
degree_centrality(G, nodes)
Compute the degree centrality for nodes in a bipartite network.
The degree centrality for a node 𝑣 is the fraction of nodes connected to it.
Parameters G : graph
A bipartite network
nodes : list or container
Container with all nodes in one bipartite node set.
Returns centrality : dictionary
Dictionary keyed by node with bipartite degree centrality as the value.
See also:
betweenness_centrality, closeness_centrality, sets, is_bipartite
Notes
The nodes input parameter must conatin all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both bipartite node sets.
For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree
(which is 𝑛 − 1 where 𝑛 is the number of nodes in G).
In the bipartite case, the maximum possible degree of a node in a bipartite node set is the number of nodes in
the opposite node set [R159]. The degree centrality for a node 𝑣 in the bipartite sets 𝑈 with 𝑛 nodes and 𝑉 with
𝑚 nodes is
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑈,
𝑚
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑉,
𝑛
where 𝑑𝑒𝑔(𝑣) is the degree of node 𝑣.
References
[R159]
betweenness_centrality
betweenness_centrality(G, nodes)
Compute betweenness centrality for nodes in a bipartite network.
Betweenness centrality of a node 𝑣 is the sum of the fraction of all-pairs shortest paths that pass through 𝑣.
Values of betweenness are normalized by the maximum possible value which for bipartite graphs is limited by
the relative size of the two node sets [R157].
Let 𝑛 be the number of nodes in the node set 𝑈 and 𝑚 be the number of nodes in the node set 𝑉 , then nodes in
𝑈 are normalized by dividing by
1 2
[𝑚 (𝑠 + 1)2 + 𝑚(𝑠 + 1)(2𝑡 − 𝑠 − 1) − 𝑡(2𝑠 − 𝑡 + 3)],
2
where
𝑠 = (𝑛 − 1) ÷ 𝑚, 𝑡 = (𝑛 − 1) mod 𝑚,
𝑝 = (𝑚 − 1) ÷ 𝑛, 𝑟 = (𝑚 − 1) mod 𝑛.
Parameters G : graph
A bipartite graph
nodes : list or container
Container with all nodes in one bipartite node set.
Notes
The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned contains
all nodes from both node sets.
References
[R157]
4.4 Blockmodeling
blockmodel(G, partitions[, multigraph]) Returns a reduced graph constructed using the generalized block modeling technique.
4.4.1 blockmodel
References
[R169]
Examples
>>> G=nx.path_graph(6)
>>> partition=[[0,1],[2,3],[4,5]]
>>> M=nx.blockmodel(G,partition)
4.5 Boundary
4.5.1 edge_boundary
Notes
4.5.2 node_boundary
Notes
4.6 Centrality
4.6.1 Degree
degree_centrality
degree_centrality(G)
Compute the degree centrality for nodes.
The degree centrality for a node v is the fraction of nodes it is connected to.
Parameters G : graph
A networkx graph
Returns nodes : dictionary
Dictionary of nodes with degree centrality as the value.
See also:
betweenness_centrality, load_centrality, eigenvector_centrality
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
in_degree_centrality
in_degree_centrality(G)
Compute the in-degree centrality for nodes.
The in-degree centrality for a node v is the fraction of nodes its incoming edges are connected to.
Parameters G : graph
A NetworkX graph
Returns nodes : dictionary
Dictionary of nodes with in-degree centrality as values.
See also:
degree_centrality, out_degree_centrality
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
out_degree_centrality
out_degree_centrality(G)
Compute the out-degree centrality for nodes.
The out-degree centrality for a node v is the fraction of nodes its outgoing edges are connected to.
Parameters G : graph
A NetworkX graph
Returns nodes : dictionary
Dictionary of nodes with out-degree centrality as values.
See also:
degree_centrality, in_degree_centrality
Notes
The degree centrality values are normalized by dividing by the maximum possible degree in a simple graph n-1
where n is the number of nodes in G.
For multigraphs or graphs with self loops the maximum degree might be higher than n-1 and values of degree
centrality greater than 1 are possible.
4.6.2 Closeness
closeness_centrality
where 𝑑(𝑣, 𝑢) is the shortest-path distance between 𝑣 and 𝑢, and 𝑛 is the number of nodes in the graph.
Notice that higher values of closeness indicate higher centrality.
Parameters G : graph
A NetworkX graph
u : node, optional
Return only the value for node u
distance : edge attribute key, optional (default=None)
Use the specified edge attribute as the edge distance in shortest path calculations
normalized : bool, optional
If True (default) normalize by the number of nodes in the connected part of the graph.
Returns nodes : dictionary
Dictionary of nodes with closeness centrality as the value.
See also:
betweenness_centrality, load_centrality, eigenvector_centrality,
degree_centrality
Notes
The closeness centrality is normalized to (𝑛 − 1)/(|𝐺| − 1) where 𝑛 is the number of nodes in the connected part
of graph containing the node. If the graph is not completely connected, this algorithm computes the closeness
centrality for each connected part separately.
If the ‘distance’ keyword is set to an edge attribute key then the shortest-path length will be computed using
Dijkstra’s algorithm with that edge attribute as the edge weight.
References
[R174]
4.6.3 Betweenness
betweenness_centrality(G[, k, normalized, ...]) Compute the shortest-path betweenness centrality for nodes.
edge_betweenness_centrality(G[, normalized, ...]) Compute betweenness centrality for edges.
betweenness_centrality
where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣) is the number of those
paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡, 𝜎(𝑠, 𝑡|𝑣) = 0 [R172].
Parameters G : graph
A NetworkX graph
k : int, optional (default=None)
If k is not None use k node samples to estimate betweenness. The value of k <= n where
n is the number of nodes in the graph. Higher values give better approximation.
normalized : bool, optional
If True the betweenness values are normalized by 2/((𝑛 − 1)(𝑛 − 2)) for graphs, and
1/((𝑛 − 1)(𝑛 − 2)) for directed graphs where 𝑛 is the number of nodes in G.
weight : None or string, optional
If None, all edge weights are considered equal. Otherwise holds the name of the edge
attribute used as weight.
endpoints : bool, optional
If True include the endpoints in the shortest path counts.
Returns nodes : dictionary
Dictionary of nodes with betweenness centrality as the value.
See also:
edge_betweenness_centrality, load_centrality
Notes
The algorithm is from Ulrik Brandes [R171]. See [R172] for details on algorithms for variations and related
metrics.
For approximate betweenness calculations set k=#samples to use k nodes (“pivots”) to estimate the betweenness
values. For an estimate of the number of pivots needed see [R173].
For weighted graphs the edge weights must be greater than zero. Zero edge weights can produce an infinite
number of equal length paths between pairs of nodes.
References
edge_betweenness_centrality
where 𝑉 is the set of nodes,‘sigma(s, t)‘ is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒) is the number of
those paths passing through edge 𝑒 [R189].
Parameters G : graph
A NetworkX graph
normalized : bool, optional
If True the betweenness values are normalized by 2/(𝑛(𝑛−1)) for graphs, and 1/(𝑛(𝑛−
1)) for directed graphs where 𝑛 is the number of nodes in G.
weight : None or string, optional
If None, all edge weights are considered equal. Otherwise holds the name of the edge
attribute used as weight.
Returns edges : dictionary
Dictionary of edges with betweenness centrality as the value.
See also:
betweenness_centrality, edge_load
Notes
References
[R188], [R189]
current_flow_closeness_centrality
Notes
References
[R185], [R186]
current_flow_betweenness_centrality
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time [R183], where 𝐼(𝑛 − 1) is the
compute the inverse Laplacian. For a full matrix this is 𝑂(𝑛3 ) but using sparse methods you can
time needed to √
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤)𝑤ℎ𝑒𝑟𝑒‘𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[R183], [R184]
edge_current_flow_betweenness_centrality
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time [R190], where 𝐼(𝑛 − 1) is the
compute the inverse Laplacian. For a full matrix this is 𝑂(𝑛3 ) but using sparse methods you can
time needed to √
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤)𝑤ℎ𝑒𝑟𝑒‘𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[R190], [R191]
approximate_current_flow_betweenness_centrality
Notes
√
The running time is 𝑂((1/𝜖2 )𝑚 𝑘 log 𝑛) and the space required is 𝑂(𝑚) for n nodes and m edges.
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
[R170]
4.6.6 Eigenvector
eigenvector_centrality(G[, max_iter, tol, ...]) Compute the eigenvector centrality for the graph G.
eigenvector_centrality_numpy(G[, weight]) Compute the eigenvector centrality for the graph G.
katz_centrality(G[, alpha, beta, max_iter, ...]) Compute the Katz centrality for the nodes of the graph G.
katz_centrality_numpy(G[, alpha, beta, ...]) Compute the Katz centrality for the graph G.
eigenvector_centrality
Notes
The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The
iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached.
For directed graphs this is “left” eigevector centrality which corresponds to the in-edges in the graph. For
out-edges eigenvector centrality first reverse the graph with G.reverse().
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> print(['%s %0.2f'%(node,centrality[node]) for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
eigenvector_centrality_numpy
eigenvector_centrality_numpy(G, weight=’weight’)
Compute the eigenvector centrality for the graph G.
Parameters G : graph
A networkx graph
weight : None or string, optional
The name of the edge attribute used as weight. If None, all edge weights are considered
equal.
Returns nodes : dictionary
Dictionary of nodes with eigenvector centrality as the value.
See also:
eigenvector_centrality, pagerank, hits
Notes
This algorithm uses the SciPy sparse eigenvalue solver (ARPACK) to find the largest eigenvalue/eigenvector
pair.
For directed graphs this is “left” eigevector centrality which corresponds to the in-edges in the graph. For
out-edges eigenvector centrality first reverse the graph with G.reverse().
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print(['%s %0.2f'%(node,centrality[node]) for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
katz_centrality
Extra weight can be provided to immediate neighbors through the parameter 𝛽. Connections made with distant
neighbors are, however, penalized by an attenuation factor 𝛼 which should be strictly less than the inverse largest
eigenvalue of the adjacency matrix in order for the Katz centrality to be computed correctly. More information
is provided in [R193] .
Parameters G : graph
A NetworkX graph
alpha : float
Attenuation factor
beta : scalar or dictionary, optional (default=1.0)
Weight attributed to the immediate neighborhood. If not a scalar the dictionary must
have an value for every node.
max_iter : integer, optional (default=1000)
Maximum number of iterations in power method.
tol : float, optional (default=1.0e-6)
Error tolerance used to check convergence in power method iteration.
nstart : dictionary, optional
Starting value of Katz iteration for each node.
normalized : bool, optional (default=True)
If True normalize the resulting values.
weight : None or string, optional
If None, all edge weights are considered equal. Otherwise holds the name of the edge
attribute used as weight.
Returns nodes : dictionary
Dictionary of nodes with Katz centrality as the value.
See also:
katz_centrality_numpy, eigenvector_centrality, eigenvector_centrality_numpy,
pagerank, hits
Notes
This algorithm it uses the power method to find the eigenvector corresponding to the largest eigenvalue of the
adjacency matrix of G. The constant alpha should be strictly less than the inverse of largest eigenvalue of the
adjacency matrix for the algorithm to converge. The iteration will stop after max_iter iterations or an error
tolerance of number_of_nodes(G)*tol has been reached.
When 𝛼 = 1/𝜆𝑚𝑎𝑥 and 𝛽 = 1 Katz centrality is the same as eigenvector centrality.
For directed graphs this finds “left” eigenvectors which corresponds to the in-edges in the graph. For out-edges
Katz centrality first reverse the graph with G.reverse().
References
[R193]
Examples
katz_centrality_numpy
Notes
This algorithm uses a direct linear solver to solve the above equation. The constant alpha should be strictly less
than the inverse of largest eigenvalue of the adjacency matrix for there to be a solution. When 𝛼 = 1/𝜆𝑚𝑎𝑥 and
𝛽 = 1 Katz centrality is the same as eigenvector centrality.
For directed graphs this finds “left” eigenvectors which corresponds to the in-edges in the graph. For out-edges
Katz centrality first reverse the graph with G.reverse().
References
[R194]
Examples
4.6.7 Communicability
communicability
communicability(G)
Return communicability between all pairs of nodes in G.
The communicability between pairs of nodes in G is the sum of closed walks of different lengths starting at node
u and ending at node v.
Parameters G: graph
Notes
This algorithm uses a spectral decomposition of the adjacency matrix. Let G=(V,E) be a simple undirected
graph. Using the connection between the powers of the adjacency matrix and the number of walks in the graph,
the communicability between nodes 𝑢 and 𝑣 based on the graph spectrum is [R175]
𝑛
∑︁
𝐶(𝑢, 𝑣) = 𝜑𝑗 (𝑢)𝜑𝑗 (𝑣)𝑒𝜆𝑗 ,
𝑗=1
where 𝜑𝑗 (𝑢) is the 𝑢th element of the 𝑗th orthonormal eigenvector of the adjacency matrix associated with the
eigenvalue 𝜆𝑗 .
References
[R175]
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> c = nx.communicability(G)
communicability_exp
communicability_exp(G)
Return communicability between all pairs of nodes in G.
Communicability between pair of node (u,v) of node in G is the sum of closed walks of different lengths starting
at node u and ending at node v.
Parameters G: graph
Returns comm: dictionary of dictionaries
Dictionary of dictionaries keyed by nodes with communicability as the value.
Raises NetworkXError
If the graph is not undirected and simple.
See also:
Notes
References
[R182]
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> c = nx.communicability_exp(G)
communicability_centrality
communicability_centrality(G)
Return communicability centrality for each node in G.
Communicability centrality, also called subgraph centrality, of a node 𝑛 is the sum of closed walks of all lengths
starting and ending at node 𝑛.
Parameters G: graph
Returns nodes: dictionary
Dictionary of nodes with communicability centrality as the value.
Raises NetworkXError
If the graph is not undirected and simple.
See also:
Notes
This version of the algorithm computes eigenvalues and eigenvectors of the adjacency matrix.
Communicability centrality of a node 𝑢 in G can be found using a spectral decomposition of the adjacency
matrix [R178] [R179],
𝑁
∑︁
𝑆𝐶(𝑢) = (𝑣𝑗𝑢 )2 𝑒𝜆𝑗 ,
𝑗=1
References
[R178], [R179]
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> sc = nx.communicability_centrality(G)
communicability_centrality_exp
communicability_centrality_exp(G)
Return the communicability centrality for each node of G
Communicability centrality, also called subgraph centrality, of a node 𝑛 is the sum of closed walks of all lengths
starting and ending at node 𝑛.
Parameters G: graph
Returns nodes:dictionary
Dictionary of nodes with communicability centrality as the value.
Raises NetworkXError
If the graph is not undirected and simple.
See also:
Notes
This version of the algorithm exponentiates the adjacency matrix. The communicability centrality of a node 𝑢
in G can be found using the matrix exponential of the adjacency matrix of G [R180] [R181],
References
[R180], [R181]
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> sc = nx.communicability_centrality_exp(G)
communicability_betweenness_centrality
communicability_betweenness_centrality(G, normalized=True)
Return communicability betweenness for all pairs of nodes in G.
Communicability betweenness measure makes use of the number of walks connecting every pair of nodes as the
basis of a betweenness centrality measure.
Parameters G: graph
Returns nodes:dictionary
Dictionary of nodes with communicability betweenness as the value.
Raises NetworkXError
If the graph is not undirected and simple.
See also:
Notes
Let 𝐺 = (𝑉, 𝐸) be a simple undirected graph with 𝑛 nodes and 𝑚 edges, and 𝐴 denote the adjacency matrix of
𝐺.
Let 𝐺(𝑟) = (𝑉, 𝐸(𝑟)) be the graph resulting from removing all edges connected to node 𝑟 but not the node
itself.
The adjacency matrix for 𝐺(𝑟) is 𝐴 + 𝐸(𝑟), where 𝐸(𝑟) has nonzeros only in row and column 𝑟.
The communicability betweenness of a node 𝑟 is [R177]
1 ∑︁ ∑︁ 𝐺𝑝𝑟𝑞
𝜔𝑟 = , 𝑝 ̸= 𝑞, 𝑞 ̸= 𝑟,
𝐶 𝑝 𝑞 𝐺𝑝𝑞
References
[R177]
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> cbc = nx.communicability_betweenness_centrality(G)
estrada_index
estrada_index(G)
Return the Estrada index of a the graph G.
Parameters G: graph
Returns estrada index: float
Raises NetworkXError
If the graph is not undirected and simple.
See also:
estrada_index_exp
Notes
Let 𝐺 = (𝑉, 𝐸) be a simple undirected graph with 𝑛 nodes and let 𝜆1 ≤ 𝜆2 ≤ · · · 𝜆𝑛 be a non-increasing
ordering of the eigenvalues of its adjacency matrix 𝐴. The Estrada index is
𝑛
∑︁
𝐸𝐸(𝐺) = 𝑒𝜆𝑗 .
𝑗=1
References
[R192]
Examples
>>> G=nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> ei=nx.estrada_index(G)
4.6.8 Load
load_centrality
Notes
Load centrality is slightly different than betweenness. For this load algorithm see the reference Scientific col-
laboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman, Phys. Rev. E 64,
016132 (2001).
edge_load
4.6.9 Dispersion
dispersion
Notes
This implementation follows Lars Backstrom and Jon Kleinberg [R187]. Typical usage would be to run disper-
sion on the ego network 𝐺𝑢 if 𝑢 were specified. Running dispersion() with neither 𝑢 nor 𝑣 specified can
take some time to complete.
References
[R187]
4.7 Chordal
4.7.1 is_chordal
is_chordal(G)
Checks whether G is a chordal graph.
A graph is chordal if every cycle of length at least 4 has a chord (an edge joining two nodes not adjacent in the
cycle).
Parameters G : graph
A NetworkX graph.
Returns chordal : bool
True if G is a chordal graph and False otherwise.
Raises NetworkXError
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. If the input
graph is an instance of one of these classes, a NetworkXError is raised.
Notes
The routine tries to go through every node following maximum cardinality search. It returns False when it finds
that the separator for any node is not a clique. Based on the algorithms in [R197].
References
[R197]
Examples
4.7.2 chordal_graph_cliques
chordal_graph_cliques(G)
Returns the set of maximal cliques of a chordal graph.
The algorithm breaks the graph in connected components and performs a maximum cardinality search in each
component to get the cliques.
Parameters G : graph
A NetworkX graph
Returns cliques : A set containing the maximal cliques in G.
Raises NetworkXError
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. If the input
graph is an instance of one of these classes, a NetworkXError is raised. The algorithm
can only be applied to chordal graphs. If the input graph is found to be non-chordal, a
NetworkXError is raised.
Examples
4.7.3 chordal_graph_treewidth
chordal_graph_treewidth(G)
Returns the treewidth of the chordal graph G.
Parameters G : graph
A NetworkX graph
Returns treewidth : int
The size of the largest clique in the graph minus one.
Raises NetworkXError
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. If the input
graph is an instance of one of these classes, a NetworkXError is raised. The algorithm
can only be applied to chordal graphs. If the input graph is found to be non-chordal, a
NetworkXError is raised.
References
[R195]
Examples
4.7.4 find_induced_nodes
find_induced_nodes(G, s, t, treewidth_bound=9223372036854775807)
Returns the set of induced nodes in the path from s to t.
Parameters G : graph
A chordal NetworkX graph
s : node
Source node to look for induced nodes
t : node
Destination node to look for induced nodes
treewith_bound: float
Maximum treewidth acceptable for the graph H. The search for induced nodes will end
as soon as the treewidth_bound is exceeded.
Returns I : Set of nodes
The set of induced nodes in the path from s to t in G
Raises NetworkXError
The algorithm does not support DiGraph, MultiGraph and MultiDiGraph. If the input
graph is an instance of one of these classes, a NetworkXError is raised. The algorithm
can only be applied to chordal graphs. If the input graph is found to be non-chordal, a
NetworkXError is raised.
Notes
References
[R196]
Examples
4.8 Clique
4.8.1 find_cliques
find_cliques(G)
Search for all maximal cliques in a graph.
Maximal cliques are the largest complete subgraph containing a given node. The largest maximal clique is
sometimes called the maximum clique.
Returns generator of lists: genetor of member list for each maximal clique
See also:
find_cliques_recursive, A
Notes
References
4.8.2 make_max_clique_graph
Notes
This should be the same as make_clique_bipartite followed by project_up, but it saves all the intermediate steps.
4.8.3 make_clique_bipartite
4.8.4 graph_clique_number
graph_clique_number(G, cliques=None)
Return the clique number (size of the largest clique) for G.
An optional list of cliques can be input if already computed.
4.8.5 graph_number_of_cliques
graph_number_of_cliques(G, cliques=None)
Returns the number of maximal cliques in G.
An optional list of cliques can be input if already computed.
4.8.6 node_clique_number
4.8.7 number_of_cliques
4.8.8 cliques_containing_node
4.9 Clustering
4.9.1 triangles
triangles(G, nodes=None)
Compute the number of triangles.
Finds the number of triangles that include a node as one vertex.
Parameters G : graph
A networkx graph
nodes : container of nodes, optional (default= all nodes in G)
Compute triangles for nodes in this container.
Returns out : dictionary
Number of triangles keyed by node label.
Notes
When computing triangles for the entire graph each triangle is counted three times, once at each node. Self
loops are ignored.
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.triangles(G,0))
6
>>> print(nx.triangles(G))
{0: 6, 1: 6, 2: 6, 3: 6, 4: 6}
>>> print(list(nx.triangles(G,(0,1)).values()))
[6, 6]
4.9.2 transitivity
transitivity(G)
Compute graph transitivity, the fraction of all possible triangles present in G.
Possible triangles are identified by the number of “triads” (two edges with a shared vertex).
The transitivity is
#𝑡𝑟𝑖𝑎𝑛𝑔𝑙𝑒𝑠
𝑇 =3 .
#𝑡𝑟𝑖𝑎𝑑𝑠
Parameters G : graph
Returns out : float
Transitivity
Examples
>>> G = nx.complete_graph(5)
>>> print(nx.transitivity(G))
1.0
4.9.3 clustering
where 𝑇 (𝑢) is the number of triangles through node 𝑢 and 𝑑𝑒𝑔(𝑢) is the degree of 𝑢.
For weighted graphs, the clustering is defined as the geometric average of the subgraph edge weights [R203],
1 ∑︁
𝑐𝑢 = (𝑤
ˆ𝑢𝑣 𝑤 ˆ𝑣𝑤 )1/3 .
ˆ𝑢𝑤 𝑤
𝑑𝑒𝑔(𝑢)(𝑑𝑒𝑔(𝑢) − 1)) 𝑢𝑣
Notes
References
[R203]
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.clustering(G,0))
1.0
>>> print(nx.clustering(G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
4.9.4 average_clustering
Notes
This is a space saving routine; it might be faster to use the clustering function to get a list and then take the
average.
Self loops are ignored.
References
[R201], [R202]
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.average_clustering(G))
1.0
4.9.5 square_clustering
square_clustering(G, nodes=None)
Compute the squares clustering coefficient for nodes.
For each node return the fraction of possible squares that exist at the node [R204]
∑︀𝑘𝑣 ∑︀𝑘𝑣
𝑤=𝑢+1 𝑞𝑣 (𝑢, 𝑤)
𝐶4 (𝑣) = ∑︀𝑘𝑣 ∑︀𝑢=1
𝑘𝑣
,
𝑢=1 𝑤=𝑢+1 [𝑎𝑣 (𝑢, 𝑤) + 𝑞𝑣 (𝑢, 𝑤)]
where 𝑞𝑣 (𝑢, 𝑤) are the number of common neighbors of 𝑢 and 𝑤 other than 𝑣 (ie squares), and 𝑎𝑣 (𝑢, 𝑤) =
(𝑘𝑢 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑣 ))(𝑘𝑤 − (1 + 𝑞𝑣 (𝑢, 𝑤) + 𝜃𝑢𝑤 )), where 𝜃𝑢𝑤 = 1 if 𝑢 and 𝑤 are connected and 0
otherwise.
Parameters G : graph
nodes : container of nodes, optional (default=all nodes in G)
Compute clustering for nodes in this container.
Returns c4 : dictionary
A dictionary keyed by node with the square clustering coefficient value.
Notes
While 𝐶3 (𝑣) (triangle clustering) gives the probability that two neighbors of node v are connected with each
other, 𝐶4 (𝑣) is the probability that two neighbors of node v share a common neighbor different from v. This
algorithm can be applied to both bipartite and unipartite networks.
References
[R204]
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.square_clustering(G,0))
1.0
>>> print(nx.square_clustering(G))
{0: 1.0, 1: 1.0, 2: 1.0, 3: 1.0, 4: 1.0}
4.10 Communities
4.10.1 K-Clique
k_clique_communities(G, k[, cliques]) Find k-clique communities in graph using the percolation method.
k_clique_communities
k_clique_communities(G, k, cliques=None)
Find k-clique communities in graph using the percolation method.
A k-clique community is the union of all cliques of size k that can be reached through adjacent (sharing k-1
nodes) k-cliques.
Parameters G : NetworkX graph
k : int
Size of smallest clique
cliques: list or generator
Precomputed cliques (use networkx.find_cliques(G))
Returns Yields sets of nodes, one for each k-clique community.
References
[R205]
Examples
>>> G = nx.complete_graph(5)
>>> K5 = nx.convert_node_labels_to_integers(G,first_label=2)
>>> G.add_edges_from(K5.edges())
>>> c = list(nx.k_clique_communities(G, 4))
>>> list(c[0])
[0, 1, 2, 3, 4, 5, 6]
>>> list(nx.k_clique_communities(G, 6))
[]
4.11 Components
4.11.1 Connectivity
Connected components.
is_connected
is_connected(G)
Return True if the graph is connected, false otherwise.
Parameters G : NetworkX Graph
An undirected graph.
Returns connected : bool
True if the graph is connected, false otherwise.
See also:
connected_components
Notes
Examples
>>> G = nx.path_graph(4)
>>> print(nx.is_connected(G))
True
number_connected_components
number_connected_components(G)
Return the number of connected components.
Parameters G : NetworkX graph
An undirected graph.
Returns n : integer
Number of connected components
See also:
connected_components
Notes
connected_components
connected_components(G)
Generate connected components.
Parameters G : NetworkX graph
An undirected graph
Returns comp : generator of lists
A list of nodes for each component of G.
See also:
strongly_connected_components
Notes
Examples
connected_component_subgraphs
connected_component_subgraphs(G, copy=True)
Generate connected components as subgraphs.
Parameters G : NetworkX graph
An undirected graph.
copy: bool (default=True)
If True make a copy of the graph attributes
Returns comp : generator
A generator of graphs, one for each connected component of G.
See also:
connected_components
Notes
For undirected graphs only. Graph, node, and edge attributes are copied to the subgraphs by default.
Examples
>>> G = nx.path_graph(4)
>>> G.add_edge(5,6)
>>> graphs = list(nx.connected_component_subgraphs(G))
node_connected_component
node_connected_component(G, n)
Return the nodes in the component of graph containing node n.
Parameters G : NetworkX Graph
An undirected graph.
n : node label
A node in G
Notes
is_strongly_connected
is_strongly_connected(G)
Test directed graph for strong connectivity.
Parameters G : NetworkX Graph
A directed graph.
Returns connected : bool
True if the graph is strongly connected, False otherwise.
See also:
strongly_connected_components
Notes
number_strongly_connected_components
number_strongly_connected_components(G)
Return number of strongly connected components in graph.
Parameters G : NetworkX graph
A directed graph.
Returns n : integer
Notes
strongly_connected_components
strongly_connected_components(G)
Generate nodes in strongly connected components of graph.
Parameters G : NetworkX Graph
An directed graph.
Returns comp : generator of lists
A list of nodes for each strongly connected component of G.
Raises NetworkXNotImplemented: If G is undirected.
See also:
connected_components, weakly_connected_components
Notes
References
[R211], [R212]
strongly_connected_component_subgraphs
strongly_connected_component_subgraphs(G, copy=True)
Generate strongly connected components as subgraphs.
Parameters G : NetworkX Graph
A graph.
Returns comp : generator of lists
A list of graphs, one for each strongly connected component of G.
copy : boolean
if copy is True, Graph, node, and edge attributes are copied to the subgraphs.
See also:
connected_component_subgraphs
strongly_connected_components_recursive
strongly_connected_components_recursive(G)
Generate nodes in strongly connected components of graph.
Recursive version of algorithm.
Parameters G : NetworkX Graph
An directed graph.
Returns comp : generator of lists
A list of nodes for each component of G. The list is ordered from largest connected
component to smallest.
Raises NetworkXNotImplemented : If G is undirected
See also:
connected_components
Notes
References
[R213], [R214]
kosaraju_strongly_connected_components
kosaraju_strongly_connected_components(G, source=None)
Generate nodes in strongly connected components of graph.
Parameters G : NetworkX Graph
An directed graph.
Returns comp : generator of lists
A list of nodes for each component of G.
Raises NetworkXNotImplemented: If G is undirected.
See also:
connected_components
Notes
condensation
condensation(G, scc=None)
Returns the condensation of G.
The condensation of G is the graph with each of the strongly connected components contracted into a single
node.
Parameters G : NetworkX DiGraph
A directed graph.
scc: list or generator (optional, default=None)
Strongly connected components. If provided, the elements in 𝑠𝑐𝑐 must
partition the nodes in 𝐺. If not provided, it will be calculated as
scc=nx.strongly_connected_components(G).
Returns C : NetworkX DiGraph
The condensation graph C of G. The node labels are integers corresponding to the index
of the component in the list of strongly connected components of G. C has a graph
attribute named ‘mapping’ with a dictionary mapping the original nodes to the nodes in
C to which they belong. Each node in C also has a node attribute ‘members’ with the
list of original nodes in G that form the SCC that the node in C represents.
Raises NetworkXNotImplemented: If G is not directed
Notes
After contracting all strongly connected components to a single node, the resulting graph is a directed acyclic
graph.
is_weakly_connected
is_weakly_connected(G)
Test directed graph for weak connectivity.
A directed graph is weakly connected if, and only if, the graph is connected when the direction of the edge
between nodes is ignored.
Parameters G : NetworkX Graph
A directed graph.
Returns connected : bool
True if the graph is weakly connected, False otherwise.
See also:
is_strongly_connected, is_semiconnected, is_connected
Notes
number_weakly_connected_components
number_weakly_connected_components(G)
Return the number of connected components in G. For directed graphs only.
weakly_connected_components
weakly_connected_components(G)
Generate weakly connected components of G.
weakly_connected_component_subgraphs
weakly_connected_component_subgraphs(G, copy=True)
Generate weakly connected components as subgraphs.
Parameters G : NetworkX Graph
A directed graph.
copy : bool
If copy is True, graph, node, and edge attributes are copied to the subgraphs.
Attracting components.
is_attracting_component
is_attracting_component(G)
Returns True if 𝐺 consists of a single attracting component.
Parameters G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns attracting : bool
True if 𝐺 has a single attracting component. Otherwise, False.
See also:
number_attracting_components
number_attracting_components(G)
Returns the number of attracting components in 𝐺.
Parameters G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns n : int
The number of attracting components in G.
See also:
attracting_components, is_attracting_component, attracting_component_subgraphs
attracting_components
attracting_components(G)
Generates a list of attracting components in 𝐺.
An attracting component in a directed graph 𝐺 is a strongly connected component with the property that a
random walker on the graph will never leave the component, once it enters the component.
The nodes in attracting components can also be thought of as recurrent nodes. If a random walker enters the
attractor containing the node, then the node will be visited infinitely often.
Parameters G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns attractors : generator of list
The list of attracting components, sorted from largest attracting component to smallest
attracting component.
See also:
number_attracting_components, is_attracting_component,
attracting_component_subgraphs
attracting_component_subgraphs
attracting_component_subgraphs(G, copy=True)
Generates a list of attracting component subgraphs from 𝐺.
Parameters G : DiGraph, MultiDiGraph
The graph to be analyzed.
Returns subgraphs : list
A list of node-induced subgraphs of the attracting components of 𝐺.
copy : bool
If copy is True, graph, node, and edge attributes are copied to the subgraphs.
See also:
attracting_components, number_attracting_components, is_attracting_component
is_biconnected
is_biconnected(G)
Return True if the graph is biconnected, False otherwise.
A graph is biconnected if, and only if, it cannot be disconnected by removing only one node (and all edges
incident on that node). If removing a node increases the number of disconnected components in the graph, that
node is called an articulation point, or cut vertex. A biconnected graph has no articulation points.
Parameters G : NetworkX Graph
An undirected graph.
Returns biconnected : bool
True if the graph is biconnected, False otherwise.
Raises NetworkXNotImplemented :
If the input graph is not undirected.
See also:
biconnected_components, articulation_points, biconnected_component_edges,
biconnected_component_subgraphs
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node 𝑛
is an articulation point if, and only if, there exists a subtree rooted at 𝑛 such that there is no back edge from
any successor of 𝑛 that links to a predecessor of 𝑛 in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[R210]
Examples
>>> G=nx.path_graph(4)
>>> print(nx.is_biconnected(G))
False
>>> G.add_edge(0,3)
>>> print(nx.is_biconnected(G))
True
biconnected_components
biconnected_components(G)
Return a generator of sets of nodes, one set for each biconnected component of the graph
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component.
Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number
of connected components of the graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G : NetworkX Graph
An undirected graph.
Returns nodes : generator
Generator of sets of nodes, one set for each biconnected component.
Raises NetworkXNotImplemented :
If the input graph is not undirected.
See also:
is_biconnected, articulation_points, biconnected_component_edges,
biconnected_component_subgraphs
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node 𝑛
is an articulation point if, and only if, there exists a subtree rooted at 𝑛 such that there is no back edge from
any successor of 𝑛 that links to a predecessor of 𝑛 in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[R209]
Examples
>>> G = nx.barbell_graph(4,2)
>>> print(nx.is_biconnected(G))
False
>>> components = nx.biconnected_components(G)
>>> G.add_edge(2,8)
>>> print(nx.is_biconnected(G))
True
>>> components = nx.biconnected_components(G)
biconnected_component_edges
biconnected_component_edges(G)
Return a generator of lists of edges, one list for each biconnected component of the input graph.
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected compo-
nent. Those nodes are articulation points, or cut vertices. However, each edge belongs to one, and only one,
biconnected component.
Notice that by convention a dyad is considered a biconnected component.
Parameters G : NetworkX Graph
An undirected graph.
Returns edges : generator of lists
Generator of lists of edges, one list for each bicomponent.
Raises NetworkXNotImplemented :
If the input graph is not undirected.
See also:
is_biconnected, biconnected_components, articulation_points,
biconnected_component_subgraphs
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node 𝑛
is an articulation point if, and only if, there exists a subtree rooted at 𝑛 such that there is no back edge from
any successor of 𝑛 that links to a predecessor of 𝑛 in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[R207]
Examples
>>> G = nx.barbell_graph(4,2)
>>> print(nx.is_biconnected(G))
False
>>> components = nx.biconnected_component_edges(G)
>>> G.add_edge(2,8)
>>> print(nx.is_biconnected(G))
True
>>> components = nx.biconnected_component_edges(G)
biconnected_component_subgraphs
biconnected_component_subgraphs(G, copy=True)
Return a generator of graphs, one graph for each biconnected component of the input graph.
Biconnected components are maximal subgraphs such that the removal of a node (and all edges incident on that
node) will not disconnect the subgraph. Note that nodes may be part of more than one biconnected component.
Those nodes are articulation points, or cut vertices. The removal of articulation points will increase the number
of connected components of the graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G : NetworkX Graph
An undirected graph.
Returns graphs : generator
Generator of graphs, one graph for each biconnected component.
Raises NetworkXNotImplemented :
If the input graph is not undirected.
See also:
is_biconnected, articulation_points, biconnected_component_edges,
biconnected_components
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node 𝑛
is an articulation point if, and only if, there exists a subtree rooted at 𝑛 such that there is no back edge from
any successor of 𝑛 that links to a predecessor of 𝑛 in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
Graph, node, and edge attributes are copied to the subgraphs.
References
[R208]
Examples
>>> G = nx.barbell_graph(4,2)
>>> print(nx.is_biconnected(G))
False
>>> subgraphs = list(nx.biconnected_component_subgraphs(G))
articulation_points
articulation_points(G)
Return a generator of articulation points, or cut vertices, of a graph.
An articulation point or cut vertex is any node whose removal (along with all its incident edges) increases the
number of connected components of a graph. An undirected connected graph without articulation points is
biconnected. Articulation points belong to more than one biconnected component of a graph.
Notice that by convention a dyad is considered a biconnected component.
Parameters G : NetworkX Graph
An undirected graph.
Returns articulation points : generator
generator of nodes
Raises NetworkXNotImplemented :
If the input graph is not undirected.
See also:
is_biconnected, biconnected_components, biconnected_component_edges,
biconnected_component_subgraphs
Notes
The algorithm to find articulation points and biconnected components is implemented using a non-recursive
depth-first-search (DFS) that keeps track of the highest level that back edges reach in the DFS tree. A node 𝑛
is an articulation point if, and only if, there exists a subtree rooted at 𝑛 such that there is no back edge from
any successor of 𝑛 that links to a predecessor of 𝑛 in the DFS tree. By keeping track of all the edges traversed
by the DFS we can obtain the biconnected components because all edges of a bicomponent will be traversed
consecutively between articulation points.
References
[R206]
Examples
>>> G = nx.barbell_graph(4,2)
>>> print(nx.is_biconnected(G))
False
>>> list(nx.articulation_points(G))
[6, 5, 4, 3]
>>> G.add_edge(2,8)
>>> print(nx.is_biconnected(G))
True
>>> list(nx.articulation_points(G))
[]
4.11.6 Semiconnectedness
Semiconnectedness.
is_semiconnected
is_semiconnected(G)
Return True if the graph is semiconnected, False otherwise.
A graph is semiconnected if, and only if, for any pair of nodes, either one is reachable from the other, or they
are mutually reachable.
Parameters G : NetworkX graph
A directed graph.
Returns semiconnected : bool
True if the graph is semiconnected, False otherwise.
Raises NetworkXNotImplemented :
If the input graph is not directed.
NetworkXPointlessConcept :
If the graph is empty.
See also:
is_strongly_connected, is_weakly_connected
Examples
>>> G=nx.path_graph(4,create_using=nx.DiGraph())
>>> print(nx.is_semiconnected(G))
True
>>> G=nx.DiGraph([(1, 2), (3, 2)])
>>> print(nx.is_semiconnected(G))
False
4.12 Connectivity
average_node_connectivity
average_node_connectivity(G, flow_func=None)
Returns the average connectivity of a graph G.
The average connectivity 𝜅
¯ of a graph G is the average of local node connectivity over all pairs of nodes of G
[R215] .
∑︀
𝑢,𝑣 𝜅𝐺 (𝑢, 𝑣)
𝜅
¯ (𝐺) = (︀𝑛)︀
2
References
[R215]
all_pairs_node_connectivity
Undirected graph
nbunch: container
Container of nodes. If provided node connectivity will be computed only over pairs of
nodes in nbunch.
flow_func : function
A function for computing the maximum flow among a pair of nodes. The function has to
accept at least three parameters: a Digraph, a source node, and a target node. And return
a residual network that follows NetworkX conventions (see maximum_flow() for de-
tails). If flow_func is None, the default maximum flow function (edmonds_karp())
is used. See below for details. The choice of the default function may change from
version to version and should not be relied on. Default value: None.
Returns all_pairs : dict
A dictionary with node connectivity between all pairs of nodes in G, or in nbunch if
provided.
See also:
local_node_connectivity(), edge_connectivity(), local_edge_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
edge_connectivity
Notes
This is a flow based implementation of global edge connectivity. For undirected graphs the algorithm works
by finding a ‘small’ dominating set of nodes of G (see algorithm 7 in [R216] ) and computing local maximum
flow (see local_edge_connectivity()) between an arbitrary node in the dominating set and the rest of
nodes in it. This is an implementation of algorithm 6 in [R216] . For directed graphs, the algorithm does n calls
to the maximum flow function. This is an implementation of algorithm 8 in [R216] .
References
[R216]
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.
local_edge_connectivity
Source node
t : node
Target node
flow_func : function
A function for computing the maximum flow among a pair of nodes. The function has to
accept at least three parameters: a Digraph, a source node, and a target node. And return
a residual network that follows NetworkX conventions (see maximum_flow() for de-
tails). If flow_func is None, the default maximum flow function (edmonds_karp())
is used. See below for details. The choice of the default function may change from
version to version and should not be relied on. Default value: None.
auxiliary : NetworkX DiGraph
Auxiliary digraph for computing flow based edge connectivity. If provided it will be
reused instead of recreated. Default value: None.
residual : NetworkX DiGraph
Residual network to compute maximum flow. If provided it will be reused instead of
recreated. Default value: None.
cutoff : integer, float
If specified, the maximum flow algorithm will terminate when the flow value reaches
or exceeds the cutoff. This is only for the algorithms that support the cutoff parame-
ter: edmonds_karp() and shortest_augmenting_path(). Other algorithms
will ignore this parameter. Default value: None.
Returns K : integer
local edge connectivity for nodes s and t.
See also:
edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
Notes
This is a flow based implementation of edge connectivity. We compute the maximum flow using, by default, the
edmonds_karp() algorithm on an auxiliary digraph build from the original input graph:
If the input graph is undirected, we replace each edge (𝑢,‘v‘) with two reciprocal arcs (𝑢, 𝑣) and (𝑣, 𝑢) and
then we set the attribute ‘capacity’ for each arc to 1. If the input graph is directed we simply add the ‘capacity’
attribute. This is an implementation of algorithm 1 in [R217].
The maximum flow in the auxiliary network is equal to the local edge connectivity because the value of a
maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem).
References
[R217]
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
>>> from networkx.algorithms.connectivity import local_edge_connectivity
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph()
>>> local_edge_connectivity(G, 0, 6)
5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
>>> import itertools
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import (
... build_auxiliary_edge_connectivity)
>>> H = build_auxiliary_edge_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, 'capacity')
>>> result = dict.fromkeys(G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in itertools.combinations(G, 2):
... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R)
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
True
You can also use alternative flow algorithms for computing edge connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
5
local_node_connectivity
Notes
This is a flow based implementation of node connectivity. We compute the maximum flow using, by default,
the edmonds_karp() algorithm (see: maximum_flow()) on an auxiliary digraph build from the original
input graph:
For an undirected graph G having 𝑛 nodes and 𝑚 edges we derive a directed graph H with 2𝑛 nodes and 2𝑚 + 𝑛
arcs by replacing each original node 𝑣 with two nodes 𝑣𝐴 , 𝑣𝐵 linked by an (internal) arc in H. Then for each
edge (𝑢, 𝑣) in G we add two arcs (𝑢𝐵 , 𝑣𝐴 ) and (𝑣𝐵 , 𝑢𝐴 ) in H. Finally we set the attribute capacity = 1 for each
arc in H [R219] .
For a directed graph G having 𝑛 nodes and 𝑚 arcs we derive a directed graph H with 2𝑛 nodes and 𝑚 + 𝑛 arcs
by replacing each original node 𝑣 with two nodes 𝑣𝐴 , 𝑣𝐵 linked by an (internal) arc (𝑣𝐴 , 𝑣𝐵 ) in H. Then for
each arc (𝑢, 𝑣) in G we add one arc (𝑢𝐵 , 𝑣𝐴 ) in H. Finally we set the attribute capacity = 1 for each arc in H.
This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of
a minimum s-t-cut.
References
[R219]
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
>>> from networkx.algorithms.connectivity import local_node_connectivity
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph()
>>> local_node_connectivity(G, 0, 6)
5
If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
>>> import itertools
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import (
... build_auxiliary_node_connectivity)
>>> H = build_auxiliary_node_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, 'capacity')
>>> result = dict.fromkeys(G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in itertools.combinations(G, 2):
... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R)
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
True
You can also use alternative flow algorithms for computing node connectivity. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path)
5
node_connectivity
Notes
This is a flow based implementation of node connectivity. The algorithm works by solving 𝑂((𝑛 − 𝛿 − 1 + 𝛿(𝛿 −
1)/2) maximum flow problems on an auxiliary digraph. Where 𝛿 is the minimum degree of G. For details about
the auxiliary digraph and the computation of local node connectivity see local_node_connectivity().
This implementation is based on algorithm 11 in [R220].
References
[R220]
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> nx.node_connectivity(G, flow_func=shortest_augmenting_path)
5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node
connectivity.
>>> nx.node_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_node_connectivity() for details.
minimum_edge_cut
Set of edges that, if removed, would disconnect G. If source and target nodes are pro-
vided, the set contians the edges that if removed, would destroy all paths between source
and target.
See also:
minimum_st_edge_cut(), minimum_node_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
Notes
This is a flow based implementation of minimum edge cut. For undirected graphs the algorithm works by finding
a ‘small’ dominating set of nodes of G (see algorithm 7 in [R221]) and computing the maximum flow between
an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6 in
[R221]. For directed graphs, the algorithm does n calls to the max flow function. It is an implementation of
algorithm 8 in [R221].
References
[R221]
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> len(nx.minimum_edge_cut(G, flow_func=shortest_augmenting_path))
5
If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge
connectivity.
>>> nx.edge_connectivity(G, 3, 7)
5
If you need to perform several local computations among different pairs of nodes on the same graph,
it is recommended that you reuse the data structures used in the maximum flow computations. See
local_edge_connectivity() for details.
minimum_node_cut
If source and target nodes are provided, this function returns the set of nodes of minimum cardinality that, if
removed, would destroy all paths among source and target in G. If not, it returns a set of nodes of minimum
cardinality that disconnects G.
Parameters G : NetworkX graph
s : node
Source node. Optional. Default value: None.
t : node
Target node. Optional. Default value: None.
flow_func : function
A function for computing the maximum flow among a pair of nodes. The function has to
accept at least three parameters: a Digraph, a source node, and a target node. And return
a residual network that follows NetworkX conventions (see maximum_flow() for de-
tails). If flow_func is None, the default maximum flow function (edmonds_karp())
is used. See below for details. The choice of the default function may change from
version to version and should not be relied on. Default value: None.
Returns cutset : set
Set of nodes that, if removed, would disconnect G. If source and target nodes are pro-
vided, the set contians the nodes that if removed, would destroy all paths between source
and target.
See also:
minimum_st_node_cut(), minimum_cut(), minimum_edge_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
Notes
This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in [R222].
References
[R222]
Examples
You can use alternative flow algorithms for the underlying maximum flow computation. In dense net-
works the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp(), which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> node_cut == nx.minimum_node_cut(G, flow_func=shortest_augmenting_path)
True
If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut.
>>> len(nx.minimum_node_cut(G, 3, 7))
5
If you need to perform several local st cuts among different pairs of nodes on the same graph, it is recommended
that you reuse the data structures used in the maximum flow computations. See minimum_st_node_cut()
for details.
minimum_st_edge_cut
See also:
minimum_cut(), minimum_node_cut(), minimum_edge_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
>>> from networkx.algorithms.connectivity import minimum_st_edge_cut
We use in this example the platonic icosahedral graph, which has edge connectivity 5.
>>> G = nx.icosahedral_graph()
>>> len(minimum_st_edge_cut(G, 0, 6))
5
If you need to compute local edge cuts on several pairs of nodes in the same graph, it is recommended that you
reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity,
and the residual network for the underlying maximum flow computation.
Example of how to compute local edge cuts among all pairs of nodes of the platonic icosahedral graph reusing
the data structures.
>>> import itertools
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import (
... build_auxiliary_edge_connectivity)
>>> H = build_auxiliary_edge_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, 'capacity')
>>> result = dict.fromkeys(G, dict())
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> for u, v in itertools.combinations(G, 2):
... k = len(minimum_st_edge_cut(G, u, v, auxiliary=H, residual=R))
... result[u][v] = k
>>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2))
True
You can also use alternative flow algorithms for computing edge cuts. For instance, in dense networks the algo-
rithm shortest_augmenting_path() will usually perform better than the default edmonds_karp()
which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to
be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> len(minimum_st_edge_cut(G, 0, 6, flow_func=shortest_augmenting_path))
5
minimum_st_node_cut
Notes
This is a flow based implementation of minimum node cut. The algorithm is based in solving a number of
maximum flow computations to determine the capacity of the minimum cut on an auxiliary directed network that
corresponds to the minimum node cut of G. It handles both directed and undirected graphs. This implementation
is based on algorithm 11 in [R224].
References
[R224]
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
>>> from networkx.algorithms.connectivity import minimum_st_node_cut
We use in this example the platonic icosahedral graph, which has node connectivity 5.
>>> G = nx.icosahedral_graph()
>>> len(minimum_st_node_cut(G, 0, 6))
5
If you need to compute local st cuts between several pairs of nodes in the same graph, it is recommended that
you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity
and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute local st node cuts reusing the data structures:
>>> # You also have to explicitly import the function for
>>> # building the auxiliary digraph from the connectivity package
>>> from networkx.algorithms.connectivity import (
... build_auxiliary_node_connectivity)
>>> H = build_auxiliary_node_connectivity(G)
>>> # And the function for building the residual network from the
>>> # flow package
>>> from networkx.algorithms.flow import build_residual_network
>>> # Note that the auxiliary digraph has an edge attribute named capacity
>>> R = build_residual_network(H, 'capacity')
>>> # Reuse the auxiliary digraph and the residual network by passing them
>>> # as parameters
>>> len(minimum_st_node_cut(G, 0, 6, auxiliary=H, residual=R))
5
You can also use alternative flow algorithms for computing minimum st node cuts. For instance, in dense
networks the algorithm shortest_augmenting_path() will usually perform better than the default
edmonds_karp() which is faster for sparse networks with highly skewed degree distributions. Alternative
flow functions have to be explicitly imported from the flow package.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> len(minimum_st_node_cut(G, 0, 6, flow_func=shortest_augmenting_path))
5
stoer_wagner(G[, weight, heap]) Returns the weighted minimum edge cut using the Stoer-Wagner algorithm.
stoer_wagner
The running time of the algorithm depends on the type of heaps used:
Type of heap Running time
Binary heap 𝑂(𝑛(𝑚 + 𝑛) log 𝑛)
Fibonacci heap 𝑂(𝑛𝑚 √
+ 𝑛2 log 𝑛)
2 log log 𝑛
Pairing heap 𝑂(2 𝑛𝑚 + 𝑛2 log 𝑛)
Examples
>>> G = nx.Graph()
>>> G.add_edge('x','a', weight=3)
>>> G.add_edge('x','b', weight=1)
>>> G.add_edge('a','c', weight=3)
>>> G.add_edge('b','c', weight=5)
>>> G.add_edge('b','d', weight=4)
>>> G.add_edge('d','e', weight=2)
>>> G.add_edge('c','y', weight=2)
>>> G.add_edge('e','y', weight=3)
>>> cut_value, partition = nx.stoer_wagner(G)
>>> cut_value
4
build_auxiliary_edge_connectivity
build_auxiliary_edge_connectivity(G)
Auxiliary digraph for computing flow based edge connectivity
If the input graph is undirected, we replace each edge (𝑢,‘v‘) with two reciprocal arcs (𝑢, 𝑣) and (𝑣, 𝑢) and
then we set the attribute ‘capacity’ for each arc to 1. If the input graph is directed we simply add the ‘capacity’
attribute. Part of algorithm 1 in [R226] .
References
[R226]
build_auxiliary_node_connectivity
build_auxiliary_node_connectivity(G)
Creates a directed graph D from an undirected graph G to compute flow based node connectivity.
For an undirected graph G having 𝑛 nodes and 𝑚 edges we derive a directed graph D with 2𝑛 nodes and 2𝑚 + 𝑛
arcs by replacing each original node 𝑣 with two nodes 𝑣𝐴, 𝑣𝐵 linked by an (internal) arc in D. Then for each
edge (𝑢, 𝑣) in G we add two arcs (𝑢𝐵, 𝑣𝐴) and (𝑣𝐵, 𝑢𝐴) in D. Finally we set the attribute capacity = 1 for each
arc in D [R227].
For a directed graph having 𝑛 nodes and 𝑚 arcs we derive a directed graph D with 2𝑛 nodes and 𝑚 + 𝑛 arcs by
replacing each original node 𝑣 with two nodes 𝑣𝐴, 𝑣𝐵 linked by an (internal) arc (𝑣𝐴, 𝑣𝐵) in D. Then for each
arc (𝑢, 𝑣) in G we add one arc (𝑢𝐵, 𝑣𝐴) in D. Finally we set the attribute capacity = 1 for each arc in D.
A dictionary with a mapping between nodes in the original graph and the auxiliary digraph is stored as a graph
attribute: H.graph[’mapping’].
References
[R227]
4.13 Cores
4.13.1 core_number
core_number(G)
Return the core number for each vertex.
A k-core is a maximal subgraph that contains nodes of degree k or more.
The core number of a node is the largest value k of a k-core containing that node.
Parameters G : NetworkX graph
A graph or directed graph
Returns core_number : dictionary
A dictionary keyed by node to the core number.
Raises NetworkXError
The k-core is not defined for graphs with self loops or parallel edges.
Notes
References
[R228]
4.13.2 k_core
Notes
References
[R229]
4.13.3 k_shell
Notes
This is similar to k_corona but in that case only neighbors in the k-core are considered.
Not implemented for graphs with parallel edges or self loops.
For directed graphs the node degree is defined to be the in-degree + out-degree.
Graph, node, and edge attributes are copied to the subgraph.
4.13.4 k_crust
Notes
This definition of k-crust is different than the definition in [R231]. The k-crust in [R231] is equivalent to the
k+1 crust of this algorithm.
Not implemented for graphs with parallel edges or self loops.
For directed graphs the node degree is defined to be the in-degree + out-degree.
Graph, node, and edge attributes are copied to the subgraph.
References
[R231]
4.13.5 k_corona
k_corona(G, k, core_number=None)
Return the k-corona of G.
The k-corona is the subgraph of nodes in the k-core which have exactly k neighbours in the k-core.
Parameters G : NetworkX graph
A graph or directed graph
k : int
The order of the corona.
core_number : dictionary, optional
Precomputed core numbers for the graph G.
Returns G : NetworkX graph
The k-corona subgraph
Raises NetworkXError
The k-cornoa is not defined for graphs with self loops or parallel edges.
See also:
core_number
Notes
References
[R230]
4.14 Cycles
cycle_basis(G[, root]) Returns a list of cycles which form a basis for cycles of G.
simple_cycles(G) Find simple cycles (elementary circuits) of a directed graph.
4.14.1 cycle_basis
cycle_basis(G, root=None)
Returns a list of cycles which form a basis for cycles of G.
A basis for cycles of a network is a minimal collection of cycles such that any cycle in the network can be written
as a sum of cycles in the basis. Here summation of cycles is defined as “exclusive or” of the edges. Cycle bases
are useful, e.g. when deriving equations for electric circuits using Kirchhoff’s Laws.
Notes
References
[R232]
Examples
>>> G=nx.Graph()
>>> G.add_cycle([0,1,2,3])
>>> G.add_cycle([0,3,4,5])
>>> print(nx.cycle_basis(G,0))
[[3, 4, 5, 0], [1, 2, 3, 0]]
4.14.2 simple_cycles
simple_cycles(G)
Find simple cycles (elementary circuits) of a directed graph.
An simple cycle, or elementary circuit, is a closed path where no node appears twice, except that the first and
last node are the same. Two elementary circuits are distinct if they are not cyclic permutations of each other.
This is a nonrecursive, iterator/generator version of Johnson’s algorithm [R233]. There may be better algorithms
for some cases [R234] [R235].
Parameters G : NetworkX DiGraph
A directed graph
Returns cycle_generator: generator
A generator that produces elementary cycles of the graph. Each cycle is a list of nodes
with the first and last nodes being the same.
See also:
cycle_basis
Notes
References
Examples
>>> G = nx.DiGraph([(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)])
>>> list(nx.simple_cycles(G))
[[2], [2, 1], [2, 0], [2, 0, 1], [0]]
4.15.1 ancestors
ancestors(G, source)
Return all nodes having a path to 𝑠𝑜𝑢𝑟𝑐𝑒 in G.
Parameters G : NetworkX DiGraph
source : node in G
Returns ancestors : set()
The ancestors of source in G
4.15.2 descendants
descendants(G, source)
Return all nodes reachable from 𝑠𝑜𝑢𝑟𝑐𝑒 in G.
Parameters G : NetworkX DiGraph
source : node in G
Returns des : set()
4.15.3 topological_sort
Notes
This algorithm is based on a description and proof in The Algorithm Design Manual [R237] .
References
[R237]
4.15.4 topological_sort_recursive
Return postorder instead of preorder if True. Reverse mode is a bit more efficient.
Raises NetworkXError
Topological sort is defined for directed graphs only. If the graph G is undirected, a
NetworkXError is raised.
NetworkXUnfeasible
If G is not a directed acyclic graph (DAG) no topological sort exists and a NetworkX-
Unfeasible exception is raised.
See also:
topological_sort, is_directed_acyclic_graph
Notes
4.15.5 is_directed_acyclic_graph
is_directed_acyclic_graph(G)
Return True if the graph G is a directed acyclic graph (DAG) or False if not.
Parameters G : NetworkX graph
A graph
Returns is_dag : bool
True if G is a DAG, false otherwise
4.15.6 is_aperiodic
is_aperiodic(G)
Return True if G is aperiodic.
A directed graph is aperiodic if there is no integer k > 1 that divides the length of every cycle in the graph.
Parameters G : NetworkX DiGraph
Graph
Returns aperiodic : boolean
True if the graph is aperiodic False otherwise
Raises NetworkXError
If G is not directed
Notes
This uses the method outlined in [R236], which runs in O(m) time given m edges in G. Note that a graph is not
aperiodic if it is acyclic as every integer trivial divides length 0 cycles.
References
[R236]
4.16.1 center
center(G, e=None)
Return the center of the graph G.
The center is the set of nodes with eccentricity equal to radius.
Parameters G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns c : list
List of nodes in center
4.16.2 diameter
diameter(G, e=None)
Return the diameter of the graph G.
The diameter is the maximum eccentricity.
Parameters G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns d : integer
Diameter of graph
See also:
eccentricity
4.16.3 eccentricity
4.16.4 periphery
periphery(G, e=None)
Return the periphery of the graph G.
The periphery is the set of nodes with eccentricity equal to the diameter.
Parameters G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns p : list
List of nodes in periphery
4.16.5 radius
radius(G, e=None)
Return the radius of the graph G.
The radius is the minimum eccentricity.
Parameters G : NetworkX graph
A graph
e : eccentricity dictionary, optional
A precomputed dictionary of eccentricities.
Returns r : integer
Radius of graph
4.17.1 is_distance_regular
is_distance_regular(G)
Returns True if the graph is distance regular, False otherwise.
A connected graph G is distance-regular if for any nodes x,y and any integers i,j=0,1,...,d (where d is the graph
diameter), the number of vertices at distance i from x and distance j from y depends only on i,j and the graph
distance between x and y, independently of the choice of x and y.
Parameters G: Networkx graph (undirected)
Returns bool
True if the graph is Distance Regular, False otherwise
See also:
intersection_array, global_parameters
Notes
References
[R240], [R241]
Examples
>>> G=nx.hypercube_graph(6)
>>> nx.is_distance_regular(G)
True
4.17.2 intersection_array
intersection_array(G)
Returns the intersection array of a distance-regular graph.
Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d such that for any 2 vertices x,y in G at a
distance i=d(x,y), there are exactly c_i neighbors of y at a distance of i-1 from x and b_i neighbors of y at a
distance of i+1 from x.
A distance regular graph’sintersection array is given by, [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]
Parameters G: Networkx graph (undirected)
Returns b,c: tuple of lists
See also:
global_parameters
References
[R239]
Examples
>>> G=nx.icosahedral_graph()
>>> nx.intersection_array(G)
([5, 2, 1], [1, 2, 5])
4.17.3 global_parameters
global_parameters(b, c)
Return global parameters for a given intersection array.
Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d such that for any 2 vertices x,y in G at a
distance i=d(x,y), there are exactly c_i neighbors of y at a distance of i-1 from x and b_i neighbors of y at a
distance of i+1 from x.
Thus, a distance regular graph has the global parameters, [[c_0,a_0,b_0],[c_1,a_1,b_1],......,[c_d,a_d,b_d]] for
the intersection array [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d] where a_i+b_i+c_i=k , k= degree of every vertex.
Parameters b,c: tuple of lists
Returns p : list of three-tuples
See also:
intersection_array
References
[R238]
Examples
>>> G=nx.dodecahedral_graph()
>>> b,c=nx.intersection_array(G)
>>> list(nx.global_parameters(b,c))
[(0, 0, 3), (1, 0, 2), (1, 1, 1), (1, 1, 1), (2, 0, 1), (3, 0, 0)]
4.18.1 dominating_set
dominating_set(G, start_with=None)
Finds a dominating set for the graph G.
A dominating set for a graph 𝐺 = (𝑉, 𝐸) is a node subset 𝐷 of 𝑉 such that every node not in 𝐷 is adjacent to
at least one member of 𝐷 [R242].
Parameters G : NetworkX graph
start_with : Node (default=None)
Node to use as a starting point for the algorithm.
Returns D : set
A dominating set for G.
See also:
is_dominating_set
Notes
This function is an implementation of algorithm 7 in [R243] which finds some dominating set, not necessarily
the smallest one.
References
[R242], [R243]
4.18.2 is_dominating_set
is_dominating_set(G, nbunch)
Checks if nodes in nbunch are a dominating set for G.
A dominating set for a graph 𝐺 = (𝑉, 𝐸) is a node subset 𝐷 of 𝑉 such that every node not in 𝐷 is adjacent to
at least one member of 𝐷 [R244].
Parameters G : NetworkX graph
nbunch : Node container
See also:
dominating_set
References
[R244]
4.19 Eulerian
4.19.1 is_eulerian
is_eulerian(G)
Return True if G is an Eulerian graph, False otherwise.
An Eulerian graph is a graph with an Eulerian circuit.
Parameters G : graph
A NetworkX Graph
Notes
This implementation requires the graph to be connected (or strongly connected for directed graphs).
Examples
4.19.2 eulerian_circuit
eulerian_circuit(G, source=None)
Return the edges of an Eulerian circuit in G.
An Eulerian circuit is a path that crosses every edge in G exactly once and finishes at the starting node.
Parameters G : NetworkX Graph or DiGraph
A directed or undirected graph
source : node, optional
Starting node for circuit.
Returns edges : generator
A generator that produces edges in the Eulerian circuit.
Raises NetworkXError
If the graph is not Eulerian.
See also:
is_eulerian
Notes
Linear time algorithm, adapted from [R245]. General information about Euler tours [R246].
References
[R245], [R246]
Examples
>>> G=nx.complete_graph(3)
>>> list(nx.eulerian_circuit(G))
[(0, 2), (2, 1), (1, 0)]
>>> list(nx.eulerian_circuit(G,source=1))
[(1, 2), (2, 0), (0, 1)]
>>> [u for u,v in nx.eulerian_circuit(G)] # nodes in circuit
[0, 2, 1]
4.20 Flows
maximum_flow
A function for computing the maximum flow among a pair of nodes in a capacitated
graph. The function has to accept at least three parameters: a Graph or Digraph, a
source node, and a target node. And return a residual network that follows NetworkX
conventions (see Notes). If flow_func is None, the default maximum flow function
(preflow_push()) is used. See below for alternative algorithms. The choice of
the default function may change from version to version and should not be relied on.
Default value: None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns flow_value : integer, float
Value of the maximum flow, i.e., net outflow from the source.
flow_dict : dict
A dictionary containing the value of the flow that went through each edge.
Raises NetworkXError
The algorithm does not support MultiGraph and MultiDiGraph. If the input graph is an
instance of one of these two classes, a NetworkXError is raised.
NetworkXUnbounded
If the graph has a path of infinite capacity, the value of a feasible flow on the graph is
unbounded above and the function raises a NetworkXUnbounded.
See also:
maximum_flow_value(), minimum_cut(), minimum_cut_value(), edmonds_karp(),
ford_fulkerson(), preflow_push(), shortest_augmenting_path()
Notes
The function used in the flow_func paramter has to return a residual network that follows NetworkX conventions:
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. Reacha-
bility to t using only edges (u, v) such that R[u][v][’flow’] < R[u][v][’capacity’] induces
a minimum s-t cut.
Specific algorithms may store extra data in R.
The function should supports an optional boolean parameter value_only. When True, it can optionally terminate
the algorithm as soon as the maximum flow value and the minimum cut can be determined.
The legacy ford_fulkerson() maximum flow implementation doesn’t follow this conventions but it is
supported as a valid flow_func.
Examples
maximum_flow returns both the value of the maximum flow and a dictionary with all flows.
>>> flow_value, flow_dict = nx.maximum_flow(G, 'x', 'y')
>>> flow_value
3.0
>>> print(flow_dict['x']['b'])
1.0
You can also use alternative algorithms for computing the maximum flow by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> flow_value == nx.maximum_flow(G, 'x', 'y',
... flow_func=shortest_augmenting_path)[0]
True
maximum_flow_value
the default function may change from version to version and should not be relied on.
Default value: None.
kwargs : Any other keyword parameter is passed to the function that
computes the maximum flow.
Returns flow_value : integer, float
Value of the maximum flow, i.e., net outflow from the source.
Raises NetworkXError
The algorithm does not support MultiGraph and MultiDiGraph. If the input graph is an
instance of one of these two classes, a NetworkXError is raised.
NetworkXUnbounded
If the graph has a path of infinite capacity, the value of a feasible flow on the graph is
unbounded above and the function raises a NetworkXUnbounded.
See also:
maximum_flow(), minimum_cut(), minimum_cut_value(), edmonds_karp(),
ford_fulkerson(), preflow_push(), shortest_augmenting_path()
Notes
The function used in the flow_func paramter has to return a residual network that follows NetworkX conventions:
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. Reacha-
bility to t using only edges (u, v) such that R[u][v][’flow’] < R[u][v][’capacity’] induces
a minimum s-t cut.
Specific algorithms may store extra data in R.
The function should supports an optional boolean parameter value_only. When True, it can optionally terminate
the algorithm as soon as the maximum flow value and the minimum cut can be determined.
The legacy ford_fulkerson() maximum flow implementation doesn’t follow this conventions but it is
supported as a valid flow_func.
Examples
You can also use alternative algorithms for computing the maximum flow by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> flow_value == nx.maximum_flow_value(G, 'x', 'y',
... flow_func=shortest_augmenting_path)
True
minimum_cut
Notes
The function used in the flow_func paramter has to return a residual network that follows NetworkX conventions:
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. Reacha-
bility to t using only edges (u, v) such that R[u][v][’flow’] < R[u][v][’capacity’] induces
a minimum s-t cut.
Specific algorithms may store extra data in R.
The function should supports an optional boolean parameter value_only. When True, it can optionally terminate
the algorithm as soon as the maximum flow value and the minimum cut can be determined.
Examples
minimum_cut computes both the value of the minimum cut and the node partition:
>>> cut_value, partition = nx.minimum_cut(G, 'x', 'y')
>>> reachable, non_reachable = partition
‘partition’ here is a tuple with the two sets of nodes that define the minimum cut. You can compute the cut set
of edges that induce the minimum cut as follows:
You can also use alternative algorithms for computing the minimum cut by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> cut_value == nx.minimum_cut(G, 'x', 'y',
... flow_func=shortest_augmenting_path)[0]
True
minimum_cut_value
If the graph has a path of infinite capacity, all cuts have infinite capacity and the function
raises a NetworkXError.
See also:
maximum_flow(), maximum_flow_value(), minimum_cut(), edmonds_karp(),
ford_fulkerson(), preflow_push(), shortest_augmenting_path()
Notes
The function used in the flow_func paramter has to return a residual network that follows NetworkX conventions:
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. Reacha-
bility to t using only edges (u, v) such that R[u][v][’flow’] < R[u][v][’capacity’] induces
a minimum s-t cut.
Specific algorithms may store extra data in R.
The function should supports an optional boolean parameter value_only. When True, it can optionally terminate
the algorithm as soon as the maximum flow value and the minimum cut can be determined.
Examples
You can also use alternative algorithms for computing the minimum cut by using the flow_func parameter.
>>> from networkx.algorithms.flow import shortest_augmenting_path
>>> cut_value == nx.minimum_cut_value(G, 'x', 'y',
... flow_func=shortest_augmenting_path)
True
4.20.2 Edmonds-Karp
edmonds_karp(G, s, t[, capacity, residual, ...]) Find a maximum single-commodity flow using the Edmonds-Karp algorithm.
edmonds_karp
See also:
maximum_flow(), minimum_cut(), ford_fulkerson(), preflow_push(),
shortest_augmenting_path()
Notes
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. If
cutoff is not specified, reachability to t using only edges (u, v) such that R[u][v][’flow’] <
R[u][v][’capacity’] induces a minimum s-t cut.
Examples
The functions that implement flow algorithms and output a residual network, such as this one, are not imported
to the base NetworkX namespace, so you have to explicitly import them from the flow package.
>>> G = nx.DiGraph()
>>> G.add_edge('x','a', capacity=3.0)
>>> G.add_edge('x','b', capacity=1.0)
>>> G.add_edge('a','c', capacity=3.0)
>>> G.add_edge('b','c', capacity=5.0)
>>> G.add_edge('b','d', capacity=4.0)
>>> G.add_edge('d','e', capacity=2.0)
>>> G.add_edge('c','y', capacity=2.0)
>>> G.add_edge('e','y', capacity=3.0)
>>> R = edmonds_karp(G, 'x', 'y')
>>> flow_value = nx.maximum_flow_value(G, 'x', 'y')
>>> flow_value
3.0
>>> flow_value == R.graph['flow_value']
True
4.20.3 Ford-Fulkerson
ford_fulkerson(G, s, t[, capacity]) Find a maximum single-commodity flow using the Ford-Fulkerson algorithm.
ford_fulkerson
ford_fulkerson(G, s, t, capacity=’capacity’)
Find a maximum single-commodity flow using the Ford-Fulkerson algorithm.
Notes
This is a legacy implementation of maximum flow (before 1.9). This function used to return a tuple with the
flow value and the flow dictionary. Now it returns the residual network resulting after computing the maximum
flow, in order to follow the new interface to flow algorithms introduced in NetworkX 1.9.
Note however that the residual network returned by this function does not follow the conventions for residual
networks used by the new algorithms introduced in 1.9. This residual network has edges with capacity equal to
the capacity of the edge in the original network minus the flow that went throught that edge. A dictionary with
infinite capacity edges can be found as an attribute of the residual network.
Examples
The functions that implement flow algorithms and output a residual network, such as this one, are not imported
to the base NetworkX namespace, so you have to explicitly import them from the flow package.
>>> G = nx.DiGraph()
>>> G.add_edge('x','a', capacity=3.0)
>>> G.add_edge('x','b', capacity=1.0)
>>> G.add_edge('a','c', capacity=3.0)
>>> G.add_edge('b','c', capacity=5.0)
>>> G.add_edge('b','d', capacity=4.0)
>>> G.add_edge('d','e', capacity=2.0)
>>> G.add_edge('c','y', capacity=2.0)
>>> G.add_edge('e','y', capacity=3.0)
This function returns the residual network after computing the maximum flow. This network has graph attributes
that contain: a dictionary with edges with infinite capacity flows, the flow value, and a dictionary of flows:
>>> R = ford_fulkerson(G, 'x', 'y')
>>> # A dictionary with infinite capacity flows can be found as an
>>> # attribute of the residual network
>>> inf_capacity_flows = R.graph['inf_capacity_flows']
>>> # There are also attributes for the flow value and the flow dict
>>> flow_value = R.graph['flow_value']
>>> flow_dict = R.graph['flow_dict']
You can use the interface to flow algorithms introduced in 1.9 to get the output that the function ford_fulkerson
used to produce:
>>> flow_value, flow_dict = nx.maximum_flow(G, 'x', 'y',
... flow_func=ford_fulkerson)
shortest_augmenting_path(G, s, t[, ...]) Find a maximum single-commodity flow using the shortest augmenting path algori
shortest_augmenting_path
Edges of the graph G are expected to have an attribute capacity that indicates how much
flow the edge can support. If this attribute is not present, the edge is considered to have
infinite capacity. Default value: ‘capacity’.
residual : NetworkX graph
Residual network on which the algorithm is to be executed. If None, a new residual
network is created. Default value: None.
value_only : bool
If True compute only the value of the maximum flow. This parameter will be ignored
by this algorithm because it is not applicable.
two_phase : bool
If True, a two-phase variant is used. The two-phase variant improves the running time on
unit-capacity networks from 𝑂(𝑛𝑚) to 𝑂(min(𝑛2/3 , 𝑚1/2 )𝑚). Default value: False.
cutoff : integer, float
If specified, the algorithm will terminate when the flow value reaches or exceeds the
cutoff. In this case, it may be unable to immediately determine a minimum cut. Default
value: None.
Returns R : NetworkX DiGraph
Residual network after computing the maximum flow.
Raises NetworkXError
The algorithm does not support MultiGraph and MultiDiGraph. If the input graph is an
instance of one of these two classes, a NetworkXError is raised.
NetworkXUnbounded
If the graph has a path of infinite capacity, the value of a feasible flow on the graph is
unbounded above and the function raises a NetworkXUnbounded.
See also:
maximum_flow(), minimum_cut(), edmonds_karp(), ford_fulkerson(), preflow_push()
Notes
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. If
cutoff is not specified, reachability to t using only edges (u, v) such that R[u][v][’flow’] <
R[u][v][’capacity’] induces a minimum s-t cut.
Examples
The functions that implement flow algorithms and output a residual network, such as this one, are not imported
to the base NetworkX namespace, so you have to explicitly import them from the flow package.
>>> G = nx.DiGraph()
>>> G.add_edge('x','a', capacity=3.0)
>>> G.add_edge('x','b', capacity=1.0)
>>> G.add_edge('a','c', capacity=3.0)
>>> G.add_edge('b','c', capacity=5.0)
>>> G.add_edge('b','d', capacity=4.0)
>>> G.add_edge('d','e', capacity=2.0)
>>> G.add_edge('c','y', capacity=2.0)
>>> G.add_edge('e','y', capacity=3.0)
>>> R = shortest_augmenting_path(G, 'x', 'y')
>>> flow_value = nx.maximum_flow_value(G, 'x', 'y')
>>> flow_value
3.0
>>> flow_value == R.graph['flow_value']
True
4.20.5 Preflow-Push
preflow_push(G, s, t[, capacity, residual, ...]) Find a maximum single-commodity flow using the highest-label preflow-push algo
preflow_push
Notes
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G. For each node u in R, R.node[u][’excess’] represents the difference between flow into u and flow out
of u.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. Reacha-
bility to t using only edges (u, v) such that R[u][v][’flow’] < R[u][v][’capacity’] induces
a minimum s-t cut.
Examples
The functions that implement flow algorithms and output a residual network, such as this one, are not imported
to the base NetworkX namespace, so you have to explicitly import them from the flow package.
>>> G = nx.DiGraph()
>>> G.add_edge('x','a', capacity=3.0)
>>> G.add_edge('x','b', capacity=1.0)
>>> G.add_edge('a','c', capacity=3.0)
>>> G.add_edge('b','c', capacity=5.0)
>>> G.add_edge('b','d', capacity=4.0)
>>> G.add_edge('d','e', capacity=2.0)
>>> G.add_edge('c','y', capacity=2.0)
>>> G.add_edge('e','y', capacity=3.0)
>>> R = preflow_push(G, 'x', 'y')
>>> flow_value = nx.maximum_flow_value(G, 'x', 'y')
>>> flow_value == R.graph['flow_value']
True
>>> # preflow_push also stores the maximum flow value
>>> # in the excess attribute of the sink node t
>>> flow_value == R.node['y']['excess']
True
>>> # For some problems, you might only want to compute a
>>> # maximum preflow.
>>> R = preflow_push(G, 'x', 'y', value_only=True)
>>> flow_value == R.graph['flow_value']
True
>>> flow_value == R.node['y']['excess']
True
4.20.6 Utils
build_residual_network
build_residual_network(G, capacity)
Build a residual network and initialize a zero flow.
The residual network R from an input graph G has the same nodes as G. R is a DiGraph that contains a pair of
edges (u, v) and (v, u) iff (u, v) is not a self-loop, and at least one of (u, v) and (v, u) exists in
G.
For each edge (u, v) in R, R[u][v][’capacity’] is equal to the capacity of (u, v) in G if it exists in
G or zero otherwise. If the capacity is infinite, R[u][v][’capacity’] will have a high arbitrary finite value
that does not affect the solution of the problem. This value is stored in R.graph[’inf’]. For each edge (u,
v) in R, R[u][v][’flow’] represents the flow function of (u, v) and satisfies R[u][v][’flow’]
== -R[v][u][’flow’].
The flow value, defined as the total flow into t, the sink, is stored in R.graph[’flow_value’]. If
cutoff is not specified, reachability to t using only edges (u, v) such that R[u][v][’flow’] <
R[u][v][’capacity’] induces a minimum s-t cut.
network_simplex(G[, demand, capacity, weight]) Find a minimum cost flow satisfying all demands in digraph G.
min_cost_flow_cost(G[, demand, capacity, weight]) Find the cost of a minimum cost flow satisfying all demands in digraph G
Continued on next pag
network_simplex
This exception is raised if the digraph G has a cycle of negative cost and infinite capacity.
Then, the cost of a flow satisfying all demands is unbounded below.
See also:
cost_of_flow, max_flow_min_cost, min_cost_flow, min_cost_flow_cost
Notes
This algorithm is not guaranteed to work if edge weights are floating point numbers (overflows and roundoff
errors can cause problems).
References
Examples
The mincost flow algorithm can also be used to solve shortest path problems. To find the shortest path between
two nodes u and v, give all edges an infinite capacity, give node u a demand of -1 and node v a demand a 1. Then
run the network simplex. The value of a min cost flow will be the distance between u and v and edges carrying
positive flow will indicate the path.
>>> G=nx.DiGraph()
>>> G.add_weighted_edges_from([('s','u',10), ('s','x',5),
... ('u','v',1), ('u','x',2),
... ('v','y',1), ('x','u',3),
... ('x','v',5), ('x','y',2),
... ('y','s',7), ('y','v',6)])
>>> G.add_node('s', demand = -1)
>>> G.add_node('v', demand = 1)
>>> flowCost, flowDict = nx.network_simplex(G)
>>> flowCost == nx.shortest_path_length(G, 's', 'v', weight = 'weight')
True
>>> sorted([(u, v) for u in flowDict for v in flowDict[u] if flowDict[u][v] > 0])
[('s', 'x'), ('u', 'v'), ('x', 'u')]
>>> nx.shortest_path(G, 's', 'v', weight = 'weight')
['s', 'x', 'u', 'v']
It is possible to change the name of the attributes used for the algorithm.
>>> G = nx.DiGraph()
>>> G.add_node('p', spam = -4)
>>> G.add_node('q', spam = 2)
>>> G.add_node('a', spam = -2)
>>> G.add_node('d', spam = -1)
>>> G.add_node('t', spam = 2)
>>> G.add_node('w', spam = 3)
>>> G.add_edge('p', 'q', cost = 7, vacancies = 5)
>>> G.add_edge('p', 'a', cost = 1, vacancies = 4)
>>> G.add_edge('q', 'd', cost = 2, vacancies = 3)
>>> G.add_edge('t', 'q', cost = 1, vacancies = 2)
>>> G.add_edge('a', 't', cost = 2, vacancies = 4)
>>> G.add_edge('d', 'w', cost = 3, vacancies = 4)
>>> G.add_edge('t', 'w', cost = 4, vacancies = 1)
>>> flowCost, flowDict = nx.network_simplex(G, demand = 'spam',
... capacity = 'vacancies',
... weight = 'cost')
>>> flowCost
37
>>> flowDict
{'a': {'t': 4}, 'd': {'w': 2}, 'q': {'d': 1}, 'p': {'q': 2, 'a': 2}, 't': {'q': 1, 'w': 1}, 'w':
min_cost_flow_cost
Raises NetworkXError
This exception is raised if the input graph is not directed or not connected.
NetworkXUnfeasible
This exception is raised in the following situations:
• The sum of the demands is not zero. Then, there is no flow satisfying all demands.
• There is no flow satisfying all demand.
NetworkXUnbounded
This exception is raised if the digraph G has a cycle of negative cost and infinite capacity.
Then, the cost of a flow satisfying all demands is unbounded below.
See also:
cost_of_flow, max_flow_min_cost, min_cost_flow, network_simplex
Examples
min_cost_flow
Edges of the graph G are expected to have an attribute capacity that indicates how much
flow the edge can support. If this attribute is not present, the edge is considered to have
infinite capacity. Default value: ‘capacity’.
weight: string
Edges of the graph G are expected to have an attribute weight that indicates the cost in-
curred by sending one unit of flow on that edge. If not present, the weight is considered
to be 0. Default value: ‘weight’.
Returns flowDict: dictionary
Dictionary of dictionaries keyed by nodes such that flowDict[u][v] is the flow edge (u,
v).
Raises NetworkXError
This exception is raised if the input graph is not directed or not connected.
NetworkXUnfeasible
This exception is raised in the following situations:
• The sum of the demands is not zero. Then, there is no flow satisfying all demands.
• There is no flow satisfying all demand.
NetworkXUnbounded
This exception is raised if the digraph G has a cycle of negative cost and infinite capacity.
Then, the cost of a flow satisfying all demands is unbounded below.
See also:
cost_of_flow, max_flow_min_cost, min_cost_flow_cost, network_simplex
Examples
cost_of_flow
weight: string
Edges of the graph G are expected to have an attribute weight that indicates the cost in-
curred by sending one unit of flow on that edge. If not present, the weight is considered
to be 0. Default value: ‘weight’.
flowDict: dictionary
Dictionary of dictionaries keyed by nodes such that flowDict[u][v] is the flow edge (u,
v).
Returns cost: Integer, float
The total cost of the flow. This is given by the sum over all edges of the product of the
edge’s flow and the edge’s weight.
See also:
max_flow_min_cost, min_cost_flow, min_cost_flow_cost, network_simplex
max_flow_min_cost
This exception is raised if there is an infinite capacity path from s to t in G. In this case
there is no maximum flow. This exception is also raised if the digraph G has a cycle of
negative cost and infinite capacity. Then, the cost of a flow is unbounded below.
See also:
cost_of_flow, ford_fulkerson, min_cost_flow, min_cost_flow_cost,
network_simplex
Examples
>>> G = nx.DiGraph()
>>> G.add_edges_from([(1, 2, {'capacity': 12, 'weight': 4}),
... (1, 3, {'capacity': 20, 'weight': 6}),
... (2, 3, {'capacity': 6, 'weight': -3}),
... (2, 6, {'capacity': 14, 'weight': 1}),
... (3, 4, {'weight': 9}),
... (3, 5, {'capacity': 10, 'weight': 5}),
... (4, 2, {'capacity': 19, 'weight': 13}),
... (4, 5, {'capacity': 4, 'weight': 0}),
... (5, 7, {'capacity': 28, 'weight': 2}),
... (6, 5, {'capacity': 11, 'weight': 1}),
... (6, 7, {'weight': 8}),
... (7, 4, {'capacity': 6, 'weight': 6})])
>>> mincostFlow = nx.max_flow_min_cost(G, 1, 7)
>>> nx.cost_of_flow(G, mincostFlow)
373
>>> from networkx.algorithms.flow import ford_fulkerson
>>> R = ford_fulkerson(G, 1, 7)
>>> maxFlow = R.graph['flow_dict']
>>> nx.cost_of_flow(G, maxFlow)
428
>>> mincostFlowValue = (sum((mincostFlow[u][7] for u in G.predecessors(7)))
... - sum((mincostFlow[7][v] for v in G.successors(7))))
>>> mincostFlowValue == nx.maximum_flow_value(G, 1, 7)
True
capacity_scaling(G[, demand, capacity, ...]) Find a minimum cost flow satisfying all demands in digraph G.
capacity_scaling
Notes
This algorithm does not work if edge weights are floating-point numbers.
Examples
It is possible to change the name of the attributes used for the algorithm.
>>> G = nx.DiGraph()
>>> G.add_node('p', spam = -4)
>>> G.add_node('q', spam = 2)
>>> G.add_node('a', spam = -2)
>>> G.add_node('d', spam = -1)
>>> G.add_node('t', spam = 2)
>>> G.add_node('w', spam = 3)
>>> G.add_edge('p', 'q', cost = 7, vacancies = 5)
>>> G.add_edge('p', 'a', cost = 1, vacancies = 4)
>>> G.add_edge('q', 'd', cost = 2, vacancies = 3)
>>> G.add_edge('t', 'q', cost = 1, vacancies = 2)
>>> G.add_edge('a', 't', cost = 2, vacancies = 4)
>>> G.add_edge('d', 'w', cost = 3, vacancies = 4)
>>> G.add_edge('t', 'w', cost = 4, vacancies = 1)
>>> flowCost, flowDict = nx.capacity_scaling(G, demand = 'spam',
... capacity = 'vacancies',
... weight = 'cost')
>>> flowCost
37
>>> flowDict
{'a': {'t': 4}, 'd': {'w': 2}, 'q': {'d': 1}, 'p': {'q': 2, 'a': 2}, 't': {'q': 1, 'w': 1}, 'w':
4.21.1 is_graphical
is_graphical(sequence, method=’eg’)
Returns True if sequence is a valid degree sequence.
A degree sequence is valid if some graph can realize it.
Parameters sequence : list or iterable container
A sequence of integer node degrees
method : “eg” | “hh”
The method used to validate the degree sequence. “eg” corresponds to the Erdős-Gallai
algorithm, and “hh” to the Havel-Hakimi algorithm.
Returns valid : bool
True if the sequence is a valid degree sequence and False if not.
References
Examples
>>> G = nx.path_graph(4)
>>> sequence = G.degree().values()
>>> nx.is_valid_degree_sequence(sequence)
True
4.21.2 is_digraphical
is_digraphical(in_sequence, out_sequence)
Returns True if some directed graph can realize the in- and out-degree sequences.
Parameters in_sequence : list or iterable container
A sequence of integer node in-degrees
out_sequence : list or iterable container
A sequence of integer node out-degrees
Returns valid : bool
True if in and out-sequences are digraphic False if not.
Notes
This algorithm is from Kleitman and Wang [R247]. The worst case runtime is O(s * log n) where s and n are
the sum and length of the sequences respectively.
References
[R247]
4.21.3 is_multigraphical
is_multigraphical(sequence)
Returns True if some multigraph can realize the sequence.
Parameters deg_sequence : list
A list of integers
Returns valid : bool
True if deg_sequence is a multigraphic degree sequence and False if not.
Notes
The worst-case run time is O(n) where n is the length of the sequence.
References
[R248]
4.21.4 is_pseudographical
is_pseudographical(sequence)
Returns True if some pseudograph can realize the sequence.
Every nonnegative integer sequence with an even sum is pseudographical (see [R249]).
Parameters sequence : list or iterable container
A sequence of integer node degrees
Returns valid : bool
True if the sequence is a pseudographic degree sequence and False if not.
Notes
The worst-case run time is O(n) where n is the length of the sequence.
References
[R249]
4.21.5 is_valid_degree_sequence_havel_hakimi
is_valid_degree_sequence_havel_hakimi(deg_sequence)
Returns True if deg_sequence can be realized by a simple graph.
The validation proceeds using the Havel-Hakimi theorem. Worst-case run time is: O(s) where s is the sum of
the sequence.
Parameters deg_sequence : list
A list of integers where each element specifies the degree of a node in a graph.
Returns valid : bool
True if deg_sequence is graphical and False if not.
Notes
References
4.21.6 is_valid_degree_sequence_erdos_gallai
is_valid_degree_sequence_erdos_gallai(deg_sequence)
Returns True if deg_sequence can be realized by a simple graph.
The validation is done using the Erdős-Gallai theorem [EG1960].
Parameters deg_sequence : list
A list of integers
Returns valid : bool
True if deg_sequence is graphical and False if not.
Notes
This implementation uses an equivalent form of the Erdős-Gallai criterion. Worst-case run time is: O(n) where
n is the length of the sequence.
Specifically, a sequence d is graphical if and only if the sum of the sequence is even and for all strong indices k
in the sequence,
𝑘
∑︁ 𝑛
∑︁ 𝑘−1
∑︁ 𝑘−1
∑︁
𝑑𝑖 ≤ 𝑘(𝑘 − 1) + min(𝑑𝑖 , 𝑘) = 𝑘(𝑛 − 1) − (𝑘 𝑛𝑗 − 𝑗𝑛𝑗 )
𝑖=1 𝑗=𝑘+1 𝑗=0 𝑗=0
A strong index k is any index where 𝑑𝑘 ≥ 𝑘 and the value 𝑛𝑗 is the number of occurrences of j in d. The
maximal strong index is called the Durfee index.
This particular rearrangement comes from the proof of Theorem 3 in [R251].
The ZZ condition says that for the sequence d if
References
[EG1960], [choudum1986]
[R250], [R251]
4.22 Hierarchy
Flow Hierarchy.
4.22.1 flow_hierarchy
flow_hierarchy(G, weight=None)
Returns the flow hierarchy of a directed network.
Flow hierarchy is defined as the fraction of edges not participating in cycles in a directed graph [R253].
Parameters G : DiGraph or MultiDiGraph
A directed graph
weight : key,optional (default=None)
Attribute to use for node weights. If None the weight defaults to 1.
Returns h : float
Flow heirarchy value
Notes
The algorithm described in [R253] computes the flow hierarchy through exponentiation of the adjacency matrix.
This function implements an alternative approach that finds strongly connected components. An edge is in a
cycle if and only if it is in a strongly connected component, which can be found in 𝑂(𝑚) time using Tarjan’s
algorithm.
References
[R253]
4.23 Isolates
4.23.1 is_isolate
is_isolate(G, n)
Determine of node n is an isolate (degree zero).
Parameters G : graph
A networkx graph
n : node
A node in G
Returns isolate : bool
True if n has no neighbors, False otherwise.
Examples
>>> G=nx.Graph()
>>> G.add_edge(1,2)
>>> G.add_node(3)
>>> nx.is_isolate(G,2)
False
>>> nx.is_isolate(G,3)
True
4.23.2 isolates
isolates(G)
Return list of isolates in the graph.
Isolates are nodes with no neighbors (degree zero).
Parameters G : graph
A networkx graph
Returns isolates : list
List of isolate nodes.
Examples
>>> G = nx.Graph()
>>> G.add_edge(1,2)
>>> G.add_node(3)
>>> nx.isolates(G)
[3]
To remove all isolates in the graph use >>> G.remove_nodes_from(nx.isolates(G)) >>> G.nodes() [1, 2]
For digraphs isolates have zero in-degree and zero out_degre >>> G = nx.DiGraph([(0,1),(1,2)]) >>>
G.add_node(3) >>> nx.isolates(G) [3]
4.24 Isomorphism
is_isomorphic(G1, G2[, node_match, edge_match]) Returns True if the graphs G1 and G2 are isomorphic and False otherwise.
could_be_isomorphic(G1, G2) Returns False if graphs are definitely not isomorphic.
fast_could_be_isomorphic(G1, G2) Returns False if graphs are definitely not isomorphic.
faster_could_be_isomorphic(G1, G2) Returns False if graphs are definitely not isomorphic.
4.24.1 is_isomorphic
Notes
References
[R254]
Examples
For multidigraphs G1 and G2, using ‘fill’ node attribute (default: ‘’)
>>> G1 = nx.MultiDiGraph()
>>> G2 = nx.MultiDiGraph()
>>> G1.add_nodes_from([1,2,3],fill='red')
>>> G2.add_nodes_from([10,20,30,40],fill='red')
>>> G1.add_path([1,2,3,4],weight=3, linewidth=2.5)
>>> G2.add_path([10,20,30,40],weight=3)
>>> nm = iso.categorical_node_match('fill', 'red')
>>> nx.is_isomorphic(G1, G2, node_match=nm)
True
For multigraphs G1 and G2, using ‘weight’ and ‘linewidth’ edge attributes with default values 7 and 2.5. Also
using ‘fill’ node attribute with default value ‘red’.
>>> em = iso.numerical_multiedge_match(['weight', 'linewidth'], [7, 2.5])
>>> nm = iso.categorical_node_match('fill', 'red')
>>> nx.is_isomorphic(G1, G2, edge_match=em, node_match=nm)
True
4.24.2 could_be_isomorphic
could_be_isomorphic(G1, G2)
Returns False if graphs are definitely not isomorphic. True does NOT guarantee isomorphism.
Parameters G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
4.24.3 fast_could_be_isomorphic
fast_could_be_isomorphic(G1, G2)
Returns False if graphs are definitely not isomorphic.
True does NOT guarantee isomorphism.
Parameters G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
4.24.4 faster_could_be_isomorphic
faster_could_be_isomorphic(G1, G2)
Returns False if graphs are definitely not isomorphic.
True does NOT guarantee isomorphism.
Parameters G1, G2 : graphs
The two graphs G1 and G2 must be the same type.
Notes
VF2 Algorithm
Introduction
The GraphMatcher and DiGraphMatcher are responsible for matching graphs or directed graphs in a predetermined
manner. This usually means a check for an isomorphism, though other checks are also possible. For example, a
subgraph of one graph can be checked for isomorphism to a second graph.
Matching is done via syntactic feasibility. It is also possible to check for semantic feasibility. Feasibility, then, is
defined as the logical AND of the two functions.
To include a semantic check, the (Di)GraphMatcher class should be subclassed, and the semantic_feasibility() function
should be redefined. By default, the semantic feasibility function always returns True. The effect of this is that
semantics are not considered in the matching of G1 and G2.
Examples
Subgraph Isomorphism
Graph theory literature can be ambiguious about the meaning of the above statement, and we seek to clarify it now.
In the VF2 literature, a mapping M is said to be a graph-subgraph isomorphism iff M is an isomorphism between G2
and a subgraph of G1. Thus, to say that G1 and G2 are graph-subgraph isomorphic is to say that a subgraph of G1 is
isomorphic to G2.
Other literature uses the phrase ‘subgraph isomorphic’ as in ‘G1 does not have a subgraph isomorphic to G2’. Another
use is as an in adverb for isomorphic. Thus, to say that G1 and G2 are subgraph isomorphic is to say that a subgraph
of G1 is isomorphic to G2.
Finally, the term ‘subgraph’ can have multiple meanings. In this context, ‘subgraph’ always means a ‘node-induced
subgraph’. Edge-induced subgraph isomorphisms are not directly supported, but one should be able to perform the
check by making use of nx.line_graph(). For subgraphs which are not induced, the term ‘monomorphism’ is preferred
over ‘isomorphism’. Currently, it is not possible to check for monomorphisms.
Let G=(N,E) be a graph with a set of nodes N and set of edges E.
If G’=(N’,E’) is a subgraph, then: N’ is a subset of N E’ is a subset of E
If G’=(N’,E’) is a node-induced subgraph, then: N’ is a subset of N E’ is the subset of edges in E relating nodes in
N’
If G’=(N’,E’) is an edge-induced subgrpah, then: N’ is the subset of nodes in N related by edges in E’ E’ is a subset
of E
References
[1] Luigi P. Cordella, Pasquale Foggia, Carlo Sansone, Mario Vento, “A (Sub)Graph Isomorphism Algorithm for
Matching Large Graphs”, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 26, no. 10, pp.
1367-1372, Oct., 2004. http://ieeexplore.ieee.org/iel5/34/29305/01323804.pdf
[2] L. P. Cordella, P. Foggia, C. Sansone, M. Vento, “An Improved Algorithm for Matching Large Graphs”, 3rd
IAPR-TC15 Workshop on Graph-based Representations in Pattern Recognition, Cuen, pp. 149-159, 2001.
http://amalfi.dis.unina.it/graph/db/papers/vf-algorithm.pdf
See Also
syntactic_feasibliity(), semantic_feasibility()
Notes
Graph Matcher
__init__
GraphMatcher.__init__(G1, G2, node_match=None, edge_match=None)
Initialize graph matcher.
Parameters G1, G2: graph
The graphs to be tested.
node_match: callable
A function that returns True iff node n1 in G1 and n2 in G2 should be considered equal
during the isomorphism test. The function will be called like:
node_match(G1.node[n1], G2.node[n2])
That is, the function will receive the node attribute dictionaries of the nodes under con-
sideration. If None, then no attributes are considered when testing for an isomorphism.
edge_match: callable
A function that returns True iff the edge attribute dictionary for the pair of nodes (u1,
v1) in G1 and (u2, v2) in G2 should be considered equal during the isomorphism test.
The function will be called like:
edge_match(G1[u1][v1], G2[u2][v2])
That is, the function will receive the edge attribute dictionaries of the edges under con-
sideration. If None, then no attributes are considered when testing for an isomorphism.
initialize
GraphMatcher.initialize()
Reinitializes the state of the algorithm.
This method should be redefined if using something other than GMState. If only subclassing GraphMatcher, a
redefinition is not necessary.
is_isomorphic
GraphMatcher.is_isomorphic()
Returns True if G1 and G2 are isomorphic graphs.
subgraph_is_isomorphic
GraphMatcher.subgraph_is_isomorphic()
Returns True if a subgraph of G1 is isomorphic to G2.
isomorphisms_iter
GraphMatcher.isomorphisms_iter()
Generator over isomorphisms between G1 and G2.
subgraph_isomorphisms_iter
GraphMatcher.subgraph_isomorphisms_iter()
Generator over isomorphisms between a subgraph of G1 and G2.
candidate_pairs_iter
GraphMatcher.candidate_pairs_iter()
Iterator over candidate pairs of nodes in G1 and G2.
match
GraphMatcher.match()
Extends the isomorphism mapping.
This function is called recursively to determine if a complete isomorphism can be found between G1 and G2. It
cleans up the class variables after each recursive call. If an isomorphism is found, we yield the mapping.
semantic_feasibility
GraphMatcher.semantic_feasibility(G1_node, G2_node)
Returns True if mapping G1_node to G2_node is semantically feasible.
syntactic_feasibility
GraphMatcher.syntactic_feasibility(G1_node, G2_node)
Returns True if adding (G1_node, G2_node) is syntactically feasible.
This function returns True if it is adding the candidate pair to the current partial isomorphism mapping is
allowable. The addition is allowable if the inclusion of the candidate pair does not make it impossible for an
isomorphism to be found.
DiGraph Matcher
__init__
DiGraphMatcher.__init__(G1, G2, node_match=None, edge_match=None)
Initialize graph matcher.
Parameters G1, G2 : graph
The graphs to be tested.
node_match : callable
A function that returns True iff node n1 in G1 and n2 in G2 should be considered equal
during the isomorphism test. The function will be called like:
node_match(G1.node[n1], G2.node[n2])
That is, the function will receive the node attribute dictionaries of the nodes under con-
sideration. If None, then no attributes are considered when testing for an isomorphism.
edge_match : callable
A function that returns True iff the edge attribute dictionary for the pair of nodes (u1,
v1) in G1 and (u2, v2) in G2 should be considered equal during the isomorphism test.
The function will be called like:
edge_match(G1[u1][v1], G2[u2][v2])
That is, the function will receive the edge attribute dictionaries of the edges under con-
sideration. If None, then no attributes are considered when testing for an isomorphism.
initialize
DiGraphMatcher.initialize()
Reinitializes the state of the algorithm.
This method should be redefined if using something other than DiGMState. If only subclassing GraphMatcher,
a redefinition is not necessary.
is_isomorphic
DiGraphMatcher.is_isomorphic()
Returns True if G1 and G2 are isomorphic graphs.
subgraph_is_isomorphic
DiGraphMatcher.subgraph_is_isomorphic()
Returns True if a subgraph of G1 is isomorphic to G2.
isomorphisms_iter
DiGraphMatcher.isomorphisms_iter()
Generator over isomorphisms between G1 and G2.
subgraph_isomorphisms_iter
DiGraphMatcher.subgraph_isomorphisms_iter()
Generator over isomorphisms between a subgraph of G1 and G2.
candidate_pairs_iter
DiGraphMatcher.candidate_pairs_iter()
Iterator over candidate pairs of nodes in G1 and G2.
match
DiGraphMatcher.match()
Extends the isomorphism mapping.
This function is called recursively to determine if a complete isomorphism can be found between G1 and G2. It
cleans up the class variables after each recursive call. If an isomorphism is found, we yield the mapping.
semantic_feasibility
DiGraphMatcher.semantic_feasibility(G1_node, G2_node)
Returns True if mapping G1_node to G2_node is semantically feasible.
syntactic_feasibility
DiGraphMatcher.syntactic_feasibility(G1_node, G2_node)
Returns True if adding (G1_node, G2_node) is syntactically feasible.
This function returns True if it is adding the candidate pair to the current partial isomorphism mapping is
allowable. The addition is allowable if the inclusion of the candidate pair does not make it impossible for an
isomorphism to be found.
Match helpers
categorical_node_match
categorical_node_match(attr, default)
Returns a comparison function for a categorical node attribute.
The value(s) of the attr(s) must be hashable and comparable via the == operator since they are placed into a
set([]) object. If the sets from G1 and G2 are the same, then the constructed function returns True.
Parameters attr : string | list
The categorical node attribute to compare, or a list of categorical node attributes to
compare.
default : value | list
The default value for the categorical node attribute, or a list of default values for the
categorical node attributes.
Returns match : function
The customized, categorical 𝑛𝑜𝑑𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
categorical_edge_match
categorical_edge_match(attr, default)
Returns a comparison function for a categorical edge attribute.
The value(s) of the attr(s) must be hashable and comparable via the == operator since they are placed into a
set([]) object. If the sets from G1 and G2 are the same, then the constructed function returns True.
Parameters attr : string | list
The categorical edge attribute to compare, or a list of categorical edge attributes to
compare.
default : value | list
The default value for the categorical edge attribute, or a list of default values for the
categorical edge attributes.
Returns match : function
The customized, categorical 𝑒𝑑𝑔𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
categorical_multiedge_match
categorical_multiedge_match(attr, default)
Returns a comparison function for a categorical edge attribute.
The value(s) of the attr(s) must be hashable and comparable via the == operator since they are placed into a
set([]) object. If the sets from G1 and G2 are the same, then the constructed function returns True.
Parameters attr : string | list
The categorical edge attribute to compare, or a list of categorical edge attributes to
compare.
default : value | list
The default value for the categorical edge attribute, or a list of default values for the
categorical edge attributes.
Returns match : function
The customized, categorical 𝑒𝑑𝑔𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
numerical_node_match
numerical_node_match(attr, default, rtol=1e-05, atol=1e-08)
Returns a comparison function for a numerical node attribute.
The value(s) of the attr(s) must be numerical and sortable. If the sorted list of values from G1 and G2 are the
same within some tolerance, then the constructed function returns True.
Parameters attr : string | list
The numerical node attribute to compare, or a list of numerical node attributes to com-
pare.
default : value | list
The default value for the numerical node attribute, or a list of default values for the
numerical node attributes.
rtol : float
The relative error tolerance.
atol : float
The absolute error tolerance.
Returns match : function
Examples
numerical_edge_match
numerical_edge_match(attr, default, rtol=1e-05, atol=1e-08)
Returns a comparison function for a numerical edge attribute.
The value(s) of the attr(s) must be numerical and sortable. If the sorted list of values from G1 and G2 are the
same within some tolerance, then the constructed function returns True.
Parameters attr : string | list
The numerical edge attribute to compare, or a list of numerical edge attributes to com-
pare.
default : value | list
The default value for the numerical edge attribute, or a list of default values for the
numerical edge attributes.
rtol : float
The relative error tolerance.
atol : float
The absolute error tolerance.
Returns match : function
The customized, numerical 𝑒𝑑𝑔𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
numerical_multiedge_match
numerical_multiedge_match(attr, default, rtol=1e-05, atol=1e-08)
Returns a comparison function for a numerical edge attribute.
The value(s) of the attr(s) must be numerical and sortable. If the sorted list of values from G1 and G2 are the
same within some tolerance, then the constructed function returns True.
Parameters attr : string | list
The numerical edge attribute to compare, or a list of numerical edge attributes to com-
pare.
default : value | list
The default value for the numerical edge attribute, or a list of default values for the
numerical edge attributes.
rtol : float
The relative error tolerance.
atol : float
The absolute error tolerance.
Returns match : function
The customized, numerical 𝑒𝑑𝑔𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
generic_node_match
generic_node_match(attr, default, op)
Returns a comparison function for a generic attribute.
The value(s) of the attr(s) are compared using the specified operators. If all the attributes are equal, then the
constructed function returns True.
Parameters attr : string | list
The node attribute to compare, or a list of node attributes to compare.
default : value | list
The default value for the node attribute, or a list of default values for the node attributes.
op : callable | list
The operator to use when comparing attribute values, or a list of operators to use when
comparing values for each attribute.
Returns match : function
The customized, generic 𝑛𝑜𝑑𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
generic_edge_match
Examples
generic_multiedge_match
generic_multiedge_match(attr, default, op)
Returns a comparison function for a generic attribute.
The value(s) of the attr(s) are compared using the specified operators. If all the attributes are equal, then the
constructed function returns True. Potentially, the constructed edge_match function can be slow since it must
verify that no isomorphism exists between the multiedges before it returns False.
Parameters attr : string | list
The edge attribute to compare, or a list of node attributes to compare.
default : value | list
The default value for the edge attribute, or a list of default values for the dgeattributes.
op : callable | list
The operator to use when comparing attribute values, or a list of operators to use when
comparing values for each attribute.
Returns match : function
The customized, generic 𝑒𝑑𝑔𝑒𝑚 𝑎𝑡𝑐ℎ function.
Examples
4.25.1 PageRank
pagerank(G[, alpha, personalization, ...]) Return the PageRank of the nodes in the graph.
pagerank_numpy(G[, alpha, personalization, ...]) Return the PageRank of the nodes in the graph.
pagerank_scipy(G[, alpha, personalization, ...]) Return the PageRank of the nodes in the graph.
google_matrix(G[, alpha, personalization, ...]) Return the Google matrix of the graph.
pagerank
Notes
The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The
iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached.
The PageRank algorithm was designed for directed graphs but this algorithm does not check if the input graph
is directed and will execute on undirected graphs by converting each edge in the directed graph to two edges.
References
[R261], [R262]
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank(G, alpha=0.9)
pagerank_numpy
The “personalization vector” consisting of a dictionary with a key for every graph node
and nonzero personalization value for each node. By default, a uniform distribution is
used.
weight : key, optional
Edge data key to use as weight. If None weights are set to 1.
dangling: dict, optional
The outedges to be assigned to any “dangling” nodes, i.e., nodes without any outedges.
The dict key is the node the outedge points to and the dict value is the weight of that
outedge. By default, dangling nodes are given outedges according to the personalization
vector (uniform if not specified) This must be selected to result in an irreducible tran-
sition matrix (see notes under google_matrix). It may be common to have the dangling
dict to be the same as the personalization dict.
Returns pagerank : dictionary
Dictionary of nodes with PageRank as value.
See also:
pagerank, pagerank_scipy, google_matrix
Notes
The eigenvector calculation uses NumPy’s interface to the LAPACK eigenvalue solvers. This will be the fastest
and most accurate for small graphs.
This implementation works with Multi(Di)Graphs. For multigraphs the weight between two nodes is set to be
the sum of all edge weights between those nodes.
References
[R263], [R264]
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank_numpy(G, alpha=0.9)
pagerank_scipy
Notes
The eigenvector calculation uses power iteration with a SciPy sparse matrix representation.
This implementation works with Multi(Di)Graphs. For multigraphs the weight between two nodes is set to be
the sum of all edge weights between those nodes.
References
[R265], [R266]
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank_scipy(G, alpha=0.9)
google_matrix
Parameters G : graph
A NetworkX graph. Undirected graphs will be converted to a directed graph with two
directed edges for each undirected edge.
alpha : float
The damping factor.
personalization: dict, optional
The “personalization vector” consisting of a dictionary with a key for every graph node
and nonzero personalization value for each node. By default, a uniform distribution is
used.
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist. If nodelist is
None, then the ordering is produced by G.nodes().
weight : key, optional
Edge data key to use as weight. If None weights are set to 1.
dangling: dict, optional
The outedges to be assigned to any “dangling” nodes, i.e., nodes without any outedges.
The dict key is the node the outedge points to and the dict value is the weight of that
outedge. By default, dangling nodes are given outedges according to the personaliza-
tion vector (uniform if not specified) This must be selected to result in an irreducible
transition matrix (see notes below). It may be common to have the dangling dict to be
the same as the personalization dict.
Returns A : NumPy matrix
Google matrix of the graph
See also:
pagerank, pagerank_numpy, pagerank_scipy
Notes
The matrix returned represents the transition matrix that describes the Markov chain used in PageRank. For
PageRank to converge to a unique solution (i.e., a unique stationary distribution in a Markov chain), the transition
matrix must be irreducible. In other words, it must be that there exists a path between every pair of nodes in the
graph, or else there is the potential of “rank sinks.”
This implementation works with Multi(Di)Graphs. For multigraphs the weight between two nodes is set to be
the sum of all edge weights between those nodes.
4.25.2 Hits
hits(G[, max_iter, tol, nstart, normalized]) Return HITS hubs and authorities values for nodes.
hits_numpy(G[, normalized]) Return HITS hubs and authorities values for nodes.
hits_scipy(G[, max_iter, tol, normalized]) Return HITS hubs and authorities values for nodes.
hub_matrix(G[, nodelist]) Return the HITS hub matrix.
Continued on next page
hits
Notes
The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The
iteration will stop after max_iter iterations or an error tolerance of number_of_nodes(G)*tol has been reached.
The HITS algorithm was designed for directed graphs but this algorithm does not check if the input graph is
directed and will execute on undirected graphs.
References
[R255], [R256]
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
hits_numpy
hits_numpy(G, normalized=True)
Return HITS hubs and authorities values for nodes.
The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the
incoming links. Hubs estimates the node value based on outgoing links.
Parameters G : graph
A NetworkX graph
normalized : bool (default=True)
Normalize results by the sum of all of the values.
Returns (hubs,authorities) : two-tuple of dictionaries
Two dictionaries keyed by node containing the hub and authority values.
Notes
References
[R257], [R258]
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
hits_scipy
Notes
References
[R259], [R260]
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
hub_matrix
hub_matrix(G, nodelist=None)
Return the HITS hub matrix.
authority_matrix
authority_matrix(G, nodelist=None)
Return the HITS authority matrix.
resource_allocation_index(G[, ebunch]) Compute the resource allocation index of all node pairs in ebunch.
jaccard_coefficient(G[, ebunch]) Compute the Jaccard coefficient of all node pairs in ebunch.
adamic_adar_index(G[, ebunch]) Compute the Adamic-Adar index of all node pairs in ebunch.
preferential_attachment(G[, ebunch]) Compute the preferential attachment score of all node pairs in ebunch.
cn_soundarajan_hopcroft(G[, ebunch, community]) Count the number of common neighbors of all node pairs in ebunch us
ra_index_soundarajan_hopcroft(G[, ebunch, ...]) Compute the resource allocation index of all node pairs in ebunch usin
within_inter_cluster(G[, ebunch, delta, ...]) Compute the ratio of within- and inter-cluster common neighbors of al
4.26.1 resource_allocation_index
resource_allocation_index(G, ebunch=None)
Compute the resource allocation index of all node pairs in ebunch.
Resource allocation index of 𝑢 and 𝑣 is defined as
∑︁ 1
|Γ(𝑤)|
𝑤∈Γ(𝑢)∩Γ(𝑣)
References
[R272]
Examples
4.26.2 jaccard_coefficient
jaccard_coefficient(G, ebunch=None)
Compute the Jaccard coefficient of all node pairs in ebunch.
Jaccard coefficient of nodes 𝑢 and 𝑣 is defined as
|Γ(𝑢) ∩ Γ(𝑣)|
|Γ(𝑢) ∪ Γ(𝑣)|
where Γ(𝑢) denotes the set of neighbors of 𝑢.
Parameters G : graph
A NetworkX undirected graph.
References
[R269]
Examples
4.26.3 adamic_adar_index
adamic_adar_index(G, ebunch=None)
Compute the Adamic-Adar index of all node pairs in ebunch.
Adamic-Adar index of 𝑢 and 𝑣 is defined as
∑︁ 1
log |Γ(𝑤)|
𝑤∈Γ(𝑢)∩Γ(𝑣)
References
[R267]
Examples
4.26.4 preferential_attachment
preferential_attachment(G, ebunch=None)
Compute the preferential attachment score of all node pairs in ebunch.
Preferential attachment score of 𝑢 and 𝑣 is defined as
|Γ(𝑢)||Γ(𝑣)|
References
[R270]
Examples
4.26.5 cn_soundarajan_hopcroft
where 𝑓 (𝑤) equals 1 if 𝑤 belongs to the same community as 𝑢 and 𝑣 or 0 otherwise and Γ(𝑢) denotes the set of
neighbors of 𝑢.
Parameters G : graph
A NetworkX undirected graph.
ebunch : iterable of node pairs, optional (default = None)
The score will be computed for each pair of nodes given in the iterable. The pairs must
be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then
all non-existent edges in the graph will be used. Default value: None.
community : string, optional (default = ‘community’)
Nodes attribute name containing the community information. G[u][community] iden-
tifies which community u belongs to. Each node belongs to at most one community.
Default value: ‘community’.
Returns piter : iterator
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their
score.
References
[R268]
Examples
4.26.6 ra_index_soundarajan_hopcroft
For two nodes 𝑢 and 𝑣, this function computes the resource allocation index considering only common neighbors
belonging to the same community as 𝑢 and 𝑣. Mathematically,
∑︁ 𝑓 (𝑤)
|Γ(𝑤)|
𝑤∈Γ(𝑢)∩Γ(𝑣)
where 𝑓 (𝑤) equals 1 if 𝑤 belongs to the same community as 𝑢 and 𝑣 or 0 otherwise and Γ(𝑢) denotes the set of
neighbors of 𝑢.
Parameters G : graph
A NetworkX undirected graph.
ebunch : iterable of node pairs, optional (default = None)
The score will be computed for each pair of nodes given in the iterable. The pairs must
be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is None then
all non-existent edges in the graph will be used. Default value: None.
community : string, optional (default = ‘community’)
Nodes attribute name containing the community information. G[u][community] iden-
tifies which community u belongs to. Each node belongs to at most one community.
Default value: ‘community’.
Returns piter : iterator
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their
score.
References
[R271]
Examples
4.26.7 within_inter_cluster
𝑢 and 𝑣. The ratio between the size of the set of within- and inter-cluster common neighbors is defined as the
WIC measure. [R273]
Parameters G : graph
A NetworkX undirected graph.
ebunch : iterable of node pairs, optional (default = None)
The WIC measure will be computed for each pair of nodes given in the iterable. The
pairs must be given as 2-tuples (u, v) where u and v are nodes in the graph. If ebunch is
None then all non-existent edges in the graph will be used. Default value: None.
delta : float, optional (default = 0.001)
Value to prevent division by zero in case there is no inter-cluster common neighbor
between two nodes. See [R273] for details. Default value: 0.001.
community : string, optional (default = ‘community’)
Nodes attribute name containing the community information. G[u][community] iden-
tifies which community u belongs to. Each node belongs to at most one community.
Default value: ‘community’.
Returns piter : iterator
An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is their
WIC measure.
References
[R273]
Examples
4.27 Matching
4.27.1 maximal_matching
maximal_matching(G)
Find a maximal cardinality matching in the graph.
A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the
number of matched edges.
Parameters G : NetworkX graph
Undirected graph
Returns matching : set
A maximal matching of the graph.
Notes
The algorithm greedily selects a maximal matching M of the graph G (i.e. no superset of M exists). It runs in
𝑂(|𝐸|) time.
4.27.2 max_weight_matching
max_weight_matching(G, maxcardinality=False)
Compute a maximum-weighted matching of G.
A matching is a subset of edges in which no node occurs more than once. The cardinality of a matching is the
number of matched edges. The weight of a matching is the sum of the weights of its edges.
Parameters G : NetworkX graph
Undirected graph
maxcardinality: bool, optional
If maxcardinality is True, compute the maximum-cardinality matching with maximum
weight among all maximum-cardinality matchings.
Returns mate : dictionary
The matching is returned as a dictionary, mate, such that mate[v] == w if node v is
matched to node w. Unmatched nodes do not occur as a key in mate.
Notes
If G has edges with ‘weight’ attribute the edge data are used as weight values else the weights are assumed to
be 1.
This function takes time O(number_of_nodes ** 3).
If all edge weights are integers, the algorithm uses only integer computations. If floating point weights are used,
the algorithm could return a slightly suboptimal matching due to numeric precision errors.
This method is based on the “blossom” method for finding augmenting paths and the “primal-dual” method for
finding a matching of maximum weight, both methods invented by Jack Edmonds [R274].
References
[R274]
maximal_independent_set(G[, nodes]) Return a random maximal independent set guaranteed to contain a given set of nodes
4.28.1 maximal_independent_set
maximal_independent_set(G, nodes=None)
Return a random maximal independent set guaranteed to contain a given set of nodes.
An independent set is a set of nodes such that the subgraph of G induced by these nodes contains no edges. A
maximal independent set is an independent set such that it is not possible to add a new node and still get an
independent set.
Parameters G : NetworkX graph
nodes : list or iterable
Nodes that must be part of the independent set. This set of nodes must be independent.
Returns indep_nodes : list
List of nodes that are part of a maximal independent set.
Raises NetworkXUnfeasible
If the nodes in the provided list are not part of the graph or do not form an independent
set, an exception is raised.
Notes
This algorithm does not solve the maximum independent set problem.
Examples
>>> G = nx.path_graph(5)
>>> nx.maximal_independent_set(G)
[4, 0, 2]
>>> nx.maximal_independent_set(G, [1])
[1, 3]
minimum_spanning_tree(G[, weight]) Return a minimum spanning tree or forest of an undirected weighted graph.
minimum_spanning_edges(G[, weight, data]) Generate edges in a minimum spanning forest of an undirected weighted graph.
4.29.1 minimum_spanning_tree
minimum_spanning_tree(G, weight=’weight’)
Return a minimum spanning tree or forest of an undirected weighted graph.
A minimum spanning tree is a subgraph of the graph (a tree) with the minimum sum of edge weights.
If the graph is not connected a spanning forest is constructed. A spanning forest is a union of the spanning trees
for each connected component of the graph.
Parameters G : NetworkX Graph
weight : string
Edge data key to use for weight (default ‘weight’).
Returns G : NetworkX Graph
A minimum spanning tree or forest.
Notes
Examples
>>> G=nx.cycle_graph(4)
>>> G.add_edge(0,3,weight=2) # assign weight 2 to edge 0-3
>>> T=nx.minimum_spanning_tree(G)
>>> print(sorted(T.edges(data=True)))
[(0, 1, {}), (1, 2, {}), (2, 3, {})]
4.29.2 minimum_spanning_edges
Notes
Examples
>>> G=nx.cycle_graph(4)
>>> G.add_edge(0,3,weight=2) # assign weight 2 to edge 0-3
>>> mst=nx.minimum_spanning_edges(G,data=False) # a generator of MST edges
>>> edgelist=list(mst) # make a list of the edges
>>> print(sorted(edgelist))
[(0, 1), (1, 2), (2, 3)]
4.30 Operators
4.30.1 complement
complement(G, name=None)
Return the graph complement of G.
Parameters G : graph
A NetworkX graph
name : string
Specify name for new graph
Returns GC : A new graph.
Notes
Note that complement() does not create self-loops and also does not produce parallel edges for MultiGraphs.
Graph, node, and edge data are not propagated to the new graph.
4.30.2 reverse
reverse(G, copy=True)
Return the reverse directed graph of G.
Parameters G : directed graph
A NetworkX directed graph
copy : bool
If True, then a new graph is returned. If False, then the graph is reversed in place.
Returns H : directed graph
The reversed G.
Operations on graphs including union, intersection, difference.
4.30.3 compose
compose(G, H, name=None)
Return a new graph of G composed with H.
Composition is the simple union of the node sets and edge sets. The node sets of G and H need not be disjoint.
Parameters G,H : graph
A NetworkX graph
name : string
Specify name for new graph
Returns C: A new graph with the same type as G
Notes
It is recommended that G and H be either both directed or both undirected. Attributes from H take precedent
over attributes from G.
4.30.4 union
Notes
To force a disjoint union with node relabeling, use disjoint_union(G,H) or convert_node_labels_to integers().
Graph, edge, and node attributes are propagated from G and H to the union graph. If a graph attribute is present
in both G and H the value from H is used.
4.30.5 disjoint_union
disjoint_union(G, H)
Return the disjoint union of graphs G and H.
This algorithm forces distinct integer node labels.
Parameters G,H : graph
A NetworkX graph
Returns U : A union graph with the same type as G.
Notes
A new graph is created, of the same class as G. It is recommended that G and H be either both directed or both
undirected.
The nodes of G are relabeled 0 to len(G)-1, and the nodes of H are relabeled len(G) to len(G)+len(H)-1.
Graph, edge, and node attributes are propagated from G and H to the union graph. If a graph attribute is present
in both G and H the value from H is used.
4.30.6 intersection
intersection(G, H)
Return a new graph that contains only the edges that exist in both G and H.
The node sets of H and G must be the same.
Parameters G,H : graph
A NetworkX graph. G and H must have the same node sets.
Notes
Attributes from the graph, nodes, and edges are not copied to the new graph. If you want a new graph of the
intersection of G and H with the attributes (including edge data) from G use remove_nodes_from() as follows
>>> G=nx.path_graph(3)
>>> H=nx.path_graph(5)
>>> R=G.copy()
>>> R.remove_nodes_from(n for n in G if n not in H)
4.30.7 difference
difference(G, H)
Return a new graph that contains the edges that exist in G but not in H.
The node sets of H and G must be the same.
Parameters G,H : graph
A NetworkX graph. G and H must have the same node sets.
Returns D : A new graph with the same type as G.
Notes
Attributes from the graph, nodes, and edges are not copied to the new graph. If you want a new graph of
the difference of G and H with with the attributes (including edge data) from G use remove_nodes_from() as
follows:
>>> G = nx.path_graph(3)
>>> H = nx.path_graph(5)
>>> R = G.copy()
>>> R.remove_nodes_from(n for n in G if n in H)
4.30.8 symmetric_difference
symmetric_difference(G, H)
Return new graph with edges that exist in either G or H but not both.
The node sets of H and G must be the same.
Parameters G,H : graph
A NetworkX graph. G and H must have the same node sets.
Returns D : A new graph with the same type as G.
Notes
Attributes from the graph, nodes, and edges are not copied to the new graph.
Operations on many graphs.
4.30.9 compose_all
compose_all(graphs, name=None)
Return the composition of all graphs.
Composition is the simple union of the node sets and edge sets. The node sets of the supplied graphs need not
be disjoint.
Parameters graphs : list
List of NetworkX graphs
name : string
Specify name for new graph
Returns C : A graph with the same type as the first graph in list
Notes
It is recommended that the supplied graphs be either all directed or all undirected.
Graph, edge, and node attributes are propagated to the union graph. If a graph attribute is present in multiple
graphs, then the value from the last graph in the list with that attribute is used.
4.30.10 union_all
Notes
To force a disjoint union with node relabeling, use disjoint_union_all(G,H) or convert_node_labels_to integers().
Graph, edge, and node attributes are propagated to the union graph. If a graph attribute is present in multiple
graphs, then the value from the last graph in the list with that attribute is used.
4.30.11 disjoint_union_all
disjoint_union_all(graphs)
Return the disjoint union of all graphs.
This operation forces distinct integer node labels starting with 0 for the first graph in the list and numbering
consecutively.
Parameters graphs : list
List of NetworkX graphs
Returns U : A graph with the same type as the first graph in list
Notes
4.30.12 intersection_all
intersection_all(graphs)
Return a new graph that contains only the edges that exist in all graphs.
All supplied graphs must have the same node set.
Parameters graphs_list : list
List of NetworkX graphs
Returns R : A new graph with the same type as the first graph in list
Notes
Attributes from the graph, nodes, and edges are not copied to the new graph.
Graph products.
4.30.13 cartesian_product
cartesian_product(G, H)
Return the Cartesian product of G and H.
The tensor product P of the graphs G and H has a node set that is the Cartesian product of the node sets,
$V(P)=V(G) imes V(H)$. P has an edge ((u,v),(x,y)) if and only if (u,v) is an edge in G and x==y or and (x,y)
is an edge in H and u==v. and (x,y) is an edge in H.
Parameters G, H: graphs
Networkx graphs.
Returns P: NetworkX graph
The Cartesian product of G and H. P will be a multi-graph if either G or H is a multi-
graph. Will be a directed if G and H are directed, and undirected if G and H are undi-
rected.
Raises NetworkXError
If G and H are not both directed or both undirected.
Notes
Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None.
For example >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0,a1=True) >>>
H.add_node(‘a’,a2=’Spam’) >>> P = nx.cartesian_product(G,H) >>> P.nodes() [(0, ‘a’)]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
4.30.14 lexicographic_product
lexicographic_product(G, H)
Return the lexicographic product of G and H.
The lexicographical product P of the graphs G and H has a node set that is the Cartesian product of the node
sets, $V(P)=V(G) imes V(H)$. P has an edge ((u,v),(x,y)) if and only if (u,v) is an edge in G or u==v and (x,y)
is an edge in H.
Parameters G, H: graphs
Networkx graphs.
Returns P: NetworkX graph
The Cartesian product of G and H. P will be a multi-graph if either G or H is a multi-
graph. Will be a directed if G and H are directed, and undirected if G and H are undi-
rected.
Raises NetworkXError
If G and H are not both directed or both undirected.
Notes
Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None.
4.30.15 strong_product
strong_product(G, H)
Return the strong product of G and H.
The strong product P of the graphs G and H has a node set that is the Cartesian product of the node sets,
$V(P)=V(G) imes V(H)$. P has an edge ((u,v),(x,y)) if and only if u==v and (x,y) is an edge in H, or x==y and
(u,v) is an edge in G, or (u,v) is an edge in G and (x,y) is an edge in H.
Parameters G, H: graphs
Networkx graphs.
Returns P: NetworkX graph
The Cartesian product of G and H. P will be a multi-graph if either G or H is a multi-
graph. Will be a directed if G and H are directed, and undirected if G and H are undi-
rected.
Raises NetworkXError
If G and H are not both directed or both undirected.
Notes
Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None.
For example >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0,a1=True) >>>
H.add_node(‘a’,a2=’Spam’) >>> P = nx.strong_product(G,H) >>> P.nodes() [(0, ‘a’)]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
4.30.16 tensor_product
tensor_product(G, H)
Return the tensor product of G and H.
The tensor product P of the graphs G and H has a node set that is the Cartesian product of the node sets,
$V(P)=V(G) times V(H)$. P has an edge ((u,v),(x,y)) if and only if (u,v) is an edge in G and (x,y) is an edge in
H.
Sometimes referred to as the categorical product.
Parameters G, H: graphs
Networkx graphs.
Returns P: NetworkX graph
The tensor product of G and H. P will be a multi-graph if either G or H is a multi-graph.
Will be a directed if G and H are directed, and undirected if G and H are undirected.
Raises NetworkXError
If G and H are not both directed or both undirected.
Notes
Node attributes in P are two-tuple of the G and H node attributes. Missing attributes are assigned None.
For example >>> G = nx.Graph() >>> H = nx.Graph() >>> G.add_node(0,a1=True) >>>
H.add_node(‘a’,a2=’Spam’) >>> P = nx.tensor_product(G,H) >>> P.nodes() [(0, ‘a’)]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
4.31.1 rich_club_coefficient
2𝐸𝑘
𝜑(𝑘) =
𝑁 𝑘(𝑁 𝑘 − 1)
where Nk is the number of nodes with degree larger than k, and Ek be the number of edges among those nodes.
Parameters G : NetworkX graph
normalized : bool (optional)
Normalize using randomized network (see [R275])
Q : float (optional, default=100)
If normalized=True build a random network by performing Q*M double-edge swaps,
where M is the number of edges in G, to use as a null-model for normalization.
Returns rc : dictionary
A dictionary, keyed by degree, with rich club coefficient values.
Notes
The rich club definition and algorithm are found in [R275]. This algorithm ignores any edge weights and is not
defined for directed graphs or graphs with parallel edges or self loops.
Estimates for appropriate values of Q are found in [R276].
References
[R275], [R276]
Examples
>>> G = nx.Graph([(0,1),(0,2),(1,2),(1,3),(1,4),(4,5)])
>>> rc = nx.rich_club_coefficient(G,normalized=False)
>>> rc[0]
0.4
Compute the shortest paths and path lengths between nodes in the graph.
These algorithms work with undirected and directed graphs.
4.32.1 shortest_path
See also:
all_pairs_shortest_path, all_pairs_dijkstra_path, single_source_shortest_path,
single_source_dijkstra_path
Notes
There may be more than one shortest path between a source and target. This returns only one of them.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.shortest_path(G,source=0,target=4))
[0, 1, 2, 3, 4]
>>> p=nx.shortest_path(G,source=0) # target not specified
>>> p[4]
[0, 1, 2, 3, 4]
>>> p=nx.shortest_path(G,target=4) # source not specified
>>> p[0]
[0, 1, 2, 3, 4]
>>> p=nx.shortest_path(G) # source,target not specified
>>> p[0][4]
[0, 1, 2, 3, 4]
4.32.2 all_shortest_paths
Notes
There may be many shortest paths between the source and target.
Examples
>>> G=nx.Graph()
>>> G.add_path([0,1,2])
>>> G.add_path([0,10,2])
>>> print([p for p in nx.all_shortest_paths(G,source=0,target=2)])
[[0, 1, 2], [0, 10, 2]]
4.32.3 shortest_path_length
Notes
The length of the path is always 1 less than the number of nodes involved in the path since the length measures
the number of edges followed.
For digraphs this returns the shortest directed path length. To find path lengths in the reverse direction use
G.reverse(copy=False) first to flip the edge orientation.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.shortest_path_length(G,source=0,target=4))
4
>>> p=nx.shortest_path_length(G,source=0) # target not specified
>>> p[4]
4
>>> p=nx.shortest_path_length(G,target=4) # source not specified
>>> p[0]
4
>>> p=nx.shortest_path_length(G) # source,target not specified
>>> p[0][4]
4
4.32.4 average_shortest_path_length
average_shortest_path_length(G, weight=None)
Return the average shortest path length.
The average shortest path length is
∑︁ 𝑑(𝑠, 𝑡)
𝑎=
𝑛(𝑛 − 1)
𝑠,𝑡∈𝑉
where 𝑉 is the set of nodes in 𝐺, 𝑑(𝑠, 𝑡) is the shortest path from 𝑠 to 𝑡, and 𝑛 is the number of nodes in 𝐺.
Parameters G : NetworkX graph
weight : None or string, optional (default = None)
If None, every edge has weight/distance/cost 1. If a string, use this edge attribute as the
edge weight. Any edge attribute not present defaults to 1.
Raises NetworkXError:
if the graph is not connected.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.average_shortest_path_length(G))
2.0
For disconnected graphs you can compute the average shortest path length for each compo-
nent: >>> G=nx.Graph([(1,2),(3,4)]) >>> for g in nx.connected_component_subgraphs(G): ...
print(nx.average_shortest_path_length(g)) 1.0 1.0
4.32.5 has_path
single_source_shortest_path(G, source[, cutoff]) Compute shortest path between source and all other nodes reachable
single_source_shortest_path_length(G, source) Compute the shortest path lengths from source to all reachable nodes
all_pairs_shortest_path(G[, cutoff]) Compute shortest paths between all nodes.
all_pairs_shortest_path_length(G[, cutoff]) Compute the shortest path lengths between all nodes in G.
predecessor(G, source[, target, cutoff, ...]) Returns dictionary of predecessors for the path from source to all nod
single_source_shortest_path
Notes
The shortest path is not necessarily unique. So there can be multiple paths between the source and each target
node, all of which have the same ‘shortest’ length. For each target node, this function returns only one of those
paths.
Examples
>>> G=nx.path_graph(5)
>>> path=nx.single_source_shortest_path(G,0)
>>> path[4]
[0, 1, 2, 3, 4]
single_source_shortest_path_length
Examples
>>> G=nx.path_graph(5)
>>> length=nx.single_source_shortest_path_length(G,0)
>>> length[4]
4
>>> print(length)
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
all_pairs_shortest_path
all_pairs_shortest_path(G, cutoff=None)
Compute shortest paths between all nodes.
Parameters G : NetworkX graph
cutoff : integer, optional
Depth to stop the search. Only paths of length <= cutoff are returned.
Returns lengths : dictionary
Dictionary, keyed by source and target, of shortest paths.
See also:
floyd_warshall
Examples
>>> G=nx.path_graph(5)
>>> path=nx.all_pairs_shortest_path(G)
>>> print(path[0][4])
[0, 1, 2, 3, 4]
all_pairs_shortest_path_length
all_pairs_shortest_path_length(G, cutoff=None)
Compute the shortest path lengths between all nodes in G.
Parameters G : NetworkX graph
cutoff : integer, optional
depth to stop the search. Only paths of length <= cutoff are returned.
Returns lengths : dictionary
Dictionary of shortest path lengths keyed by source and target.
Notes
The dictionary returned only has keys for reachable node pairs.
Examples
>>> G=nx.path_graph(5)
>>> length=nx.all_pairs_shortest_path_length(G)
>>> print(length[1][4])
3
>>> length[1]
{0: 1, 1: 0, 2: 1, 3: 2, 4: 3}
predecessor
Examples
>>> G=nx.path_graph(4)
>>> print(G.nodes())
[0, 1, 2, 3]
>>> nx.predecessor(G,0)
{0: [], 1: [0], 2: [1], 3: [2]}
dijkstra_path(G, source, target[, weight]) Returns the shortest path from source to target in a weighted graph G
dijkstra_path_length(G, source, target[, weight]) Returns the shortest path length from source to target in a weighted g
single_source_dijkstra_path(G, source[, ...]) Compute shortest path between source and all other reachable nodes
single_source_dijkstra_path_length(G, source) Compute the shortest path length between source and all other reacha
all_pairs_dijkstra_path(G[, cutoff, weight]) Compute shortest paths between all nodes in a weighted graph.
all_pairs_dijkstra_path_length(G[, cutoff, ...]) Compute shortest path lengths between all nodes in a weighted graph
single_source_dijkstra(G, source[, target, ...]) Compute shortest paths and lengths in a weighted graph G.
bidirectional_dijkstra(G, source, target[, ...]) Dijkstra’s algorithm for shortest paths using bidirectional search.
dijkstra_predecessor_and_distance(G, source) Compute shortest path length and predecessors on shortest paths in w
bellman_ford(G, source[, weight]) Compute shortest path lengths and predecessors on shortest paths in w
negative_edge_cycle(G[, weight]) Return True if there exists a negative edge cycle anywhere in G.
dijkstra_path
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.dijkstra_path(G,0,4))
[0, 1, 2, 3, 4]
dijkstra_path_length
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.dijkstra_path_length(G,0,4))
4
single_source_dijkstra_path
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Examples
>>> G=nx.path_graph(5)
>>> path=nx.single_source_dijkstra_path(G,0)
>>> path[4]
[0, 1, 2, 3, 4]
single_source_dijkstra_path_length
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Examples
>>> G=nx.path_graph(5)
>>> length=nx.single_source_dijkstra_path_length(G,0)
>>> length[4]
4
>>> print(length)
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
all_pairs_dijkstra_path
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Examples
>>> G=nx.path_graph(5)
>>> path=nx.all_pairs_dijkstra_path(G)
>>> print(path[0][4])
[0, 1, 2, 3, 4]
all_pairs_dijkstra_path_length
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The dictionary returned only has keys for reachable node pairs.
Examples
>>> G=nx.path_graph(5)
>>> length=nx.all_pairs_dijkstra_path_length(G)
>>> print(length[1][4])
3
>>> length[1]
{0: 1, 1: 0, 2: 1, 3: 2, 4: 3}
single_source_dijkstra
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
Based on the Python cookbook recipe (119466) at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466
This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows
and roundoff errors can cause problems).
Examples
>>> G=nx.path_graph(5)
>>> length,path=nx.single_source_dijkstra(G,0)
>>> print(length[4])
4
>>> print(length)
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
>>> path[4]
[0, 1, 2, 3, 4]
bidirectional_dijkstra
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
In practice bidirectional Dijkstra is much more than twice as fast as ordinary Dijkstra.
Ordinary Dijkstra expands nodes in a sphere-like manner from the source. The radius of this sphere will even-
tually be the length of the shortest path. Bidirectional Dijkstra will expand nodes from both the source and
the target, making two spheres of half this radius. Volume of the first sphere is pi*r*r while the others are
2*pi*r/2*r/2, making up half the volume.
This algorithm is not guaranteed to work if edge weights are negative or are floating point numbers (overflows
and roundoff errors can cause problems).
Examples
>>> G=nx.path_graph(5)
>>> length,path=nx.bidirectional_dijkstra(G,0,4)
>>> print(length)
4
>>> print(path)
[0, 1, 2, 3, 4]
dijkstra_predecessor_and_distance
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The list of predecessors contains more than one element only when there are more than one shortest paths to the
key node.
bellman_ford
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The dictionaries returned only have keys for nodes reachable from the source.
In the case where the (di)graph is not connected, if a component not containing the source contains a negative
cost (di)cycle, it will not be detected.
Examples
negative_edge_cycle
negative_edge_cycle(G, weight=’weight’)
Return True if there exists a negative edge cycle anywhere in G.
Parameters G : NetworkX graph
weight: string, optional (default=’weight’)
Edge data key corresponding to the edge weight
Returns negative_cycle : bool
True if a negative edge cycle exists, otherwise False.
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
This algorithm uses bellman_ford() but finds negative cycles on any component by first adding a new node
connected to every node, and starting bellman_ford on that node. It then removes that extra node.
Examples
floyd_warshall(G[, weight]) Find all-pairs shortest path lengths using Floyd’s algorithm.
floyd_warshall_predecessor_and_distance(G[, ...]) Find all-pairs shortest path lengths using Floyd’s algorithm.
floyd_warshall_numpy(G[, nodelist, weight]) Find all-pairs shortest path lengths using Floyd’s algorithm.
floyd_warshall
floyd_warshall(G, weight=’weight’)
Find all-pairs shortest path lengths using Floyd’s algorithm.
Parameters G : NetworkX graph
weight: string, optional (default= ‘weight’)
Edge data key corresponding to the edge weight.
Returns distance : dict
A dictionary, keyed by source and target, of shortest paths distances between nodes.
See also:
floyd_warshall_predecessor_and_distance, floyd_warshall_numpy,
all_pairs_shortest_path, all_pairs_shortest_path_length
Notes
Floyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when
Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time O(n^3)
with running space of O(n^2).
floyd_warshall_predecessor_and_distance
floyd_warshall_predecessor_and_distance(G, weight=’weight’)
Find all-pairs shortest path lengths using Floyd’s algorithm.
Parameters G : NetworkX graph
weight: string, optional (default= ‘weight’)
Edge data key corresponding to the edge weight.
Returns predecessor,distance : dictionaries
Dictionaries, keyed by source and target, of predecessors and distances in the shortest
path.
See also:
floyd_warshall, floyd_warshall_numpy, all_pairs_shortest_path,
all_pairs_shortest_path_length
Notes
Floyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when
Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time O(n^3)
with running space of O(n^2).
floyd_warshall_numpy
Notes
Floyd’s algorithm is appropriate for finding shortest paths in dense graphs or graphs with negative weights when
Dijkstra’s algorithm fails. This algorithm can still fail if there are negative cycles. It has running time O(n^3)
with running space of O(n^2).
4.32.8 A* Algorithm
astar_path(G, source, target[, heuristic, ...]) Return a list of nodes in a shortest path between source and target using the A* (“A
astar_path_length(G, source, target[, ...]) Return the length of the shortest path between source and target using the A* (“A-s
astar_path
Examples
>>> G=nx.path_graph(5)
>>> print(nx.astar_path(G,0,4))
[0, 1, 2, 3, 4]
>>> G=nx.grid_graph(dim=[3,3]) # nodes are two-tuples (x,y)
>>> def dist(a, b):
... (x1, y1) = a
... (x2, y2) = b
... return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
>>> print(nx.astar_path(G,(0,0),(2,2),dist))
[(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)]
astar_path_length
See also:
astar_path
all_simple_paths(G, source, target[, cutoff]) Generate all simple paths in the graph G from source to target.
4.33.1 all_simple_paths
Notes
This algorithm uses a modified depth-first search to generate the paths [R277]. A single path can be found in
𝑂(𝑉 + 𝐸) time but the number of simple paths in a graph can be very large, e.g. 𝑂(𝑛!) in the complete graph
of order n.
References
[R277]
Examples
>>> G = nx.complete_graph(4)
>>> for path in nx.all_simple_paths(G, source=0, target=3):
... print(path)
...
[0, 1, 2, 3]
[0, 1, 3]
[0, 2, 1, 3]
[0, 2, 3]
[0, 3]
>>> paths = nx.all_simple_paths(G, source=0, target=3, cutoff=2)
>>> print(list(paths))
[[0, 1, 3], [0, 2, 3], [0, 3]]
4.34 Swap
double_edge_swap(G[, nswap, max_tries]) Swap two edges in the graph while keeping the node degrees fixed.
connected_double_edge_swap(G[, nswap]) Attempt nswap double-edge swaps in the graph G.
4.34.1 double_edge_swap
If either the edge u-x or v-y already exist no swap is performed and another attempt is made to find a suitable
edge pair.
Parameters G : graph
An undirected graph
nswap : integer (optional, default=1)
Number of double-edge swaps to perform
max_tries : integer (optional)
Maximum number of attempts to swap edges
Returns G : graph
The graph after double edge swaps.
Notes
4.34.2 connected_double_edge_swap
connected_double_edge_swap(G, nswap=1)
Attempt nswap double-edge swaps in the graph G.
A double-edge swap removes two randomly chosen edges u-v and x-y and creates the new edges u-x and v-y:
u--v u v
becomes | |
x--y x y
If either the edge u-x or v-y already exist no swap is performed so the actual count of swapped edges is always
<= nswap
Parameters G : graph
An undirected graph
nswap : integer (optional, default=1)
Number of double-edge swaps to perform
Returns G : int
The number of successful swaps
Notes
The initial graph G must be connected, and the resulting graph is connected. The graph G is modified in place.
References
[R278]
4.35 Traversal
dfs_edges
dfs_edges(G, source=None)
Produce edges in a depth-first-search (DFS).
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.dfs_edges(G,0)))
[(0, 1), (1, 2)]
dfs_tree
dfs_tree(G, source)
Return oriented tree constructed from a depth-first-search from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search.
Returns T : NetworkX DiGraph
An oriented tree
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> T = nx.dfs_tree(G,0)
>>> print(T.edges())
[(0, 1), (1, 2)]
dfs_predecessors
dfs_predecessors(G, source=None)
Return dictionary of predecessors in depth-first-search from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search and return edges in the component reachable
from source.
Returns pred: dict
A dictionary with nodes as keys and predecessor nodes as values.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(nx.dfs_predecessors(G,0))
{1: 0, 2: 1}
dfs_successors
dfs_successors(G, source=None)
Return dictionary of successors in depth-first-search from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search and return edges in the component reachable
from source.
Returns succ: dict
A dictionary with nodes as keys and list of successor nodes as values.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(nx.dfs_successors(G,0))
{0: [1], 1: [2]}
dfs_preorder_nodes
dfs_preorder_nodes(G, source=None)
Produce nodes in a depth-first-search pre-ordering starting from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search and return edges in the component reachable
from source.
Returns nodes: generator
A generator of nodes in a depth-first-search pre-ordering.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.dfs_preorder_nodes(G,0)))
[0, 1, 2]
dfs_postorder_nodes
dfs_postorder_nodes(G, source=None)
Produce nodes in a depth-first-search post-ordering starting from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search and return edges in the component reachable
from source.
Returns nodes: generator
A generator of nodes in a depth-first-search post-ordering.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.dfs_postorder_nodes(G,0)))
[2, 1, 0]
dfs_labeled_edges
dfs_labeled_edges(G, source=None)
Produce edges in a depth-first-search (DFS) labeled by type.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for depth-first search and return edges in the component reachable
from source.
Returns edges: generator
A generator of edges in the depth-first-search labeled with ‘forward’, ‘nontree’, and
‘reverse’.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> edges = (list(nx.dfs_labeled_edges(G,0)))
bfs_edges
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.bfs_edges(G,0)))
[(0, 1), (1, 2)]
bfs_tree
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(list(nx.bfs_edges(G,0)))
[(0, 1), (1, 2)]
bfs_predecessors
bfs_predecessors(G, source)
Return dictionary of predecessors in breadth-first-search from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for breadth-first search and return edges in the component reach-
able from source.
Returns pred: dict
A dictionary with nodes as keys and predecessor nodes as values.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(nx.bfs_predecessors(G,0))
{1: 0, 2: 1}
bfs_successors
bfs_successors(G, source)
Return dictionary of successors in breadth-first-search from source.
Parameters G : NetworkX graph
source : node, optional
Specify starting node for breadth-first search and return edges in the component reach-
able from source.
Returns succ: dict
A dictionary with nodes as keys and list of succssors nodes as values.
Notes
Examples
>>> G = nx.Graph()
>>> G.add_path([0,1,2])
>>> print(nx.bfs_successors(G,0))
{0: [1], 1: [2]}
4.36 Tree
4.36.1 Recognition
Recognition Tests
A forest is an acyclic, undirected graph, and a tree is a connected forest. Depending on the subfield, there are various
conventions for generalizing these definitions to directed graphs.
In one convention, directed variants of forest and tree are defined in an identical manner, except that the direction of
the edges is ignored. In effect, each directed edge is treated as a single undirected edge. Then, additional restrictions
are imposed to define branchings and arborescences.
In another convention, directed variants of forest and tree correspond to the previous convention’s branchings and
arborescences, respectively. Then two new terms, polyforest and polytree, are defined to correspond to the other
convention’s forest and tree.
Summarizing:
+-----------------------------+
| Convention 1 | Convention 2 |
+=============================+
| forest | polyforest |
| tree | polytree |
| branching | forest |
| arborescence | tree |
+-----------------------------+
Each convention has its reasons. The first convention emphasizes definitional similarity in that directed forests and
trees are only concerned with acyclicity and do not have an in-degree constraint, just as their undirected counterparts do
not. The second convention emphasizes functional similarity in the sense that the directed analog of a spanning tree is
a spanning arborescence. That is, take any spanning tree and choose one node as the root. Then every edge is assigned
a direction such there is a directed path from the root to every other node. The result is a spanning arborescence.
NetworkX follows the first convention. Explicitly, these are:
undirected forest An undirected graph with no undirected cycles.
undirected tree A connected, undirected forest.
directed forest A directed graph with no undirected cycles. Equivalently, the underlying graph structure (which
ignores edge orientations) is an undirected forest. In another convention, this is known as a polyforest.
directed tree A weakly connected, directed forest. Equivalently, the underlying graph structure (which ignores edge
orientations) is an undirected tree. In another convention, this is known as a polytree.
branching A directed forest with each node having, at most, one parent. So the maximum in-degree is equal to 1. In
another convention, this is known as a forest.
arborescence A directed tree with each node having, at most, one parent. So the maximum in-degree is equal to 1.
In another convention, this is known as a tree.
is_tree
is_tree(G)
Returns 𝑇 𝑟𝑢𝑒 if 𝐺 is a tree.
A tree is a connected graph with no undirected cycles.
For directed graphs, 𝐺 is a tree if the underlying graph is a tree. The underlying graph is obtained by treating
each directed edge as a single undirected edge in a multigraph.
Parameters G : graph
The graph to test.
Returns b : bool
A boolean that is 𝑇 𝑟𝑢𝑒 if 𝐺 is a tree.
See also:
is_arborescence
Notes
In another convention, a directed tree is known as a polytree and then tree corresponds to an arborescence.
is_forest
is_forest(G)
Returns 𝑇 𝑟𝑢𝑒 if G is a forest.
A forest is a graph with no undirected cycles.
For directed graphs, 𝐺 is a forest if the underlying graph is a forest. The underlying graph is obtained by treating
each directed edge as a single undirected edge in a multigraph.
Parameters G : graph
The graph to test.
Returns b : bool
A boolean that is 𝑇 𝑟𝑢𝑒 if 𝐺 is a forest.
See also:
is_branching
Notes
In another convention, a directed forest is known as a polyforest and then forest corresponds to a branching.
4.37 Vitality
Vitality measures.
4.37.1 closeness_vitality
closeness_vitality(G, weight=None)
Compute closeness vitality for nodes.
Closeness vitality of a node is the change in the sum of distances between all node pairs when excluding that
node.
Parameters G : graph
weight : None or string (optional)
The name of the edge attribute used as weight. If None the edge weights are ignored.
Returns nodes : dictionary
Dictionary with nodes as keys and closeness vitality as the value.
See also:
closeness_centrality
References
[R279]
Examples
>>> G=nx.cycle_graph(3)
>>> nx.closeness_vitality(G)
{0: 4.0, 1: 4.0, 2: 4.0}
FIVE
FUNCTIONS
5.1 Graph
5.1.1 degree
5.1.2 degree_histogram
degree_histogram(G)
Return a list of the frequency of each degree value.
Parameters G : Networkx graph
A graph
Returns hist : list
A list of frequencies of degrees. The degree values are the index in the list.
Notes
Note: the bins are width one, hence len(list) can be large (Order(number_of_edges))
5.1.3 density
density(G)
Return the density of a graph.
339
NetworkX Reference, Release 1.9.1
Notes
The density is 0 for a graph without edges and 1 for a complete graph. The density of multigraphs can be higher
than 1.
Self loops are counted in the total number of edges so graphs with self loops can have density higher than 1.
5.1.4 info
info(G, n=None)
Print short summary of information for the graph G or the node n.
Parameters G : Networkx graph
A graph
n : node (any hashable)
A node in the graph G
5.1.5 create_empty_copy
create_empty_copy(G, with_nodes=True)
Return a copy of the graph G with all of the edges removed.
Parameters G : graph
A NetworkX graph
with_nodes : bool (default=True)
Include nodes.
Notes
Graph, node, and edge data is not propagated to the new graph.
5.1.6 is_directed
is_directed(G)
Return True if graph is directed.
5.2 Nodes
5.2.1 nodes
nodes(G)
Return a copy of the graph nodes in a list.
5.2.2 number_of_nodes
number_of_nodes(G)
Return the number of nodes in the graph.
5.2.3 nodes_iter
nodes_iter(G)
Return an iterator over the graph nodes.
5.2.4 all_neighbors
all_neighbors(graph, node)
Returns all of the neighbors of a node in the graph.
If the graph is directed returns predecessors as well as successors.
Parameters graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
Returns neighbors : iterator
Iterator of neighbors
5.2.5 non_neighbors
non_neighbors(graph, node)
Returns the non-neighbors of the node in the graph.
Parameters graph : NetworkX graph
Graph to find neighbors.
node : node
The node whose neighbors will be returned.
5.2.6 common_neighbors
common_neighbors(G, u, v)
Return the common neighbors of two nodes in a graph.
Parameters G : graph
A NetworkX undirected graph.
u, v : nodes
Nodes in the graph.
Returns cnbors : iterator
Iterator of common neighbors of u and v in the graph.
Raises NetworkXError
If u or v is not a node in the graph.
Examples
>>> G = nx.complete_graph(5)
>>> sorted(nx.common_neighbors(G, 0, 1))
[2, 3, 4]
5.3 Edges
5.3.1 edges
edges(G, nbunch=None)
Return list of edges adjacent to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
5.3.2 number_of_edges
number_of_edges(G)
Return the number of edges in the graph.
5.3.3 edges_iter
edges_iter(G, nbunch=None)
Return iterator over edges adjacent to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
5.3.4 non_edges
non_edges(graph)
Returns the non-existent edges in the graph.
Parameters graph : NetworkX graph.
Graph to find non-existent edges.
Returns non_edges : iterator
Iterator of edges that are not in the graph.
5.4 Attributes
set_node_attributes(G, name, values) Set node attributes from dictionary of nodes and values
get_node_attributes(G, name) Get node attributes from graph
set_edge_attributes(G, name, values) Set edge attributes from dictionary of edge tuples and values.
get_edge_attributes(G, name) Get edge attributes from graph
5.4.1 set_node_attributes
Examples
>>> G = nx.path_graph(3)
>>> bb = nx.betweenness_centrality(G)
>>> nx.set_node_attributes(G, 'betweenness', bb)
>>> G.node[1]['betweenness']
1.0
5.4.2 get_node_attributes
get_node_attributes(G, name)
Get node attributes from graph
Parameters G : NetworkX Graph
name : string
Attribute name
Returns Dictionary of attributes keyed by node.
Examples
>>> G=nx.Graph()
>>> G.add_nodes_from([1,2,3],color='red')
>>> color=nx.get_node_attributes(G,'color')
>>> color[1]
'red'
5.4.3 set_edge_attributes
Examples
>>> G = nx.path_graph(3)
>>> bb = nx.edge_betweenness_centrality(G, normalized=False)
>>> nx.set_edge_attributes(G, 'betweenness', bb)
>>> G[1][2]['betweenness']
2.0
5.4.4 get_edge_attributes
get_edge_attributes(G, name)
Get edge attributes from graph
Parameters G : NetworkX Graph
name : string
Attribute name
Returns Dictionary of attributes keyed by edge. For (di)graphs, the keys are
2-tuples of the form: (u,v). For multi(di)graphs, the keys are 3-tuples of
the form: (u, v, key).
Examples
>>> G=nx.Graph()
>>> G.add_path([1,2,3],color='red')
>>> color=nx.get_edge_attributes(G,'color')
>>> color[(1,2)]
'red'
freeze(G) Modify graph to prevent further change by adding or removing nodes or edges.
is_frozen(G) Return True if graph is frozen.
5.5.1 freeze
freeze(G)
Modify graph to prevent further change by adding or removing nodes or edges.
Node and edge data can still be modified.
Parameters G : graph
A NetworkX graph
See also:
is_frozen
Notes
To “unfreeze” a graph you must make a copy by creating a new graph object:
>>> graph = nx.path_graph(4)
>>> frozen_graph = nx.freeze(graph)
>>> unfrozen_graph = nx.Graph(frozen_graph)
>>> nx.is_frozen(unfrozen_graph)
False
Examples
>>> G=nx.Graph()
>>> G.add_path([0,1,2,3])
>>> G=nx.freeze(G)
>>> try:
... G.add_edge(4,5)
5.5.2 is_frozen
is_frozen(G)
Return True if graph is frozen.
Parameters G : graph
A NetworkX graph
See also:
freeze
SIX
GRAPH GENERATORS
6.1 Atlas
graph_atlas_g() Return the list [G0,G1,...,G1252] of graphs as named in the Graph Atlas.
6.1.1 graph_atlas_g
graph_atlas_g()
Return the list [G0,G1,...,G1252] of graphs as named in the Graph Atlas. G0,G1,...,G1252 are all graphs with
up to 7 nodes.
The graphs are listed:
1. in increasing order of number of nodes;
2. for a fixed number of nodes, in increasing order of the number of edges;
3. for fixed numbers of nodes and edges, in increasing order of the degree sequence, for example 111223
< 112222;
4. for fixed degree sequence, in increasing number of automorphisms.
Note that indexing is set up so that for GAG=graph_atlas_g(), then G123=GAG[123] and G[0]=empty_graph(0)
6.2 Classic
returning the complete graph on n nodes labeled 0,..,99 as a simple graph. Except for empty_graph, all the generators
in this module return a Graph class (i.e. a simple, undirected graph).
349
NetworkX Reference, Release 1.9.1
6.2.1 balanced_tree
balanced_tree(r, h, create_using=None)
Return the perfectly balanced r-tree of height h.
Parameters r : int
Branching factor of the tree
h : int
Height of the tree
create_using : NetworkX graph type, optional
Use specified type to construct graph (default = networkx.Graph)
Returns G : networkx Graph
A tree with n nodes
Notes
This is the rooted tree where all leaves are at distance h from the root. The root has degree r and all other internal
nodes have degree r+1.
Node labels are the integers 0 (the root) up to number_of_nodes - 1.
Also refered to as a complete r-ary tree.
6.2.2 barbell_graph
The 2*m1+m2 nodes are numbered 0,...,m1-1 for the left barbell, m1,...,m1+m2-1 for the path, and
m1+m2,...,2*m1+m2-1 for the right barbell.
The 3 subgraphs are joined via the edges (m1-1,m1) and (m1+m2-1,m1+m2). If m2=0, this is merely two
complete graphs joined together.
This graph is an extremal example in David Aldous and Jim Fill’s etext on Random Walks on Graphs.
6.2.3 complete_graph
complete_graph(n, create_using=None)
Return the complete graph K_n with n nodes.
Node labels are the integers 0 to n-1.
6.2.4 complete_bipartite_graph
6.2.5 circular_ladder_graph
circular_ladder_graph(n, create_using=None)
Return the circular ladder graph CL_n of length n.
CL_n consists of two concentric n-cycles in which each of the n pairs of concentric nodes are joined by an edge.
Node labels are the integers 0 to n-1
6.2.6 cycle_graph
cycle_graph(n, create_using=None)
Return the cycle graph C_n over n nodes.
C_n is the n-path with two end-nodes connected.
Node labels are the integers 0 to n-1 If create_using is a DiGraph, the direction is in increasing order.
6.2.7 dorogovtsev_goltsev_mendes_graph
dorogovtsev_goltsev_mendes_graph(n, create_using=None)
Return the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
n is the generation. See: arXiv:/cond-mat/0112143 by Dorogovtsev, Goltsev and Mendes.
6.2.8 empty_graph
empty_graph(n=0, create_using=None)
Return the empty graph with n nodes and zero edges.
Node labels are the integers 0 to n-1
For example: >>> G=nx.empty_graph(10) >>> G.number_of_nodes() 10 >>> G.number_of_edges() 0
The variable create_using should point to a “graph”-like object that will be cleaned (nodes and edges will
be removed) and refitted as an empty “graph” with n nodes with integer labels. This capability is useful for
specifying the class-nature of the resulting empty “graph” (i.e. Graph, DiGraph, MyWeirdGraphClass, etc.).
The variable create_using has two main uses: Firstly, the variable create_using can be used to create an empty
digraph, network,etc. For example,
>>> n=10
>>> G=nx.empty_graph(n,create_using=nx.DiGraph())
6.2.9 grid_2d_graph
6.2.10 grid_graph
grid_graph(dim, periodic=False)
Return the n-dimensional grid graph.
The dimension is the length of the list ‘dim’ and the size in each dimension is the value of the list element.
E.g. G=grid_graph(dim=[2,3]) produces a 2x3 grid graph.
If periodic=True then join grid edges with periodic boundary conditions.
6.2.11 hypercube_graph
hypercube_graph(n)
Return the n-dimensional hypercube.
Node labels are the integers 0 to 2**n - 1.
6.2.12 ladder_graph
ladder_graph(n, create_using=None)
Return the Ladder graph of length n.
This is two rows of n nodes, with each pair connected by a single edge.
Node labels are the integers 0 to 2*n - 1.
6.2.13 lollipop_graph
lollipop_graph(m, n, create_using=None)
Return the Lollipop Graph; K_m connected to P_n.
This is the Barbell Graph without the right barbell.
For m>1 and n>=0, the complete graph K_m is connected to the path P_n. The resulting m+n nodes are labelled
0,...,m-1 for the complete graph and m,...,m+n-1 for the path. The 2 subgraphs are joined via the edge (m-1,m).
If n=0, this is merely a complete graph.
Node labels are the integers 0 to number_of_nodes - 1.
(This graph is an extremal example in David Aldous and Jim Fill’s etext on Random Walks on Graphs.)
6.2.14 null_graph
null_graph(create_using=None)
Return the Null graph with no nodes or edges.
See empty_graph for the use of create_using.
6.2.15 path_graph
path_graph(n, create_using=None)
Return the Path graph P_n of n nodes linearly connected by n-1 edges.
Node labels are the integers 0 to n - 1. If create_using is a DiGraph then the edges are directed in increasing
order.
6.2.16 star_graph
star_graph(n, create_using=None)
Return the Star graph with n+1 nodes: one center node, connected to n outer nodes.
Node labels are the integers 0 to n.
6.2.17 trivial_graph
trivial_graph(create_using=None)
Return the Trivial graph with one node (with integer label 0) and no edges.
6.2.18 wheel_graph
wheel_graph(n, create_using=None)
Return the wheel graph: a single hub node connected to each node of the (n-1)-node cycle graph.
Node labels are the integers 0 to n - 1.
6.3 Small
Various small and named graphs, together with some compact generators.
6.3.1 make_small_graph
make_small_graph(graph_description, create_using=None)
Return the small graph described by graph_description.
graph_description is a list of the form [ltype,name,n,xlist]
Here ltype is one of “adjacencylist” or “edgelist”, name is the name of the graph and n the number of nodes.
This constructs a graph of n nodes with integer labels 0,..,n-1.
If ltype=”adjacencylist” then xlist is an adjacency list with exactly n entries, in with the j’th entry (which can be
empty) specifies the nodes connected to vertex j. e.g. the “square” graph C_4 can be obtained by
>>> G=nx.make_small_graph(["adjacencylist","C_4",4,[[2,4],[1,3],[2,4],[1,3]]])
>>> G=nx.make_small_graph(["adjacencylist","C_4",4,[[2,4],[3],[4],[]]])
If ltype=”edgelist” then xlist is an edge list written as [[v1,w2],[v2,w2],...,[vk,wk]], where vj and wj integers in
the range 1,..,n e.g. the “square” graph C_4 can be obtained by
>>> G=nx.make_small_graph(["edgelist","C_4",4,[[1,2],[3,4],[2,3],[4,1]]])
6.3.2 LCF_graph
6.3.3 bull_graph
bull_graph(create_using=None)
Return the Bull graph.
6.3.4 chvatal_graph
chvatal_graph(create_using=None)
Return the Chvátal graph.
6.3.5 cubical_graph
cubical_graph(create_using=None)
Return the 3-regular Platonic Cubical graph.
6.3.6 desargues_graph
desargues_graph(create_using=None)
Return the Desargues graph.
6.3.7 diamond_graph
diamond_graph(create_using=None)
Return the Diamond graph.
6.3.8 dodecahedral_graph
dodecahedral_graph(create_using=None)
Return the Platonic Dodecahedral graph.
6.3.9 frucht_graph
frucht_graph(create_using=None)
Return the Frucht Graph.
The Frucht Graph is the smallest cubical graph whose automorphism group consists only of the identity element.
6.3.10 heawood_graph
heawood_graph(create_using=None)
Return the Heawood graph, a (3,6) cage.
6.3.11 house_graph
house_graph(create_using=None)
Return the House graph (square with triangle on top).
6.3.12 house_x_graph
house_x_graph(create_using=None)
Return the House graph with a cross inside the house square.
6.3.13 icosahedral_graph
icosahedral_graph(create_using=None)
Return the Platonic Icosahedral graph.
6.3.14 krackhardt_kite_graph
krackhardt_kite_graph(create_using=None)
Return the Krackhardt Kite Social Network.
A 10 actor social network introduced by David Krackhardt to illustrate: degree, betweenness, centrality, close-
ness, etc. The traditional labeling is: Andre=1, Beverley=2, Carol=3, Diane=4, Ed=5, Fernando=6, Garth=7,
Heather=8, Ike=9, Jane=10.
6.3.15 moebius_kantor_graph
moebius_kantor_graph(create_using=None)
Return the Moebius-Kantor graph.
6.3.16 octahedral_graph
octahedral_graph(create_using=None)
Return the Platonic Octahedral graph.
6.3.17 pappus_graph
pappus_graph()
Return the Pappus graph.
6.3.18 petersen_graph
petersen_graph(create_using=None)
Return the Petersen graph.
6.3.19 sedgewick_maze_graph
sedgewick_maze_graph(create_using=None)
Return a small maze with a cycle.
This is the maze used in Sedgewick,3rd Edition, Part 5, Graph Algorithms, Chapter 18, e.g. Figure 18.2 and
following. Nodes are numbered 0,..,7
6.3.20 tetrahedral_graph
tetrahedral_graph(create_using=None)
Return the 3-regular Platonic Tetrahedral graph.
6.3.21 truncated_cube_graph
truncated_cube_graph(create_using=None)
Return the skeleton of the truncated cube.
6.3.22 truncated_tetrahedron_graph
truncated_tetrahedron_graph(create_using=None)
Return the skeleton of the truncated Platonic tetrahedron.
6.3.23 tutte_graph
tutte_graph(create_using=None)
Return the Tutte graph.
fast_gnp_random_graph(n, p[, seed, directed]) Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).
gnp_random_graph(n, p[, seed, directed]) Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).
dense_gnm_random_graph(n, m[, seed]) Return the random graph G_{n,m}.
gnm_random_graph(n, m[, seed, directed]) Return the random graph G_{n,m}.
erdos_renyi_graph(n, p[, seed, directed]) Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).
binomial_graph(n, p[, seed, directed]) Return a random graph G_{n,p} (Erdős-Rényi graph, binomial graph).
newman_watts_strogatz_graph(n, k, p[, seed]) Return a Newman-Watts-Strogatz small world graph.
watts_strogatz_graph(n, k, p[, seed]) Return a Watts-Strogatz small-world graph.
connected_watts_strogatz_graph(n, k, p[, ...]) Return a connected Watts-Strogatz small-world graph.
random_regular_graph(d, n[, seed]) Return a random regular graph of n nodes each with degree d.
barabasi_albert_graph(n, m[, seed]) Return random graph using Barabási-Albert preferential attachment mo
powerlaw_cluster_graph(n, m, p[, seed]) Holme and Kim algorithm for growing graphs with powerlaw degree di
random_lobster(n, p1, p2[, seed]) Return a random lobster.
random_shell_graph(constructor[, seed]) Return a random shell graph for the constructor given.
random_powerlaw_tree(n[, gamma, seed, tries]) Return a tree with a powerlaw degree distribution.
random_powerlaw_tree_sequence(n[, gamma, ...]) Return a degree sequence for a tree with a powerlaw distribution.
6.4.1 fast_gnp_random_graph
Notes
The G_{n,p} graph algorithm chooses each of the [n(n-1)]/2 (undirected) or n(n-1) (directed) possible edges
with probability p.
This algorithm is O(n+m) where m is the expected number of edges m=p*n*(n-1)/2.
It should be faster than gnp_random_graph when p is small and the expected number of edges is small (sparse
graph).
References
[R312]
6.4.2 gnp_random_graph
Notes
This is an O(n^2) algorithm. For sparse graphs (small p) see fast_gnp_random_graph for a faster algorithm.
References
[R313], [R314]
6.4.3 dense_gnm_random_graph
dense_gnm_random_graph(n, m, seed=None)
Return the random graph G_{n,m}.
Gives a graph picked randomly out of the set of all graphs with n nodes and m edges. This algorithm should be
faster than gnm_random_graph for dense graphs.
Parameters n : int
The number of nodes.
m : int
The number of edges.
seed : int, optional
Seed for random number generator (default=None).
See also:
gnm_random_graph
Notes
Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth’s Algorithm S (Selection sampling technique),
in section 3.4.2 of [R309].
References
[R309]
6.4.4 gnm_random_graph
6.4.5 erdos_renyi_graph
Notes
This is an O(n^2) algorithm. For sparse graphs (small p) see fast_gnp_random_graph for a faster algorithm.
References
[R310], [R311]
6.4.6 binomial_graph
See also:
fast_gnp_random_graph
Notes
This is an O(n^2) algorithm. For sparse graphs (small p) see fast_gnp_random_graph for a faster algorithm.
References
[R307], [R308]
6.4.7 newman_watts_strogatz_graph
newman_watts_strogatz_graph(n, k, p, seed=None)
Return a Newman-Watts-Strogatz small world graph.
Parameters n : int
The number of nodes
k : int
Each node is connected to k nearest neighbors in ring topology
p : float
The probability of adding a new edge for each edge
seed : int, optional
seed for random number generator (default=None)
See also:
watts_strogatz_graph
Notes
First create a ring over n nodes. Then each node in the ring is connected with its k nearest neighbors (k-1
neighbors if k is odd). Then shortcuts are created by adding new edges as follows: for each edge u-v in the
underlying “n-ring with k nearest neighbors” with probability p add a new edge u-w with randomly-chosen
existing node w. In contrast with watts_strogatz_graph(), no edges are removed.
References
[R315]
6.4.8 watts_strogatz_graph
watts_strogatz_graph(n, k, p, seed=None)
Return a Watts-Strogatz small-world graph.
Parameters n : int
Notes
First create a ring over n nodes. Then each node in the ring is connected with its k nearest neighbors (k-1
neighbors if k is odd). Then shortcuts are created by replacing some edges as follows: for each edge u-v in the
underlying “n-ring with k nearest neighbors” with probability p replace it with a new edge u-w with uniformly
random choice of existing node w.
In contrast with newman_watts_strogatz_graph(), the random rewiring does not increase the number of edges.
The rewired graph is not guaranteed to be connected as in connected_watts_strogatz_graph().
References
[R319]
6.4.9 connected_watts_strogatz_graph
See also:
newman_watts_strogatz_graph, watts_strogatz_graph
6.4.10 random_regular_graph
random_regular_graph(d, n, seed=None)
Return a random regular graph of n nodes each with degree d.
The resulting graph G has no self-loops or parallel edges.
Parameters d : int
Degree
n : integer
Number of nodes. The value of n*d must be even.
seed : hashable object
The seed for random number generator.
Notes
References
[R317], [R318]
6.4.11 barabasi_albert_graph
barabasi_albert_graph(n, m, seed=None)
Return random graph using Barabási-Albert preferential attachment model.
A graph of n nodes is grown by attaching new nodes each with m edges that are preferentially attached to
existing nodes with high degree.
Parameters n : int
Number of nodes
m : int
Number of edges to attach from a new node to existing nodes
seed : int, optional
Seed for random number generator (default=None).
Returns G : Graph
Notes
References
[R306]
6.4.12 powerlaw_cluster_graph
powerlaw_cluster_graph(n, m, p, seed=None)
Holme and Kim algorithm for growing graphs with powerlaw degree distribution and approximate average
clustering.
Parameters n : int
the number of nodes
m : int
the number of random edges to add for each new node
p : float,
Probability of adding a triangle after adding a random edge
seed : int, optional
Seed for random number generator (default=None).
Notes
The average clustering has a hard time getting above a certain cutoff that depends on m. This cutoff is often
quite low. Note that the transitivity (fraction of triangles to possible triangles) seems to go down with network
size.
It is essentially the Barabási-Albert (B-A) growth model with an extra step that each random edge is followed
by a chance of making an edge to one of its neighbors too (and thus a triangle).
This algorithm improves on B-A in the sense that it enables a higher average clustering to be attained if desired.
It seems possible to have a disconnected graph with this algorithm since the initial m nodes may not be all linked
to a new node on the first iteration like the B-A model.
References
[R316]
6.4.13 random_lobster
Parameters n : int
The expected number of nodes in the backbone
p1 : float
Probability of adding an edge to the backbone
p2 : float
Probability of adding an edge one level beyond backbone
seed : int, optional
Seed for random number generator (default=None).
6.4.14 random_shell_graph
random_shell_graph(constructor, seed=None)
Return a random shell graph for the constructor given.
Parameters constructor: a list of three-tuples
(n,m,d) for each shell starting at the center shell.
n : int
The number of nodes in the shell
m : int
The number or edges in the shell
d : float
The ratio of inter-shell (next) edges to intra-shell edges. d=0 means no intra shell edges,
d=1 for the last shell
seed : int, optional
Seed for random number generator (default=None).
Examples
>>> constructor=[(10,20,0.8),(20,40,0.8)]
>>> G=nx.random_shell_graph(constructor)
6.4.15 random_powerlaw_tree
Notes
A trial powerlaw degree sequence is chosen and then elements are swapped with new elements from a powerlaw
distribution until the sequence makes a tree (#edges=#nodes-1).
6.4.16 random_powerlaw_tree_sequence
Notes
A trial powerlaw degree sequence is chosen and then elements are swapped with new elements from a powerlaw
distribution until the sequence makes a tree (#edges=#nodes-1).
configuration_model(deg_sequence[, ...]) Return a random graph with the given degree sequence.
directed_configuration_model(...[, ...]) Return a directed_random graph with the given degree sequences.
expected_degree_graph(w[, seed, selfloops]) Return a random graph with given expected degrees.
havel_hakimi_graph(deg_sequence[, create_using]) Return a simple graph with given degree sequence constructed using
directed_havel_hakimi_graph(in_deg_sequence, ...) Return a directed graph with the given degree sequences.
degree_sequence_tree(deg_sequence[, ...]) Make a tree for the given degree sequence.
random_degree_sequence_graph(sequence[, ...]) Return a simple random graph with the given degree sequence.
6.5.1 configuration_model
The configuration model generates a random pseudograph (graph with parallel edges and self loops) by ran-
domly assigning edges to match the given degree sequence.
Parameters deg_sequence : list of integers
Each list entry corresponds to the degree of a node.
create_using : graph, optional (default MultiGraph)
Return graph of this type. The instance will be cleared.
seed : hashable object, optional
Seed for random number generator.
Returns G : MultiGraph
A graph with the specified degree sequence. Nodes are labeled starting at 0 with an
index corresponding to the position in deg_sequence.
Raises NetworkXError
If the degree sequence does not have an even sum.
See also:
is_valid_degree_sequence
Notes
References
[R283]
Examples
>>> G=nx.Graph(G)
6.5.2 directed_configuration_model
Notes
References
[R284]
Examples
6.5.3 expected_degree_graph
Parameters w : list
The list of expected degrees.
selfloops: bool (default=True)
Set to False to remove the possibility of self-loop edges.
seed : hashable object, optional
The seed for the random number generator.
Returns Graph
Notes
The nodes have integer labels corresponding to index of expected degrees input sequence.
The complexity of this algorithm is 𝒪(𝑛 + 𝑚) where 𝑛 is the number of nodes and 𝑚 is the expected number
of edges.
The model in [R286] includes the possibility of self-loop edges. Set selfloops=False to produce a graph without
self loops.
For finite graphs this model doesn’t produce exactly the given expected degree sequence. Instead the expected
degrees are as follows.
For the case without self loops (selfloops=False),
(︂ )︂
∑︁ 𝑤𝑢
𝐸[𝑑𝑒𝑔(𝑢)] = 𝑝𝑢𝑣 = 𝑤𝑢 1 − ∑︀ .
𝑣̸=𝑢 𝑘 𝑤𝑘
NetworkX uses the standard convention that a self-loop edge counts 2 in the degree of a node, so with self loops
(selfloops=True),
(︂ )︂
∑︁ 𝑤𝑢
𝐸[𝑑𝑒𝑔(𝑢)] = 𝑝𝑢𝑣 + 2𝑝𝑢𝑢 = 𝑤𝑢 1 + ∑︀ .
𝑣̸=𝑢 𝑘 𝑤𝑘
References
[R286], [R287]
Examples
6.5.4 havel_hakimi_graph
havel_hakimi_graph(deg_sequence, create_using=None)
Return a simple graph with given degree sequence constructed using the Havel-Hakimi algorithm.
Parameters deg_sequence: list of integers
Each integer corresponds to the degree of a node (need not be sorted).
create_using : graph, optional (default Graph)
Return graph of this type. The instance will be cleared. Directed graphs are not allowed.
Raises NetworkXException
For a non-graphical degree sequence (i.e. one not realizable by some simple graph).
Notes
The Havel-Hakimi algorithm constructs a simple graph by successively connecting the node of highest degree
to other nodes of highest degree, resorting remaining nodes by degree, and repeating the process. The resulting
graph has a high degree-associativity. Nodes are labeled 1,.., len(deg_sequence), corresponding to their position
in deg_sequence.
The basic algorithm is from Hakimi [R288] and was generalized by Kleitman and Wang [R289].
References
[R288], [R289]
6.5.5 directed_havel_hakimi_graph
Notes
References
[R285]
6.5.6 degree_sequence_tree
degree_sequence_tree(deg_sequence, create_using=None)
Make a tree for the given degree sequence.
A tree has #nodes-#edges=1 so the degree sequence must have len(deg_sequence)-sum(deg_sequence)/2=1
6.5.7 random_degree_sequence_graph
Raises NetworkXUnfeasible
If the degree sequence is not graphical.
NetworkXError
If a graph is not produced in specified number of tries
See also:
is_valid_degree_sequence, configuration_model
Notes
References
[R290]
Examples
random_clustered_graph(joint_degree_sequence) Generate a random graph with the given joint degree and triangle degree s
6.6.1 random_clustered_graph
A graph with the specified degree sequence. Nodes are labeled starting at 0 with an
index corresponding to the position in deg_sequence.
Raises NetworkXError
If the independent edge degree sequence sum is not even or the triangle degree sequence
sum is not divisible by 3.
Notes
As described by Miller [R304] (see also Newman [R305] for an equivalent description).
A non-graphical degree sequence (not realizable by some simple graph) is allowed since this function returns
graphs with self loops and parallel edges. An exception is raised if the independent degree sequence does not
have an even sum or the triangle degree sequence sum is not divisible by 3.
This configuration model-like construction process can lead to duplicate edges and loops. You can remove the
self-loops and parallel edges (see below) which will likely result in a graph that doesn’t have the exact degree
sequence specified. This “finite-size effect” decreases as the size of the graph increases.
References
[R304], [R305]
Examples
>>> deg_tri=[[1,0],[1,0],[1,0],[2,0],[1,0],[2,1],[0,1],[0,1]]
>>> G = nx.random_clustered_graph(deg_tri)
6.7 Directed
6.7.1 gn_graph
References
[R291]
Examples
6.7.2 gnr_graph
References
[R293]
Examples
6.7.3 gnc_graph
References
[R292]
6.7.4 scale_free_graph
gamma : float
Probability for adding a new node conecgted to an existing node chosen randomly ac-
cording to the out-degree distribution.
delta_in : float
Bias for choosing ndoes from in-degree distribution.
delta_out : float
Bias for choosing ndoes from out-degree distribution.
create_using : graph, optional (default MultiDiGraph)
Use this graph instance to start the process (default=3-cycle).
seed : integer, optional
Seed for random number generator
Notes
References
[R294]
Examples
>>> G=nx.scale_free_graph(100)
6.8 Geometric
random_geometric_graph(n, radius[, dim, pos]) Return the random geometric graph in the unit cube.
geographical_threshold_graph(n, theta[, ...]) Return a geographical threshold graph.
waxman_graph(n[, alpha, beta, L, domain]) Return a Waxman random graph.
navigable_small_world_graph(n[, p, q, r, ...]) Return a navigable small-world graph.
6.8.1 random_geometric_graph
radius: float
Distance threshold value
dim : int, optional
Dimension of graph
pos : dict, optional
A dictionary keyed by node with node positions as values.
Returns Graph
Notes
This uses an 𝑛2 algorithm to build the graph. A faster algorithm is possible using k-d trees.
The pos keyword can be used to specify node positions so you can create an arbitrary distribution and domain
for positions. If you need a distance function other than Euclidean you’ll have to hack the algorithm.
E.g to use a 2d Gaussian distribution of node positions with mean (0,0) and std. dev. 2
>>> import random
>>> n=20
>>> p=dict((i,(random.gauss(0,2),random.gauss(0,2))) for i in range(n))
>>> G = nx.random_geometric_graph(n,0.2,pos=p)
References
[R298]
Examples
>>> G = nx.random_geometric_graph(20,0.1)
6.8.2 geographical_threshold_graph
𝑤𝑢 + 𝑤𝑣 ≥ 𝜃𝑟𝛼
Notes
If weights are not specified they are assigned to nodes by drawing randomly from an the exponential distribution
with rate parameter 𝜆 = 1. To specify a weights from a different distribution assign them to a dictionary and
pass it as the weight= keyword
>>> import random
>>> n = 20
>>> w=dict((i,random.expovariate(5.0)) for i in range(n))
>>> G = nx.geographical_threshold_graph(20,50,weight=w)
If node positions are not specified they are randomly assigned from the uniform distribution.
References
[R295], [R296]
Examples
>>> G = nx.geographical_threshold_graph(20,50)
6.8.3 waxman_graph
𝑝 = 𝛼 * 𝑒𝑥𝑝(−𝑑/(𝛽 * 𝐿)).
Parameters n : int
Number of nodes
alpha: float
Model parameter
beta: float
Model parameter
L : float, optional
Maximum distance between nodes. If not specified the actual distance is calculated.
domain : tuple of numbers, optional
Domain size (xmin, ymin, xmax, ymax)
Returns G: Graph
References
[R299]
6.8.4 navigable_small_world_graph
References
[R297]
6.9 Hybrid
Hybrid
kl_connected_subgraph(G, k, l[, low_memory, ...]) Returns the maximum locally (k,l) connected subgraph of G.
is_kl_connected(G, k, l[, low_memory]) Returns True if G is kl connected.
6.9.1 kl_connected_subgraph
6.9.2 is_kl_connected
is_kl_connected(G, k, l, low_memory=False)
Returns True if G is kl connected.
6.10 Bipartite
bipartite_configuration_model(aseq, bseq[, ...]) Return a random bipartite graph from two given degree sequenc
bipartite_havel_hakimi_graph(aseq, bseq[, ...]) Return a bipartite graph from two given degree sequences using
bipartite_reverse_havel_hakimi_graph(aseq, bseq) Return a bipartite graph from two given degree sequences using
bipartite_alternating_havel_hakimi_graph(...) Return a bipartite graph from two given degree sequences using
bipartite_preferential_attachment_graph(aseq, p) Create a bipartite graph with a preferential attachment model fro
bipartite_random_graph(n, m, p[, seed, directed]) Return a bipartite random graph.
bipartite_gnmk_random_graph(n, m, k[, seed, ...]) Return a random bipartite graph G_{n,m,k}.
6.10.1 bipartite_configuration_model
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
6.10.2 bipartite_havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
6.10.3 bipartite_reverse_havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
6.10.4 bipartite_alternating_havel_hakimi_graph
Notes
The sum of the two sequences must be equal: sum(aseq)=sum(bseq) If no graph type is specified use MultiGraph
with parallel edges. If you want a graph with no parallel edges use create_using=Graph() but then the resulting
degree sequences might not be exact.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
6.10.5 bipartite_preferential_attachment_graph
References
[R281]
6.10.6 bipartite_random_graph
Notes
The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges
with probability p.
This algorithm is O(n+m) where m is the expected number of edges.
The nodes are assigned the attribute ‘bipartite’ with the value 0 or 1 to indicate which bipartite set the node
belongs to.
References
[R282]
6.10.7 bipartite_gnmk_random_graph
Notes
Examples
G = nx.bipartite_gnmk_random_graph(10,20,50)
For an undirected graph G without multiple edges, each edge can be written as a set {u,v}. Its line graph L has the
edges of G as its nodes. If x and y are two nodes in L, then {x,y} is an edge in L if and only if the intersection of x and
y is nonempty. Thus, the set of all edges is determined by the set of all pair-wise intersections of edges in G.
Trivially, every edge x={u,v} in G would have a nonzero intersection with itself, and so every node in L should have
a self-loop. This is not so interesting, and the original context of line graphs was with simple graphs, which had no
self-loops or multiple edges. The line graph was also meant to be simple graph and thus, self-loops in L are not part
of the standard definition of a line graph. In a pair-wise intersection matrix, this is analogous to not including the
diagonal as part of the line graph definition.
Self-loops and multiple edges in G add nodes to L in a natural way, and do not require any fundamental changes to the
definition. It might be argued that the self-loops we excluded before should now be included. However, the self-loops
are still “trivial” in some sense and thus, are usually excluded.
For a directed graph G without multiple edges, each edge can be written as a tuple (u,v). Its line graph L has the edges
of G as its nodes. If x=(a,b) and y=(c,d) are two nodes in L, then (x,y) is an edge in L if and only if the tail of x matches
the head of y—e.g., b=c.
Due to the directed nature of the edges, it is no longer the case that every edge x=(u,v) should be connected to itself
with a self-loop in L. Now, the only time self-loops arise is if G itself has a self-loop. So such self-loops are no longer
“trivial” but instead, represent essential features of the topology of G. For this reason, the historical development of
line digraphs is such that self-loops are included. When the graph G has multiple edges, once again only superficial
changes are required to the definition.
6.11.3 References
Harary, Frank, and Norman, Robert Z., “Some properties of line digraphs”, Rend. Circ. Mat. Palermo, II. Ser.
9 (1960), 161–168.
Hemminger, R. L.; Beineke, L. W. (1978), “Line graphs and line digraphs”, in Beineke, L. W.; Wilson, R. J., Se-
lected Topics in Graph Theory, Academic Press Inc., pp. 271–305.
6.11.4 line_graph
line_graph(G, create_using=None)
Return the line graph of the graph or digraph G.
The line graph of a graph G has a node for each edge in G and an edge between those nodes if the two edges in
G share a common node. For directed graphs, nodes are connected only if they form a directed path of length 2.
The nodes of the line graph are 2-tuples of nodes in the original graph (or 3-tuples for multigraphs, with the key
of the edge as the 3rd element).
For more discussion, see the docstring in networkx.generators.line.
Parameters G : graph
A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
Returns L : graph
Notes
Graph, node, and edge data are not propagated to the new graph. For undirected graphs, the nodes in G must be
sortable—otherwise, the constructed line graph may not be correct.
Examples
>>> G = nx.star_graph(3)
>>> L = nx.line_graph(G)
>>> print(sorted(L.edges())) # makes a clique, K3
[((0, 1), (0, 2)), ((0, 1), (0, 3)), ((0, 3), (0, 2))]
Ego graph.
ego_graph(G, n[, radius, center, ...]) Returns induced subgraph of neighbors centered at node n within a given radius.
6.12.1 ego_graph
Notes
For directed graphs D this produces the “out” neighborhood or successors. If you want the neighborhood of
predecessors first reverse the graph with D.reverse(). If you want both directions use the keyword argument
undirected=True.
Node, edge, and graph attributes are copied to the returned subgraph.
6.13 Stochastic
Stocastic graph.
6.13.1 stochastic_graph
6.14 Intersection
6.14.1 uniform_random_intersection_graph
uniform_random_intersection_graph(n, m, p, seed=None)
Return a uniform random intersection graph.
Parameters n : int
The number of nodes in the first bipartite set (nodes)
m : int
The number of nodes in the second bipartite set (attributes)
p : float
Probability of connecting nodes between bipartite sets
seed : int, optional
References
[R302], [R303]
6.14.2 k_random_intersection_graph
k_random_intersection_graph(n, m, k)
Return a intersection graph with randomly chosen attribute sets for each node that are of equal size (k).
Parameters n : int
The number of nodes in the first bipartite set (nodes)
m : int
The number of nodes in the second bipartite set (attributes)
k : float
Size of attribute set to assign to each node.
seed : int, optional
Seed for random number generator (default=None).
See also:
gnp_random_graph, uniform_random_intersection_graph
References
[R301]
6.14.3 general_random_intersection_graph
general_random_intersection_graph(n, m, p)
Return a random intersection graph with independent probabilities for connections between node and attribute
sets.
Parameters n : int
The number of nodes in the first bipartite set (nodes)
m : int
The number of nodes in the second bipartite set (attributes)
p : list of floats of length m
Probabilities for connecting nodes to each attribute
seed : int, optional
Seed for random number generator (default=None).
See also:
gnp_random_graph, uniform_random_intersection_graph
References
[R300]
6.15.1 karate_club_graph
karate_club_graph()
Return Zachary’s Karate club graph.
References
[R322], [R323]
6.15.2 davis_southern_women_graph
davis_southern_women_graph()
Return Davis Southern women social network.
This is a bipartite graph.
References
[R320]
6.15.3 florentine_families_graph
florentine_families_graph()
Return Florentine families graph.
References
[R321]
SEVEN
LINEAR ALGEBRA
7.1.1 adjacency_matrix
Notes
If you want a pure Python adjacency matrix representation try networkx.convert.to_dict_of_dicts which will
return a dictionary-of-dictionaries format that can be addressed as a sparse matrix.
For MultiGraph/MultiDiGraph with parallel edges the weights are summed. See to_numpy_matrix for other
options.
391
NetworkX Reference, Release 1.9.1
The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the edge weight
attribute (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling the edge
weight is desired the resulting Scipy sparse matrix can be modified as follows:
>>> import scipy as sp
>>> G = nx.Graph([(1,1)])
>>> A = nx.adjacency_matrix(G)
>>> print(A.todense())
[[1]]
>>> A.setdiag(A.diagonal()*2)
>>> print(A.todense())
[[2]]
7.1.2 incidence_matrix
Notes
References
[R324]
7.2.1 laplacian_matrix
Notes
7.2.2 normalized_laplacian_matrix
𝑁 𝐿 = 𝐷−1/2 𝐿𝐷−1/2
where 𝐿 is the graph Laplacian and 𝐷 is the diagonal matrix of node degrees.
Parameters G : graph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist. If nodelist is
None, then the ordering is produced by G.nodes().
weight : string or None, optional (default=’weight’)
The edge data key used to compute each value in the matrix. If None, then each edge
has weight 1.
Returns L : NumPy matrix
The normalized Laplacian matrix of G.
See also:
laplacian_matrix
Notes
For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options.
If the Graph contains selfloops, D is defined as diag(sum(A,1)), where A is the adjencency matrix [R327].
References
[R326], [R327]
7.2.3 directed_laplacian_matrix
where 𝐼 is the identity matrix, 𝑃 is the transition matrix of the graph, and Φ a matrix with the Perron vector of
𝑃 in the diagonal and zeros elsewhere.
Depending on the value of walk_type, 𝑃 can be the transition matrix induced by a random walk, a lazy random
walk, or a random walk with teleportation (PageRank).
Parameters G : DiGraph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist. If nodelist is
None, then the ordering is produced by G.nodes().
weight : string or None, optional (default=’weight’)
The edge data key used to compute each value in the matrix. If None, then each edge
has weight 1.
Notes
References
[R325]
7.3 Spectrum
7.3.1 laplacian_spectrum
laplacian_spectrum(G, weight=’weight’)
Return eigenvalues of the Laplacian of G
Parameters G : graph
A NetworkX graph
weight : string or None, optional (default=’weight’)
The edge data key used to compute each value in the matrix. If None, then each edge
has weight 1.
Returns evals : NumPy array
Eigenvalues
See also:
laplacian_matrix
Notes
For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options.
7.3.2 adjacency_spectrum
adjacency_spectrum(G, weight=’weight’)
Return eigenvalues of the adjacency matrix of G.
Parameters G : graph
A NetworkX graph
weight : string or None, optional (default=’weight’)
The edge data key used to compute each value in the matrix. If None, then each edge
has weight 1.
Returns evals : NumPy array
Eigenvalues
See also:
adjacency_matrix
Notes
For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options.
7.4.1 algebraic_connectivity
The data key used to determine the weight of each edge. If None, then each edge has
unit weight. Default value: None.
normalized : bool, optional
Whether the normalized Laplacian matrix is used. Default value: False.
tol : float, optional
Tolerance of relative residual in eigenvalue computation. Default value: 1e-8.
method : string, optional
Method of eigenvalue computation. It should be one of ‘tracemin’ (TraceMIN), ‘lanc-
zos’ (Lanczos iteration) and ‘lobpcg’ (LOBPCG). Default value: ‘tracemin’.
The TraceMIN algorithm uses a linear system solver. The following values allow spec-
ifying the solver to be used.
Value Solver
‘tracemin_pcg’ Preconditioned conjugate gradient method
‘tracemin_chol’ Cholesky factorization
‘tracemin_lu’ LU factorization
Returns algebraic_connectivity : float
Algebraic connectivity.
Raises NetworkXNotImplemented
If G is directed.
NetworkXError
If G has less than two nodes.
See also:
laplacian_matrix
Notes
Edge weights are interpreted by their absolute values. For MultiGraph’s, weights of parallel edges are summed.
Zero-weighted edges are ignored.
To use Cholesky factorization in the TraceMIN algorithm, the scikits.sparse package must be installed.
7.4.2 fiedler_vector
Notes
Edge weights are interpreted by their absolute values. For MultiGraph’s, weights of parallel edges are summed.
Zero-weighted edges are ignored.
To use Cholesky factorization in the TraceMIN algorithm, the scikits.sparse package must be installed.
7.4.3 spectral_ordering
Notes
Edge weights are interpreted by their absolute values. For MultiGraph’s, weights of parallel edges are summed.
Zero-weighted edges are ignored.
To use Cholesky factorization in the TraceMIN algorithm, the scikits.sparse package must be installed.
attr_matrix(G[, edge_attr, node_attr, ...]) Returns a NumPy matrix using attributes from G.
attr_sparse_matrix(G[, edge_attr, ...]) Returns a SciPy sparse matrix using attributes from G.
7.5.1 attr_matrix
Examples
We can also color the nodes and ask for the probability distribution over all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.node[0]['color'] = 'red'
>>> G.node[1]['color'] = 'red'
>>> G.node[2]['color'] = 'blue'
>>> rc = ['red', 'blue']
>>> nx.attr_matrix(G, node_attr='color', normalized=True, rc_order=rc)
matrix([[ 0.33333333, 0.66666667],
[ 1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3 Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1 Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> nx.attr_matrix(G, edge_attr='weight', node_attr='color', rc_order=rc)
matrix([[ 3., 2.],
[ 2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1) (red, blue) is 2 # contributions from edges
(0,2) and (1,2) (blue, red) is 2 # same as (red, blue) since graph is undirected (blue, blue) is 0 # there
are no edges with blue endpoints
7.5.2 attr_sparse_matrix
Each row and column in the matrix represents a particular value of the node attribute.
The attribute must be present for all nodes in the graph. Note, the values of this attribute
should be reliably hashable. So, float values are not recommended. If no attribute is
specified, then the rows and columns will be the nodes of the graph.
normalized : bool, optional
If True, then each row is normalized by the summation of its values.
rc_order : list, optional
A list of the node attribute values. This list specifies the ordering of rows and columns
of the array. If no ordering is provided, then the ordering will be random (and also, a
return value).
Returns M : SciPy sparse matrix
The attribute matrix.
ordering : list
If 𝑟𝑐𝑜 𝑟𝑑𝑒𝑟 was specified, then only the matrix is returned. However, if 𝑟𝑐𝑜 𝑟𝑑𝑒𝑟 was
None, then the ordering used to construct the matrix is returned as well.
Other Parameters dtype : NumPy data-type, optional
A valid NumPy dtype used to initialize the array. Keep in mind certain dtypes can
yield unexpected results if the array is to be normalized. The parameter is passed to
numpy.zeros(). If unspecified, the NumPy default is used.
Examples
We can also color the nodes and ask for the probability distribution over all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.node[0]['color'] = 'red'
>>> G.node[1]['color'] = 'red'
>>> G.node[2]['color'] = 'blue'
>>> rc = ['red', 'blue']
>>> M = nx.attr_sparse_matrix(G, node_attr='color', normalized
>>> M.todense()
matrix([[ 0.33333333, 0.66666667],
[ 1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3 Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1 Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> M = nx.attr_sparse_matrix(G, edge_attr='weight', node_attr=
>>> M.todense()
matrix([[ 3., 2.],
[ 2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1) (red, blue) is 2 # contributions from edges
(0,2) and (1,2) (blue, red) is 2 # same as (red, blue) since graph is undirected (blue, blue) is 0 # there
are no edges with blue endpoints
EIGHT
8.1.1 Examples
nx_pygraphviz, nx_pydot
to_networkx_graph(data[, create_using, ...]) Make a NetworkX graph from a known data structure.
8.1.3 to_networkx_graph
405
NetworkX Reference, Release 1.9.1
8.2 Dictionaries
8.2.1 to_dict_of_dicts
8.2.2 from_dict_of_dicts
Examples
8.3 Lists
8.3.1 to_dict_of_lists
to_dict_of_lists(G, nodelist=None)
Return adjacency representation of graph as a dictionary of lists.
Parameters G : graph
A NetworkX graph
nodelist : list
Use only nodes specified in nodelist
Notes
8.3.2 from_dict_of_lists
from_dict_of_lists(d, create_using=None)
Return a graph from a dictionary of lists.
Parameters d : dictionary of lists
A dictionary of lists adjacency representation.
create_using : NetworkX graph
Use specified graph for result. Otherwise a new graph is created.
Examples
8.3.3 to_edgelist
to_edgelist(G, nodelist=None)
Return a list of edges in the graph.
Parameters G : graph
A NetworkX graph
nodelist : list
Use only nodes specified in nodelist
8.3.4 from_edgelist
from_edgelist(edgelist, create_using=None)
Return a graph from a list of edges.
Parameters edgelist : list or iterator
Edge tuples
create_using : NetworkX graph
Use specified graph for result. Otherwise a new graph is created.
Examples
8.4 Numpy
8.4.1 Examples
or equivalently
>>> D = nx.to_networkx_graph(a,create_using=nx.DiGraph())
nx_pygraphviz, nx_pydot
to_numpy_matrix(G[, nodelist, dtype, order, ...]) Return the graph adjacency matrix as a NumPy matrix.
to_numpy_recarray(G[, nodelist, dtype, order]) Return the graph adjacency matrix as a NumPy recarray.
from_numpy_matrix(A[, create_using]) Return a graph from numpy matrix.
8.4.3 to_numpy_matrix
Notes
The matrix entries are assigned to the weight edge attribute. When an edge does not have a weight attribute, the
value of the entry is set to the number 1. For multiple (parallel) edges, the values of the entries are determined
by the ‘multigraph_weight’ paramter. The default is to sum the weight attributes for each of the parallel edges.
When 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡 does not contain every node in 𝐺, the matrix is built from the subgraph of 𝐺 that is induced by
the nodes in 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡.
The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the weight
attributr of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling
the edge weight is desired the resulting Numpy matrix can be modified as follows:
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0,1,weight=2)
>>> G.add_edge(1,0)
>>> G.add_edge(2,2,weight=3)
>>> G.add_edge(2,2)
>>> nx.to_numpy_matrix(G, nodelist=[0,1,2])
matrix([[ 0., 2., 0.],
[ 1., 0., 0.],
[ 0., 0., 4.]])
8.4.4 to_numpy_recarray
Notes
When 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡 does not contain every node in 𝐺, the matrix is built from the subgraph of 𝐺 that is induced by
the nodes in 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡.
Examples
>>> G = nx.Graph()
>>> G.add_edge(1,2,weight=7.0,cost=5)
>>> A=nx.to_numpy_recarray(G,dtype=[('weight',float),('cost',int)])
>>> print(A.weight)
[[ 0. 7.]
[ 7. 0.]]
>>> print(A.cost)
[[0 5]
[5 0]]
8.4.5 from_numpy_matrix
from_numpy_matrix(A, create_using=None)
Return a graph from numpy matrix.
The numpy matrix is interpreted as an adjacency matrix for the graph.
Parameters A : numpy matrix
An adjacency matrix representation of a graph
create_using : NetworkX graph
Use specified graph for result. The default is Graph()
See also:
to_numpy_matrix, to_numpy_recarray
Notes
If the numpy matrix has a single data type for each matrix entry it will be converted to an appropriate Python
data type.
If the numpy matrix has a user-specified compound data type the names of the data fields will be used as attribute
keys in the resulting NetworkX graph.
Examples
>>> G[0][0]['weight']
1.0
8.5 Scipy
to_scipy_sparse_matrix(G[, nodelist, dtype, ...]) Return the graph adjacency matrix as a SciPy sparse matrix.
from_scipy_sparse_matrix(A[, create_using, ...]) Return a graph from scipy sparse matrix adjacency list.
8.5.1 to_scipy_sparse_matrix
Notes
The matrix entries are populated using the edge attribute held in parameter weight. When an edge does not have
that attribute, the value of the entry is 1.
For multiple edges the matrix values are the sums of the edge weights.
When 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡 does not contain every node in 𝐺, the matrix is built from the subgraph of 𝐺 that is induced by
the nodes in 𝑛𝑜𝑑𝑒𝑙𝑖𝑠𝑡.
Uses coo_matrix format. To convert to other formats specify the format= keyword.
The convention used for self-loop edges in graphs is to assign the diagonal matrix entry value to the weight
attribute of the edge (or the number 1 if the edge has no weight attribute). If the alternate convention of doubling
the edge weight is desired the resulting Scipy sparse matrix can be modified as follows:
References
[R280]
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0,1,weight=2)
>>> G.add_edge(1,0)
>>> G.add_edge(2,2,weight=3)
>>> G.add_edge(2,2)
>>> S = nx.to_scipy_sparse_matrix(G, nodelist=[0,1,2])
>>> print(S.todense())
[[0 2 0]
[1 0 0]
[0 0 4]]
8.5.2 from_scipy_sparse_matrix
Examples
NINE
9.1.1 Format
The adjacency list format consists of lines with node labels. The first label in a line is the source node. Further labels
in the line are considered target nodes and are added to the graph along with an edge between the source node and
target node.
The graph with edges a-b, a-c, d-e can be represented as the following adjacency list (anything following the # in a
line is a comment):
a b c # source target target
d e
read_adjlist(path[, comments, delimiter, ...]) Read graph in adjacency list format from path.
write_adjlist(G, path[, comments, ...]) Write graph G in single-line adjacency-list format to path.
parse_adjlist(lines[, comments, delimiter, ...]) Parse lines of a graph adjacency list representation.
generate_adjlist(G[, delimiter]) Generate a single line of the graph G in adjacency list format.
9.1.2 read_adjlist
415
NetworkX Reference, Release 1.9.1
Notes
Examples
>>> G=nx.path_graph(4)
>>> nx.write_adjlist(G, "test.adjlist")
>>> G=nx.read_adjlist("test.adjlist")
The path can be a filehandle or a string with the name of the file. If a filehandle is provided, it has to be opened
in ‘rb’ mode.
>>> fh=open("test.adjlist", 'rb')
>>> G=nx.read_adjlist(fh)
9.1.3 write_adjlist
Notes
Examples
>>> G=nx.path_graph(4)
>>> nx.write_adjlist(G,"test.adjlist")
The path can be a filehandle or a string with the name of the file. If a filehandle is provided, it has to be opened
in ‘wb’ mode.
>>> fh=open("test.adjlist",'wb')
>>> nx.write_adjlist(G, fh)
9.1.4 parse_adjlist
Examples
9.1.5 generate_adjlist
generate_adjlist(G, delimiter=’ ‘)
Generate a single line of the graph G in adjacency list format.
Parameters G : NetworkX graph
delimiter : string, optional
Separator for node labels
Returns lines : string
Lines of data in adjlist format.
See also:
write_adjlist, read_adjlist
Examples
>>> G = nx.lollipop_graph(4, 3)
>>> for line in nx.generate_adjlist(G):
... print(line)
0 1 2 3
1 2 3
2 3
3 4
4 5
5 6
6
9.2.1 Format
The first label in a line is the source node label followed by the node degree d. The next d lines are target node labels
and optional edge data. That pattern repeats for all nodes in the graph.
The graph with edges a-b, a-c, d-e can be represented as the following adjacency list (anything following the # in a
line is a comment):
# example.multiline-adjlist
a 2
b
c
d 1
e
read_multiline_adjlist(path[, comments, ...]) Read graph in multi-line adjacency list format from path.
write_multiline_adjlist(G, path[, ...]) Write the graph G in multiline adjacency list format to path
parse_multiline_adjlist(lines[, comments, ...]) Parse lines of a multiline adjacency list representation of a graph.
generate_multiline_adjlist(G[, delimiter]) Generate a single line of the graph G in multiline adjacency list format.
9.2.2 read_multiline_adjlist
Notes
Examples
>>> G=nx.path_graph(4)
>>> nx.write_multiline_adjlist(G,"test.adjlist")
>>> G=nx.read_multiline_adjlist("test.adjlist")
The path can be a file or a string with the name of the file. If a file s provided, it has to be opened in ‘rb’ mode.
>>> fh=open("test.adjlist", 'rb')
>>> G=nx.read_multiline_adjlist(fh)
The optional create_using parameter is a NetworkX graph container. The default is Graph(), an undirected
graph. To read the data as a directed graph use
>>> G=nx.read_multiline_adjlist("test.adjlist", create_using=nx.DiGraph())
9.2.3 write_multiline_adjlist
Text encoding.
See also:
read_multiline_adjlist
Examples
>>> G=nx.path_graph(4)
>>> nx.write_multiline_adjlist(G,"test.adjlist")
The path can be a file handle or a string with the name of the file. If a file handle is provided, it has to be opened
in ‘wb’ mode.
>>> fh=open("test.adjlist",'wb')
>>> nx.write_multiline_adjlist(G,fh)
9.2.4 parse_multiline_adjlist
Examples
9.2.5 generate_multiline_adjlist
generate_multiline_adjlist(G, delimiter=’ ‘)
Generate a single line of the graph G in multiline adjacency list format.
Parameters G : NetworkX graph
delimiter : string, optional
Separator for node labels
Returns lines : string
Lines of data in multiline adjlist format.
See also:
write_multiline_adjlist, read_multiline_adjlist
Examples
>>> G = nx.lollipop_graph(4, 3)
>>> for line in nx.generate_multiline_adjlist(G):
... print(line)
0 3
1 {}
2 {}
3 {}
1 2
2 {}
3 {}
2 1
3 {}
3 1
4 {}
4 1
5 {}
5 1
6 {}
6 0
The multi-line adjacency list format is useful for graphs with nodes that can be meaningfully represented as strings.
With the edgelist format simple edge data can be stored but node or graph data is not. There is no way of representing
isolated nodes unless the node has a self-loop edge.
9.3.1 Format
You can read or write three formats of edge lists with these functions.
Node pairs with no data:
1 2
Arbitrary data:
1 2 7 green
9.3.2 read_edgelist
Convert edge data from strings to specified type and use as ‘weight’
encoding: string, optional
Specify which encoding to use when reading file.
Returns G : graph
A networkx Graph or other type specified with create_using
See also:
parse_edgelist
Notes
Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset -
or tuples of those, etc.)
Examples
9.3.3 write_edgelist
Examples
>>> G=nx.path_graph(4)
>>> nx.write_edgelist(G, "test.edgelist")
>>> G=nx.path_graph(4)
>>> fh=open("test.edgelist",'wb')
>>> nx.write_edgelist(G, fh)
>>> nx.write_edgelist(G, "test.edgelist.gz")
>>> nx.write_edgelist(G, "test.edgelist.gz", data=False)
>>> G=nx.Graph()
>>> G.add_edge(1,2,weight=7,color='red')
>>> nx.write_edgelist(G,'test.edgelist',data=False)
>>> nx.write_edgelist(G,'test.edgelist',data=['color'])
>>> nx.write_edgelist(G,'test.edgelist',data=['color','weight'])
9.3.4 read_weighted_edgelist
Notes
Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset -
or tuples of those, etc.)
Example edgelist file format.
With numeric edge data:
# read with
# >>> G=nx.read_weighted_edgelist(fh)
# source target data
a b 1
a c 3.14159
d e 42
9.3.5 write_weighted_edgelist
Examples
>>> G=nx.Graph()
>>> G.add_edge(1,2,weight=7)
>>> nx.write_weighted_edgelist(G, 'test.weighted.edgelist')
9.3.6 generate_edgelist
Examples
>>> G = nx.lollipop_graph(4, 3)
>>> G[1][2]['weight'] = 3
>>> G[3][4]['capacity'] = 12
>>> for line in nx.generate_edgelist(G, data=False):
... print(line)
0 1
0 2
0 3
1 2
1 3
2 3
3 4
4 5
5 6
2 3
3 4
4 5
5 6
9.3.7 parse_edgelist
Examples
9.4 GEXF
9.4.1 Format
read_gexf(path[, node_type, relabel, version]) Read graph in GEXF format from path.
write_gexf(G, path[, encoding, prettyprint, ...]) Write G in GEXF format to path.
relabel_gexf_graph(G) Relabel graph using “label” node keyword for node label.
9.4.2 read_gexf
If True relabel the nodes to use the GEXF node “label” attribute instead of the node “id”
attribute as the NetworkX node label.
Returns graph: NetworkX graph
If no parallel edges are found a Graph or DiGraph is returned. Otherwise a MultiGraph
or MultiDiGraph is returned.
Notes
This implementation does not support mixed graphs (directed and undirected edges together).
References
[R328]
9.4.3 write_gexf
Notes
This implementation does not support mixed graphs (directed and undirected edges together).
The node id attribute is set to be the string of the node label. If you want to specify an id use set it as node data,
e.g. node[’a’][’id’]=1 to set the id of node ‘a’ to 1.
References
[R329]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_gexf(G, "test.gexf")
9.4.4 relabel_gexf_graph
relabel_gexf_graph(G)
Relabel graph using “label” node keyword for node label.
Parameters G : graph
A NetworkX graph read from GEXF data
Returns H : graph
A NetworkX graph with relabed nodes
Notes
This function relabels the nodes in a NetworkX graph with the “label” attribute. It also handles relabeling the
specific GEXF node attributes “parents”, and “pid”.
9.5 GML
9.5.1 Format
9.5.2 read_gml
read_gml(path, relabel=False)
Read graph in GML format from path.
Notes
Requires pyparsing: http://pyparsing.wikispaces.com/ The GML specification says that files should be ASCII
encoded, with any extended ASCII characters (iso8859-1) appearing as HTML character entities.
References
Examples
>>> G=nx.path_graph(4)
>>> nx.write_gml(G,'test.gml')
>>> H=nx.read_gml('test.gml')
9.5.3 write_gml
write_gml(G, path)
Write the graph G in GML format to the file or file handle path.
Parameters path : filename or filehandle
The filename or filehandle to write. Filenames ending in .gz or .gz2 will be compressed.
See also:
read_gml, parse_gml
Notes
GML specifications indicate that the file should only use 7bit ASCII text encoding.iso8859-1 (latin-1).
This implementation does not support all Python data types as GML data. Nodes, node attributes, edge attributes,
and graph attributes must be either dictionaries or single stings or numbers. If they are not an attempt is made
to represent them as strings. For example, a list as edge data G[1][2][’somedata’]=[1,2,3], will be represented
in the GML file as:
edge [
source 1
target 2
somedata "[1, 2, 3]"
]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_gml(G,"test.gml")
9.5.4 parse_gml
parse_gml(lines, relabel=True)
Parse GML graph from a string or iterable.
Parameters lines : string or iterable
Data in GML format.
relabel : bool, optional
If True use the GML node label attribute for node names otherwise use the node id.
Returns G : MultiGraph or MultiDiGraph
Raises ImportError
If the pyparsing module is not available.
See also:
write_gml, read_gml
Notes
This stores nested GML attributes as dictionaries in the NetworkX graph, node, and edge attribute structures.
Requires pyparsing: http://pyparsing.wikispaces.com/
References
9.5.5 generate_gml
generate_gml(G)
Generate a single entry of the graph G in GML format.
Parameters G : NetworkX graph
Notes
This implementation does not support all Python data types as GML data. Nodes, node attributes, edge attributes,
and graph attributes must be either dictionaries or single stings or numbers. If they are not an attempt is made
to represent them as strings. For example, a list as edge data G[1][2][’somedata’]=[1,2,3], will be represented
in the GML file as:
edge [
source 1
target 2
somedata "[1, 2, 3]"
]
9.6 Pickle
9.6.1 Format
See http://docs.python.org/library/pickle.html
9.6.2 read_gpickle
read_gpickle(path)
Read graph object in Python pickle format.
Pickles are a serialized byte stream of a Python object [R330]. This format will preserve Python objects used as
nodes or edges.
Parameters path : file or string
File or filename to write. Filenames ending in .gz or .bz2 will be uncompressed.
Returns G : graph
A NetworkX graph
References
[R330]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_gpickle(G,"test.gpickle")
>>> G=nx.read_gpickle("test.gpickle")
9.6.3 write_gpickle
write_gpickle(G, path)
Write graph in Python pickle format.
Pickles are a serialized byte stream of a Python object [R331]. This format will preserve Python objects used as
nodes or edges.
Parameters G : graph
A NetworkX graph
path : file or string
File or filename to write. Filenames ending in .gz or .bz2 will be compressed.
References
[R331]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_gpickle(G,"test.gpickle")
9.7 GraphML
9.7.1 Format
9.7.2 read_graphml
Notes
This implementation does not support mixed graphs (directed and unidirected edges together), hypergraphs,
nested graphs, or ports.
For multigraphs the GraphML edge “id” will be used as the edge key. If not specified then they “key” attribute
will be used. If there is no “key” attribute a default NetworkX multigraph edge key will be provided.
Files with the yEd “yfiles” extension will can be read but the graphics information is discarded.
yEd compressed files (“file.graphmlz” extension) can be read by renaming the file to “file.graphml.gz”.
9.7.3 write_graphml
Notes
This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges,
nested graphs, or ports.
Examples
>>> G=nx.path_graph(4)
>>> nx.write_graphml(G, "test.graphml")
9.8 JSON
node_link_data(G[, attrs]) Return data in node-link format that is suitable for JSON serialization and use in Javascri
node_link_graph(data[, directed, ...]) Return graph from node-link data format.
adjacency_data(G[, attrs]) Return data in adjacency format that is suitable for JSON serialization and use in Javascr
adjacency_graph(data[, directed, ...]) Return graph from adjacency data format.
tree_data(G, root[, attrs]) Return data in tree format that is suitable for JSON serialization and use in Javascript doc
tree_graph(data[, attrs]) Return graph from tree data format.
9.8.1 node_link_data
target=’target’, key=’key’).
If some user-defined graph data use these attribute names as data keys, they may be
silently dropped.
Returns data : dict
A dictionary with node-link formatted data.
Raises NetworkXError
If values in attrs are not unique.
See also:
node_link_graph, adjacency_data, tree_data
Notes
Graph, node, and link attributes are stored in this format but keys for attributes must be strings if you want to
serialize with JSON.
The default value of attrs will be changed in a future release of NetworkX.
Examples
9.8.2 node_link_graph
Notes
Examples
9.8.3 adjacency_data
Notes
Graph, node, and link attributes will be written when using this format but attribute keys must be strings if you
want to serialize the resulting data with JSON.
The default value of attrs will be changed in a future release of NetworkX.
Examples
9.8.4 adjacency_graph
Notes
Examples
9.8.5 tree_data
Notes
Node attributes are stored in this format but keys for attributes must be strings if you want to serialize with
JSON.
Graph and edge attributes are not stored.
The default value of attrs will be changed in a future release of NetworkX.
Examples
9.8.6 tree_graph
Notes
Examples
9.9 LEDA
9.9.1 Format
See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
9.9.2 read_leda
read_leda(path, encoding=’UTF-8’)
Read graph in LEDA format from path.
Parameters path : file or string
File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
Returns G : NetworkX graph
References
[R333]
Examples
G=nx.read_leda(‘file.leda’)
9.9.3 parse_leda
parse_leda(lines)
Read graph in LEDA format from string or iterable.
Parameters lines : string or iterable
Data in LEDA format.
Returns G : NetworkX graph
References
[R332]
Examples
G=nx.parse_leda(string)
9.10 YAML
9.10.1 Format
http://pyyaml.org/wiki/PyYAML
9.10.2 read_yaml
read_yaml(path)
Read graph in YAML format from path.
YAML is a data serialization format designed for human readability and interaction with scripting languages
[R336].
Parameters path : file or string
File or filename to read. Filenames ending in .gz or .bz2 will be uncompressed.
Returns G : NetworkX graph
References
[R336]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_yaml(G,'test.yaml')
>>> G=nx.read_yaml('test.yaml')
9.10.3 write_yaml
References
[R337]
Examples
>>> G=nx.path_graph(4)
>>> nx.write_yaml(G,'test.yaml')
9.11 SparseGraph6
9.11.1 Graph6
Graph6
Read and write graphs in graph6 format.
Format
“graph6 and sparse6 are formats for storing undirected graphs in a compact manner, using only printable ASCII
characters. Files in these formats have text type and contain one line per graph.”
See http://cs.anu.edu.au/~bdm/data/formats.txt for details.
parse_graph6
parse_graph6(string)
Read a simple undirected graph in graph6 format from string.
Parameters string : string
Data in graph6 format
Returns G : Graph
Raises NetworkXError
If the string is unable to be parsed in graph6 format
See also:
generate_graph6, read_graph6, write_graph6
References
Examples
>>> G = nx.parse_graph6('A_')
>>> sorted(G.edges())
[(0, 1)]
read_graph6
read_graph6(path)
Read simple undirected graphs in graph6 format from path.
Parameters path : file or string
File or filename to write.
Returns G : Graph or list of Graphs
If the file contains multiple lines then a list of graphs is returned
Raises NetworkXError
If the string is unable to be parsed in graph6 format
See also:
generate_graph6, parse_graph6, write_graph6
References
Examples
generate_graph6
Notes
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are
silently ignored.
References
Examples
write_graph6
Notes
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are
silently ignored.
References
Examples
9.11.2 Sparse6
Sparse6
Read and write graphs in sparse6 format.
Format
“graph6 and sparse6 are formats for storing undirected graphs in a compact manner, using only printable ASCII
characters. Files in these formats have text type and contain one line per graph.”
See http://cs.anu.edu.au/~bdm/data/formats.txt for details.
parse_sparse6
parse_sparse6(string)
Read an undirected graph in sparse6 format from string.
Parameters string : string
Data in sparse6 format
Returns G : Graph
Raises NetworkXError
If the string is unable to be parsed in sparse6 format
See also:
generate_sparse6, read_sparse6, write_sparse6
References
Examples
>>> G = nx.parse_sparse6(':A_')
>>> sorted(G.edges())
[(0, 1), (0, 1), (0, 1)]
read_sparse6
read_sparse6(path)
Read an undirected graph in sparse6 format from path.
Parameters path : file or string
File or filename to write.
Returns G : Graph/Multigraph or list of Graphs/MultiGraphs
If the file contains multple lines then a list of graphs is returned
Raises NetworkXError
If the string is unable to be parsed in sparse6 format
See also:
generate_sparse6, read_sparse6, parse_sparse6
References
Examples
generate_sparse6
Notes
The format does not support edge or node labels. References ———- Sparse6 specification:
http://cs.anu.edu.au/~bdm/data/formats.txt for details.
Examples
write_sparse6
Raises NetworkXError
If the graph is directed
See also:
read_sparse6, parse_sparse6, generate_sparse6
Notes
References
Examples
9.12 Pajek
9.12.1 Format
9.12.2 read_pajek
read_pajek(path, encoding=’UTF-8’)
Read graph in Pajek format from path.
Parameters path : file or string
File or filename to write. Filenames ending in .gz or .bz2 will be uncompressed.
Returns G : NetworkX MultiGraph or MultiDiGraph.
References
Examples
>>> G=nx.path_graph(4)
>>> nx.write_pajek(G, "test.net")
>>> G=nx.read_pajek("test.net")
9.12.3 write_pajek
References
Examples
>>> G=nx.path_graph(4)
>>> nx.write_pajek(G, "test.net")
9.12.4 parse_pajek
parse_pajek(lines)
Parse Pajek format graph from string or iterable.
Parameters lines : string or iterable
9.13.1 read_shp
read_shp(path)
Generates a networkx.DiGraph from shapefiles. Point geometries are translated into nodes, lines into edges.
Coordinate tuples are used as keys. Attributes are preserved, line geometries are simplified into start and end
coordinates. Accepts a single shapefile or directory of many shapefiles.
“The Esri Shapefile or simply a shapefile is a popular geospatial vector data format for geographic information
systems software [R334].”
Parameters path : file or string
File, directory, or filename to read.
Returns G : NetworkX graph
References
[R334]
Examples
>>> G=nx.read_shp('test.shp')
9.13.2 write_shp
write_shp(G, outdir)
Writes a networkx.DiGraph to two shapefiles, edges and nodes. Nodes and edges are expected to have a Well
Known Binary (Wkb) or Well Known Text (Wkt) key in order to generate geometries. Also acceptable are nodes
with a numeric tuple key (x,y).
“The Esri Shapefile or simply a shapefile is a popular geospatial vector data format for geographic information
systems software [R335].”
References
[R335]
Examples
TEN
DRAWING
10.1 Matplotlib
matplotlib: http://matplotlib.sourceforge.net/
pygraphviz: http://networkx.lanl.gov/pygraphviz/
10.1.2 draw
455
NetworkX Reference, Release 1.9.1
Notes
This function has the same name as pylab.draw and pyplot.draw so beware when using
>>> from networkx import *
Examples
>>> G=nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout
10.1.3 draw_networkx
Examples
>>> G=nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G,pos=nx.spring_layout(G)) # use spring layout
10.1.4 draw_networkx_nodes
Examples
>>> G=nx.dodecahedral_graph()
>>> nodes=nx.draw_networkx_nodes(G,pos=nx.spring_layout(G))
10.1.5 draw_networkx_edges
A networkx graph
pos : dictionary
A dictionary with nodes as keys and positions as values. Positions should be sequences
of length 2.
edgelist : collection of edge tuples
Draw only specified edges(default=G.edges())
width : float
Line width of edges (default =1.0)
edge_color : color string, or array of floats
Edge color. Can be a single color format string (default=’r’), or a sequence of colors
with the same length as edgelist. If numeric values are specified they will be mapped to
colors using the edge_cmap and edge_vmin,edge_vmax parameters.
style : string
Edge line style (default=’solid’) (solid|dashed|dotted,dashdot)
alpha : float
The edge transparency (default=1.0)
edge_ cmap : Matplotlib colormap
Colormap for mapping intensities of edges (default=None)
edge_vmin,edge_vmax : floats
Minimum and maximum for edge colormap scaling (default=None)
ax : Matplotlib Axes object, optional
Draw the graph in the specified Matplotlib axes.
arrows : bool, optional (default=True)
For directed graphs, if True draw arrowheads.
label : [None| string]
Label for legend
Returns matplotlib.collection.LineCollection
𝐿𝑖𝑛𝑒𝐶𝑜𝑙𝑙𝑒𝑐𝑡𝑖𝑜𝑛 of the edges
See also:
draw, draw_networkx, draw_networkx_nodes, draw_networkx_labels,
draw_networkx_edge_labels
Notes
For directed graphs, “arrows” (actually just thicker stubs) are drawn at the head end. Arrows can be turned off
with keyword arrows=False. Yes, it is ugly but drawing proper arrows with Matplotlib this way is tricky.
Examples
>>> G=nx.dodecahedral_graph()
>>> edges=nx.draw_networkx_edges(G,pos=nx.spring_layout(G))
10.1.6 draw_networkx_labels
Examples
>>> G=nx.dodecahedral_graph()
>>> labels=nx.draw_networkx_labels(G,pos=nx.spring_layout(G))
10.1.7 draw_networkx_edge_labels
Examples
>>> G=nx.dodecahedral_graph()
>>> edge_labels=nx.draw_networkx_edge_labels(G,pos=nx.spring_layout(G))
10.1.8 draw_circular
draw_circular(G, **kwargs)
Draw the graph G with a circular layout.
Parameters G : graph
A networkx graph
**kwargs : optional keywords
See networkx.draw_networkx() for a description of optional keywords, with the excep-
tion of the pos parameter which is not used by this function.
10.1.9 draw_random
draw_random(G, **kwargs)
Draw the graph G with a random layout.
Parameters G : graph
A networkx graph
**kwargs : optional keywords
See networkx.draw_networkx() for a description of optional keywords, with the excep-
tion of the pos parameter which is not used by this function.
10.1.10 draw_spectral
draw_spectral(G, **kwargs)
Draw the graph G with a spectral layout.
Parameters G : graph
A networkx graph
**kwargs : optional keywords
See networkx.draw_networkx() for a description of optional keywords, with the excep-
tion of the pos parameter which is not used by this function.
10.1.11 draw_spring
draw_spring(G, **kwargs)
Draw the graph G with a spring layout.
Parameters G : graph
A networkx graph
10.1.12 draw_shell
draw_shell(G, **kwargs)
Draw networkx graph with shell layout.
Parameters G : graph
A networkx graph
**kwargs : optional keywords
See networkx.draw_networkx() for a description of optional keywords, with the excep-
tion of the pos parameter which is not used by this function.
10.1.13 draw_graphviz
10.2.1 Examples
>>> G=nx.complete_graph(5)
>>> A=nx.to_agraph(G)
>>> H=nx.from_agraph(A)
Pygraphviz: http://networkx.lanl.gov/pygraphviz
10.2.3 from_agraph
from_agraph(A, create_using=None)
Return a NetworkX Graph or DiGraph from a PyGraphviz graph.
Parameters A : PyGraphviz AGraph
A graph created with PyGraphviz
create_using : NetworkX graph class instance
The output is created using the given graph class instance
Notes
The Graph G will have a dictionary G.graph_attr containing the default graphviz attributes for graphs, nodes
and edges.
Default node attributes will be in the dictionary G.node_attr which is keyed by node.
Edge attributes will be returned as edge data in G. With edge_attr=False the edge data will be the Graphviz edge
weight attribute or the value 1 if no edge weight attribute is found.
Examples
>>> K5=nx.complete_graph(5)
>>> A=nx.to_agraph(K5)
>>> G=nx.from_agraph(A)
>>> G=nx.from_agraph(A)
10.2.4 to_agraph
to_agraph(N)
Return a pygraphviz graph from a NetworkX graph N.
Parameters N : NetworkX graph
A graph created with NetworkX
Notes
If N has an dict N.graph_attr an attempt will be made first to copy properties attached to the graph (see
from_agraph) and then updated with the calling arguments if any.
Examples
>>> K5=nx.complete_graph(5)
>>> A=nx.to_agraph(K5)
10.2.5 write_dot
write_dot(G, path)
Write NetworkX graph G to Graphviz dot format on path.
Parameters G : graph
A networkx graph
path : filename
Filename or file handle to write
10.2.6 read_dot
read_dot(path)
Return a NetworkX graph from a dot file on path.
Parameters path : file or string
File name or file handle to read.
10.2.7 graphviz_layout
Notes
Examples
>>> G=nx.petersen_graph()
>>> pos=nx.graphviz_layout(G)
>>> pos=nx.graphviz_layout(G,prog='dot')
10.2.8 pygraphviz_layout
Examples
>>> G=nx.petersen_graph()
>>> pos=nx.graphviz_layout(G)
>>> pos=nx.graphviz_layout(G,prog='dot')
Import and export NetworkX graphs in Graphviz dot format using pydot.
Either this module or nx_pygraphviz can be used to interface with graphviz.
10.3.2 from_pydot
from_pydot(P)
Return a NetworkX graph from a Pydot graph.
Parameters P : Pydot graph
A graph created with Pydot
Returns G : NetworkX multigraph
A MultiGraph or MultiDiGraph.
Examples
>>> K5=nx.complete_graph(5)
>>> A=nx.to_pydot(K5)
>>> G=nx.from_pydot(A) # return MultiGraph
>>> G=nx.Graph(nx.from_pydot(A)) # make a Graph instead of MultiGraph
10.3.3 to_pydot
to_pydot(N, strict=True)
Return a pydot graph from a NetworkX graph N.
Parameters N : NetworkX graph
A graph created with NetworkX
Examples
>>> K5=nx.complete_graph(5)
>>> P=nx.to_pydot(K5)
10.3.4 write_dot
write_dot(G, path)
Write NetworkX graph G to Graphviz dot format on path.
Path can be a string or a file handle.
10.3.5 read_dot
read_dot(path)
Return a NetworkX MultiGraph or MultiDiGraph from a dot file on path.
Parameters path : filename or file handle
Returns G : NetworkX multigraph
A MultiGraph or MultiDiGraph.
Notes
10.3.6 graphviz_layout
Notes
Examples
>>> G=nx.complete_graph(4)
>>> pos=nx.graphviz_layout(G)
>>> pos=nx.graphviz_layout(G,prog='dot')
10.3.7 pydot_layout
Examples
>>> G=nx.complete_graph(4)
>>> pos=nx.pydot_layout(G)
>>> pos=nx.pydot_layout(G,prog='dot')
10.4.1 circular_layout
Notes
This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
Examples
>>> G=nx.path_graph(4)
>>> pos=nx.circular_layout(G)
10.4.2 random_layout
random_layout(G, dim=2)
Position nodes uniformly at random in the unit square.
For every node, a position is generated by choosing each of dim coordinates uniformly at random on the interval
[0.0, 1.0).
NumPy (http://scipy.org) is required for this function.
Parameters G : NetworkX graph
A position will be assigned to every node in G.
dim : int
Dimension of layout.
Returns dict :
A dictionary of positions keyed by node
Examples
>>> G = nx.lollipop_graph(4, 3)
>>> pos = nx.random_layout(G)
10.4.3 shell_layout
Notes
This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
Examples
>>> G=nx.path_graph(4)
>>> shells=[[0],[1,2,3]]
>>> pos=nx.shell_layout(G,shells)
10.4.4 spring_layout
Examples
>>> G=nx.path_graph(4)
>>> pos=nx.spring_layout(G)
10.4.5 spectral_layout
Notes
Directed graphs will be considered as unidrected graphs when positioning the nodes.
For larger graphs (>500 nodes) this will use the SciPy sparse eigenvalue solver (ARPACK).
Examples
>>> G=nx.path_graph(4)
>>> pos=nx.spectral_layout(G)
ELEVEN
EXCEPTIONS
473
NetworkX Reference, Release 1.9.1
TWELVE
UTILITIES
12.1.1 is_string_like
is_string_like(obj)
Check if obj is string.
12.1.2 flatten
flatten(obj, result=None)
Return flattened version of (possibly nested) iterable object.
12.1.3 iterable
iterable(obj)
Return True if obj is iterable with a well-defined len().
475
NetworkX Reference, Release 1.9.1
12.1.4 is_list_of_ints
is_list_of_ints(intlist)
Return True if list is a list of ints.
12.1.5 make_str
make_str(x)
Return the string representation of t.
12.1.6 cumulative_sum
cumulative_sum(numbers)
Yield cumulative sum of numbers.
>>> import networkx.utils as utils
>>> list(utils.cumulative_sum([1,2,3,4]))
[1, 3, 6, 10]
12.1.7 generate_unique_node
generate_unique_node()
Generate a unique node label.
12.1.8 default_opener
default_opener(filename)
Opens 𝑓 𝑖𝑙𝑒𝑛𝑎𝑚𝑒 using system’s default program.
Parameters filename : str
The path of the file to be opened.
UnionFind.union(*objects) Find the sets containing the objects and merge them all.
12.2.1 union
UnionFind.union(*objects)
Find the sets containing the objects and merge them all.
Utilities for generating random numbers, random sequences, and random selections.
12.3.1 create_degree_sequence
12.3.2 pareto_sequence
pareto_sequence(n, exponent=1.0)
Return sample sequence of length n from a Pareto distribution.
12.3.3 powerlaw_sequence
powerlaw_sequence(n, exponent=2.0)
Return sample sequence of length n from a power law distribution.
12.3.4 uniform_sequence
uniform_sequence(n)
Return sample sequence of length n from a uniform distribution.
12.3.5 cumulative_distribution
cumulative_distribution(distribution)
Return normalized cumulative distribution from discrete distribution.
12.3.6 discrete_sequence
12.3.7 zipf_sequence
12.3.8 zipf_rv
Notes
The rejection algorithm generates random values for a the power-law distribution in uniformly bounded expected
time dependent on parameters. See [1] for details on its operation.
References
..[1] Luc Devroye, Non-Uniform Random Variate Generation, Springer-Verlag, New York, 1986.
Examples
12.3.9 random_weighted_sample
random_weighted_sample(mapping, k)
Return k items without replacement from a weighted sample.
The input is a dictionary of items with weights as values.
12.3.10 weighted_choice
weighted_choice(mapping)
Return a single element from a weighted sample.
The input is a dictionary of items with weights as values.
12.4 Decorators
12.4.1 open_file
open_file(path_arg, mode=’r’)
Decorator to ensure clean opening and closing of files.
Parameters path_arg : int
Location of the path argument in args. Even if the argument is a named positional
argument (with a default value), you must specify its index as a positional argument.
mode : str
String for opening mode.
Returns _open_file : function
Function which cleanly executes the io.
Examples
@open_file(1,'w')
def write_function(G,pathname):
pass
@open_file(1,'w')
def write_function(G, pathname='graph.dot')
pass
@open_file('path', 'w+')
def another_function(arg, **kwargs):
path = kwargs['path']
pass
cuthill_mckee_ordering(G[, heuristic]) Generate an ordering (permutation) of the graph nodes to make a sparse
reverse_cuthill_mckee_ordering(G[, heuristic]) Generate an ordering (permutation) of the graph nodes to make a sparse
12.5.1 cuthill_mckee_ordering
cuthill_mckee_ordering(G, heuristic=None)
Generate an ordering (permutation) of the graph nodes to make a sparse matrix.
Uses the Cuthill-McKee heuristic (based on breadth-first search) [R338].
Parameters G : graph
A NetworkX graph
heuristic : function, optional
Function to choose starting node for RCM algorithm. If None a node from a psuedo-
peripheral pair is used. A user-defined function can be supplied that takes a graph object
and returns a single node.
Returns nodes : generator
Generator of nodes in Cuthill-McKee ordering.
See also:
reverse_cuthill_mckee_ordering
Notes
References
[R338], [R339]
Examples
12.5.2 reverse_cuthill_mckee_ordering
reverse_cuthill_mckee_ordering(G, heuristic=None)
Generate an ordering (permutation) of the graph nodes to make a sparse matrix.
Uses the reverse Cuthill-McKee heuristic (based on breadth-first search) [R340].
Parameters G : graph
A NetworkX graph
heuristic : function, optional
Function to choose starting node for RCM algorithm. If None a node from a psuedo-
peripheral pair is used. A user-defined function can be supplied that takes a graph object
and returns a single node.
Returns nodes : generator
Generator of nodes in reverse Cuthill-McKee ordering.
See also:
cuthill_mckee_ordering
Notes
References
[R340], [R341]
Examples
reversed(*args, **kwds) A context manager for temporarily reversing a directed graph in place.
12.6.1 reversed
reversed(*args, **kwds)
A context manager for temporarily reversing a directed graph in place.
This is a no-op for undirected graphs.
Parameters G : graph
A NetworkX graph.
THIRTEEN
LICENSE
* Neither the name of the NetworkX Developers nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
485
NetworkX Reference, Release 1.9.1
FOURTEEN
CITING
487
NetworkX Reference, Release 1.9.1
FIFTEEN
CREDITS
NetworkX was originally written by Aric Hagberg, Dan Schult, and Pieter Swart, and has been developed with the
help of many others.
Thanks to Guido van Rossum for the idea of using Python for implementing a graph data structure
http://www.python.org/doc/essays/graphs.html
Thanks to David Eppstein for the idea of representing a graph G so that “for n in G” loops over the nodes in G and
G[n] are node n’s neighbors.
Thanks to everyone who has improved NetworkX by contributing code, bug reports (and fixes), documentation, and
input on design, featues, and the future of NetworkX.
Thanks especially to the following contributors:
• Katy Bold contributed the Karate Club graph.
• Hernan Rozenfeld added dorogovtsev_goltsev_mendes_graph and did stress testing.
• Brendt Wohlberg added examples from the Stanford GraphBase.
• Jim Bagrow reported bugs in the search methods.
• Holly Johnsen helped fix the path based centrality measures.
• Arnar Flatberg fixed the graph laplacian routines.
• Chris Myers suggested using None as a default datatype, suggested improvements for the IO routines, added
grid generator index tuple labeling and associated routines, and reported bugs.
• Joel Miller tested and improved the connected components methods fixed bugs and typos in the graph generators,
and contributed the random clustered graph generator.
• Keith Briggs sorted out naming issues for random graphs and wrote dense_gnm_random_graph.
• Ignacio Rozada provided the Krapivsky-Redner graph generator.
• Phillipp Pagel helped fix eccentricity etc. for disconnected graphs.
• Sverre Sundsdal contributed bidirectional shortest path and Dijkstra routines, s-metric computation and graph
generation
• Ross M. Richardson contributed the expected degree graph generator and helped test the pygraphviz interface.
• Christopher Ellison implemented the VF2 isomorphism algorithm and is a core developer.
• Eben Kenah contributed the strongly connected components and DFS functions.
• Sasha Gutfriend contributed edge betweenness algorithms.
• Udi Weinsberg helped develop intersection and difference operators.
• Matteo Dell’Amico wrote the random regular graph generator.
489
NetworkX Reference, Release 1.9.1
• Andrew Conway contributed ego_graph, eigenvector centrality, line graph and much more.
• Raf Guns wrote the GraphML writer.
• Salim Fadhley and Matteo Dell’Amico contributed the A* algorithm.
• Fabrice Desclaux contributed the Matplotlib edge labeling code.
• Arpad Horvath fixed the barabasi_albert_graph() generator.
• Minh Van Nguyen contributed the connected_watts_strogatz_graph() and documentation for the Graph and
MultiGraph classes.
• Willem Ligtenberg contributed the directed scale free graph generator.
• Loïc Séguin-C. contributed the Ford-Fulkerson max flow and min cut algorithms, and ported all of NetworkX
to Python3. He is a NetworkX core developer.
• Paul McGuire improved the performance of the GML data parser.
• Jesus Cerquides contributed the chordal graph algorithms.
• Ben Edwards contributed tree generating functions, the rich club coefficient algorithm, the graph product func-
tions, and a whole lot of other useful nuts and bolts.
• Jon Olav Vik contributed cycle finding algorithms.
• Hugh Brown improved the words.py example from the n^2 algorithm.
• Ben Reilly contributed the shapefile reader and writer.
• Leo Lopes contributed the maximal independent set algorithm.
• Jordi Torrents contributed the bipartite clustering, bipartite node redundancy, square clustering, bipartite projec-
tion articulation point, and flow-based connectivity algorithms.
• Dheeraj M R contributed the distance-regular testing algorithm
• Franck Kalala contributed the subgraph_centrality and communicability algorithms
• Simon Knight improved the GraphML functions to handle yEd/yfiles data, and to handle types correctly.
• Conrad Lee contributed the k-clique community finding algorithm.
• Sérgio Nery Simões wrote the function for finding all simple paths, and all shortest paths.
• Robert King contributed union, disjoint union, compose, and intersection operators that work on lists of graphs.
• Nick Mancuso wrote the approximation algorithms for dominating set, edge dominating set, independent set,
max clique, and min-weighted vertex cover.
• Brian Cloteaux contributed the linear-time graphicality tests and Havel-Hakimi graph generators
• Alejandro Weinstein contributed the directed Laplacian code
• Dustin Smith wrote the dictionary to numpy array function
• Mathieu Larose sped up the topological sort code
• Vincent Gauthier contributed the Katz centrality algorithm
• Sérgio Nery Simões developed the code for finding all simple paths
SIXTEEN
GLOSSARY
dictionary A Python dictionary maps keys to values. Also known as “hashes”, or “associative arrays”. See
http://docs.python.org/tutorial/datastructures.html#dictionaries
ebunch An iteratable container of edge tuples like a list, iterator, or file.
edge Edges are either two-tuples of nodes (u,v) or three tuples of nodes with an edge attribute dictionary (u,v,dict).
edge attribute Edges can have arbitrary Python objects assigned as attributes by using keyword/value pairs when
adding an edge assigning to the G.edge[u][v] attribute dictionary for the specified edge u-v.
hashable An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects
which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the
hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionar-
ies) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal,
and their hash value is their id().
Definition from http://docs.python.org/glossary.html
nbunch An nbunch is any iterable container of nodes that is not itself a node in the graph. It can be an iterable or an
iterator, e.g. a list, set, graph, file, etc..
node A node can be any hashable Python object except None.
node attribute Nodes can have arbitrary Python objects assigned as attributes by using keyword/value pairs when
adding a node or assigning to the G.node[n] attribute dictionary for the specified node n.
491
NetworkX Reference, Release 1.9.1
[R142] Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding sub-
graphs. BIT Numerical Mathematics, 32(2), 180–196. Springer. doi:10.1007/BF01994876
[R141] Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding sub-
graphs. BIT Numerical Mathematics, 32(2), 180–196. Springer.
[R143] Schank, Thomas, and Dorothea Wagner. Approximating clustering coef-
ficient and transitivity. Universität Karlsruhe, Fakultät für Informatik, 2004.
http://www.emis.ams.org/journals/JGAA/accepted/2005/SchankWagner2005.9.2.pdf
[R144] Vazirani, Vijay Approximation Algorithms (2001)
[R145] Boppana, R., & Halldórsson, M. M. (1992). Approximating maximum independent sets by excluding sub-
graphs. BIT Numerical Mathematics, 32(2), 180–196. Springer.
[R146] Vazirani, Vijay Approximation Algorithms (2001)
[R147] Bar-Yehuda, R., & Even, S. (1985). A local-ratio theorem for approximating the weighted vertex cover prob-
lem. Annals of Discrete Mathematics, 25, 27–46 http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf
[R151] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003
[R152] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS
107, 10815-20 (2010).
[R148] M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003
[R156] M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003
[R153] M. E. J. Newman, Mixing patterns in networks Physical Review E, 67 026126, 2003
[R154] Foster, J.G., Foster, D.V., Grassberger, P. & Paczuski, M. Edge direction and the structure of networks, PNAS
107, 10815-20 (2010).
[R150] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted
networks”. PNAS 101 (11): 3747–3752 (2004).
[R149] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted
networks”. PNAS 101 (11): 3747–3752 (2004).
[R155] A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted
networks”. PNAS 101 (11): 3747–3752 (2004).
[R166] Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds)
The Sage Handbook of Social Network Analysis. Sage Publications.
[R164] Scientific collaboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman,
Phys. Rev. E 64, 016132 (2001).
493
NetworkX Reference, Release 1.9.1
[R165] Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation Networks. In Carrington, P. and Scott, J. (eds)
The Sage Handbook of Social Network Analysis. Sage Publications.
[R168] E. Estrada and J. A. Rodríguez-Velázquez, “Spectral measures of bipartivity in complex networks”, PhysRev
E 72, 046105 (2005)
[R161] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of
large two-mode networks. Social Networks 30(1), 31–48.
[R160] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of
large two-mode networks. Social Networks 30(1), 31–48.
[R162] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of
large two-mode networks. Social Networks 30(1), 31–48.
[R163] Robins, G. and M. Alexander (2004). Small worlds among interlocking directors: Network structure and
distance in bipartite graphs. Computational & Mathematical Organization Theory 10(1), 69–94.
[R167] Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of
large two-mode networks. Social Networks 30(1), 31–48.
[R158] Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington,
P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications.
http://www.steveborgatti.com/papers/bhaffiliations.pdf
[R159] Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington,
P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications.
http://www.steveborgatti.com/papers/bhaffiliations.pdf
[R157] Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington,
P. and Scott, J. (eds) The Sage Handbook of Social Network Analysis. Sage Publications.
http://www.steveborgatti.com/papers/bhaffiliations.pdf
[R169] Patrick Doreian, Vladimir Batagelj, and Anuska Ferligoj “Generalized Blockmodeling”,Cambridge Univer-
sity Press, 2004.
[R174] Freeman, L.C., 1979. Centrality in networks: I. Conceptual clarification. Social Networks 1, 215–239.
http://www.soc.ucsb.edu/faculty/friedkin/Syllabi/Soc146/Freeman78.PDF
[R171] A Faster Algorithm for Betweenness Centrality. Ulrik Brandes, Journal of Mathematical Sociology 25(2):163-
177, 2001. http://www.inf.uni-konstanz.de/algo/publications/b-fabc-01.pdf
[R172] Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social
Networks 30(2):136-145, 2008. http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
[R173] Ulrik Brandes and Christian Pich: Centrality Estimation in Large Networks. International Journal of Bifurca-
tion and Chaos 17(7):2303-2318, 2007. http://www.inf.uni-konstanz.de/algo/publications/bp-celn-06.pdf
[R188] A Faster Algorithm for Betweenness Centrality. Ulrik Brandes, Journal of Mathematical Sociology 25(2):163-
177, 2001. http://www.inf.uni-konstanz.de/algo/publications/b-fabc-01.pdf
[R189] Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social
Networks 30(2):136-145, 2008. http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf
[R185] Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp.
Theoretical Aspects of Computer Science (STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf
[R186] Stephenson, K. and Zelen, M. Rethinking centrality: Methods and examples. Social Networks. Volume 11,
Issue 1, March 1989, pp. 1-37 http://dx.doi.org/10.1016/0378-8733(89)90016-6
494 Bibliography
NetworkX Reference, Release 1.9.1
[R183] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp.
Theoretical Aspects of Computer Science (STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf
[R184] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54
(2005).
[R190] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp.
Theoretical Aspects of Computer Science (STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf
[R191] A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54
(2005).
[R170] Centrality Measures Based on Current Flow. Ulrik Brandes and Daniel Fleischer, Proc. 22nd Symp.
Theoretical Aspects of Computer Science (STACS ‘05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005.
http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf
[R193] M. Newman, Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.
[R194] M. Newman, Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.
[R175] Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111
(2008). http://arxiv.org/abs/0707.0756
[R182] Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111
(2008). http://arxiv.org/abs/0707.0756
[R178] Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review
E 71, 056103 (2005). http://arxiv.org/abs/cond-mat/0504730
[R179] Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111
(2008). http://arxiv.org/abs/0707.0756
[R180] Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review
E 71, 056103 (2005). http://arxiv.org/abs/cond-mat/0504730
[R181] Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111
(2008). http://arxiv.org/abs/0707.0756
[R177] Ernesto Estrada, Desmond J. Higham, Naomichi Hatano, “Communicability Betweenness in Complex Net-
works” Physica A 388 (2009) 764-774. http://arxiv.org/abs/0905.4102
[R192] E. Estrada, Characterization of 3D molecular structure, Chem. Phys. Lett. 319, 713 (2000).
[R187] Romantic Partnerships and the Dispersion of Social Ties: A Network Analysis of Relationship Status on
Facebook. Lars Backstrom, Jon Kleinberg. http://arxiv.org/pdf/1310.6753v1.pdf
[R197] R. E. Tarjan and M. Yannakakis, Simple linear-time algorithms to test chordality of graphs, test acyclicity of
hypergraphs, and selectively reduce acyclic hypergraphs, SIAM J. Comput., 13 (1984), pp. 566–579.
[R195] http://en.wikipedia.org/wiki/Tree_decomposition#Treewidth
[R196] Learning Bounded Treewidth Bayesian Networks. Gal Elidan, Stephen Gould; JMLR, 9(Dec):2699–2731,
2008. http://jmlr.csail.mit.edu/papers/volume9/elidan08a/elidan08a.pdf
[R198] Bron, C. and Kerbosch, J. 1973. Algorithm 457: finding all cliques of an undirected graph. Commun. ACM
16, 9 (Sep. 1973), 575-577. http://portal.acm.org/citation.cfm?doid=362342.362367
[R199] Etsuji Tomita, Akira Tanaka, Haruhisa Takahashi, The worst-case time complexity for generating all maximal
cliques and computational experiments, Theoretical Computer Science, Volume 363, Issue 1, Computing and
Combinatorics, 10th Annual International Conference on Computing and Combinatorics (COCOON 2004), 25
October 2006, Pages 28-42 http://dx.doi.org/10.1016/j.tcs.2006.06.015
Bibliography 495
NetworkX Reference, Release 1.9.1
[R200] F. Cazals, C. Karande, A note on the problem of reporting maximal cliques, Theoretical Computer Science,
Volume 407, Issues 1-3, 6 November 2008, Pages 564-568, http://dx.doi.org/10.1016/j.tcs.2008.05.010
[R203] Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki,
M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
http://jponnela.com/web_documents/a9.pdf
[R201] Generalizations of the clustering coefficient to weighted complex networks by J. Saramäki,
M. Kivelä, J.-P. Onnela, K. Kaski, and J. Kertész, Physical Review E, 75 027105 (2007).
http://jponnela.com/web_documents/a9.pdf
[R202] Marcus Kaiser, Mean clustering coefficients: the role of isolated nodes and leafs on clustering measures for
small-world networks. http://arxiv.org/abs/0802.2512
[R204] Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks.
Physical Review E (72) 056127.
[R205] Gergely Palla, Imre Derényi, Illés Farkas1, and Tamás Vicsek, Uncovering the overlapping community struc-
ture of complex networks in nature and society Nature 435, 814-818, 2005, doi:10.1038/nature03607
[R211] Depth-first search and linear graph algorithms, R. Tarjan SIAM Journal of Computing 1(2):146-160, (1972).
[R212] On finding the strongly connected components in a directed graph. E. Nuutila and E. Soisalon-Soinen Infor-
mation Processing Letters 49(1): 9-14, (1994)..
[R213] Depth-first search and linear graph algorithms, R. Tarjan SIAM Journal of Computing 1(2):146-160, (1972).
[R214] On finding the strongly connected components in a directed graph. E. Nuutila and E. Soisalon-Soinen Infor-
mation Processing Letters 49(1): 9-14, (1994)..
[R210] Hopcroft, J.; Tarjan, R. (1973). “Efficient algorithms for graph manipulation”. Communications of the ACM
16: 372–378. doi:10.1145/362248.362272
[R209] Hopcroft, J.; Tarjan, R. (1973). “Efficient algorithms for graph manipulation”. Communications of the ACM
16: 372–378. doi:10.1145/362248.362272
[R207] Hopcroft, J.; Tarjan, R. (1973). “Efficient algorithms for graph manipulation”. Communications of the ACM
16: 372–378. doi:10.1145/362248.362272
[R208] Hopcroft, J.; Tarjan, R. (1973). “Efficient algorithms for graph manipulation”. Communications of the ACM
16: 372–378. doi:10.1145/362248.362272
[R206] Hopcroft, J.; Tarjan, R. (1973). “Efficient algorithms for graph manipulation”. Communications of the ACM
16: 372–378. doi:10.1145/362248.362272
[R215] Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics
252(1-3), 31-45. http://www.sciencedirect.com/science/article/pii/S0012365X01001807
[R216] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R217] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R219] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, ‘Network Analysis:
Methodological Foundations’, Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
[R220] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R221] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R222] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R224] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
496 Bibliography
NetworkX Reference, Release 1.9.1
[R226] Abdol-Hossein Esfahanian. Connectivity Algorithms. (this is a chapter, look for the reference of the book).
http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R227] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, ‘Network Analysis:
Methodological Foundations’, Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005.
http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf
[R228] An O(m) Algorithm for Cores Decomposition of Networks Vladimir Batagelj and Matjaz Zaversnik, 2003.
http://arxiv.org/abs/cs.DS/0310049
[R229] An O(m) Algorithm for Cores Decomposition of Networks Vladimir Batagelj and Matjaz Zaversnik, 2003.
http://arxiv.org/abs/cs.DS/0310049
[R231] A model of Internet topology using k-shell decomposition Shai Carmi, Shlomo Havlin, Scott
Kirkpatrick, Yuval Shavitt, and Eran Shir, PNAS July 3, 2007 vol. 104 no. 27 11150-11154
http://www.pnas.org/content/104/27/11150.full
[R230] k -core (bootstrap) percolation on complex networks: Critical phenomena and nonlocal ef-
fects, A. V. Goltsev, S. N. Dorogovtsev, and J. F. F. Mendes, Phys. Rev. E 73, 056101 (2006)
http://link.aps.org/doi/10.1103/PhysRevE.73.056101
[R232] Paton, K. An algorithm for finding a fundamental set of cycles of a graph. Comm. ACM 12, 9 (Sept 1969),
514-518.
[R233] Finding all the elementary circuits of a directed graph. D. B. Johnson, SIAM Journal on Computing 4, no. 1,
77-84, 1975. http://dx.doi.org/10.1137/0204007
[R234] Enumerating the cycles of a digraph: a new preprocessing strategy. G. Loizou and P. Thanish, Information
Sciences, v. 27, 163-182, 1982.
[R235] A search strategy for the elementary cycles of a directed graph. J.L. Szwarcfiter and P.E. Lauer, BIT NUMER-
ICAL MATHEMATICS, v. 16, no. 2, 192-204, 1976.
[R237] Skiena, S. S. The Algorithm Design Manual (Springer-Verlag, 1998).
http://www.amazon.com/exec/obidos/ASIN/0387948600/ref=ase_thealgorithmrepo/
[R236] Jarvis, J. P.; Shier, D. R. (1996), Graph-theoretic analysis of finite Markov chains, in Shier, D. R.; Wallenius,
K. T., Applied Mathematical Modeling: A Multidisciplinary Approach, CRC Press.
[R240] Brouwer, A. E.; Cohen, A. M.; and Neumaier, A. Distance-Regular Graphs. New York: Springer-Verlag,
1989.
[R241] Weisstein, Eric W. “Distance-Regular Graph.” http://mathworld.wolfram.com/Distance-RegularGraph.html
[R239] Weisstein, Eric W. “Intersection Array.” From MathWorld–A Wolfram Web Resource.
http://mathworld.wolfram.com/IntersectionArray.html
[R238] Weisstein, Eric W. “Global Parameters.” From MathWorld–A Wolfram Web Resource.
http://mathworld.wolfram.com/GlobalParameters.html
[R242] http://en.wikipedia.org/wiki/Dominating_set
[R243] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
[R244] http://en.wikipedia.org/wiki/Dominating_set
[R245] J. Edmonds, E. L. Johnson. Matching, Euler tours and the Chinese postman. Mathematical programming,
Volume 5, Issue 1 (1973), 111-114.
[R246] http://en.wikipedia.org/wiki/Eulerian_path
[R247] D.J. Kleitman and D.L. Wang Algorithms for Constructing Graphs and Digraphs with Given Valences and
Factors, Discrete Mathematics, 6(1), pp. 79-88 (1973)
Bibliography 497
NetworkX Reference, Release 1.9.1
[R248] S. L. Hakimi. “On the realizability of a set of integers as degrees of the vertices of a linear graph”, J. SIAM,
10, pp. 496-506 (1962).
[R249] F. Boesch and F. Harary. “Line removal algorithms for graphs and their degree lists”, IEEE Trans. Circuits
and Systems, CAS-23(12), pp. 778-782 (1976).
[R252] I.E. Zverovich and V.E. Zverovich. “Contributions to the theory of graphic sequences”, Discrete Mathematics,
105, pp. 292-303 (1992).
[R250] A. Tripathi and S. Vijay. “A note on a theorem of Erdős & Gallai”, Discrete Mathematics, 265, pp. 417-420
(2003).
[R251] I.E. Zverovich and V.E. Zverovich. “Contributions to the theory of graphic sequences”, Discrete Mathematics,
105, pp. 292-303 (1992).
[R253] Luo, J.; Magee, C.L. (2011), Detecting evolving patterns of self-organizing networks by
flow hierarchy measurement, Complexity, Volume 16 Issue 6 53-61. DOI: 10.1002/cplx.20368
http://web.mit.edu/~cmagee/www/documents/28-DetectingEvolvingPatterns_FlowHierarchy.pdf
[R254] L. P. Cordella, P. Foggia, C. Sansone, M. Vento, “An Improved Algorithm for Matching Large Graphs”,
3rd IAPR-TC15 Workshop on Graph-based Representations in Pattern Recognition, Cuen, pp. 149-159, 2001.
http://amalfi.dis.unina.it/graph/db/papers/vf-algorithm.pdf
[R261] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R262] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, The PageRank citation ranking:
Bringing order to the Web. 1999 http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-
66&format=pdf
[R263] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R264] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, The PageRank citation ranking:
Bringing order to the Web. 1999 http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-
66&format=pdf
[R265] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R266] Page, Lawrence; Brin, Sergey; Motwani, Rajeev and Winograd, Terry, The PageRank citation ranking:
Bringing order to the Web. 1999 http://dbpubs.stanford.edu:8090/pub/showDoc.Fulltext?lang=en&doc=1999-
66&format=pdf
[R255] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R256] Jon Kleinberg, Authoritative sources in a hyperlinked environment Journal of the ACM 46 (5): 604-32, 1999.
doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf.
[R257] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R258] Jon Kleinberg, Authoritative sources in a hyperlinked environment Journal of the ACM 46 (5): 604-32, 1999.
doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf.
[R259] A. Langville and C. Meyer, “A survey of eigenvector methods of web information retrieval.”
http://citeseer.ist.psu.edu/713792.html
[R260] Jon Kleinberg, Authoritative sources in a hyperlinked environment Journal of the ACM 46 (5): 604-632, 1999.
doi:10.1145/324133.324140. http://www.cs.cornell.edu/home/kleinber/auth.pdf.
498 Bibliography
NetworkX Reference, Release 1.9.1
[R272] T. Zhou, L. Lu, Y.-C. Zhang. Predicting missing links via local information. Eur. Phys. J. B 71 (2009) 623.
http://arxiv.org/pdf/0901.0553.pdf
[R269] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004).
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
[R267] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004).
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
[R270] D. Liben-Nowell, J. Kleinberg. The Link Prediction Problem for Social Networks (2004).
http://www.cs.cornell.edu/home/kleinber/link-pred.pdf
[R268] Sucheta Soundarajan and John Hopcroft. Using community information to improve the precision of link pre-
diction methods. In Proceedings of the 21st international conference companion on World Wide Web (WWW ‘12
Companion). ACM, New York, NY, USA, 607-608. http://doi.acm.org/10.1145/2187980.2188150
[R271] Sucheta Soundarajan and John Hopcroft. Using community information to improve the precision of link pre-
diction methods. In Proceedings of the 21st international conference companion on World Wide Web (WWW ‘12
Companion). ACM, New York, NY, USA, 607-608. http://doi.acm.org/10.1145/2187980.2188150
[R273] Jorge Carlos Valverde-Rebaza and Alneu de Andrade Lopes. Link prediction in complex networks based
on cluster information. In Proceedings of the 21st Brazilian conference on Advances in Artificial Intelligence
(SBIA‘12) http://dx.doi.org/10.1007/978-3-642-34459-6_10
[R274] “Efficient Algorithms for Finding Maximum Matching in Graphs”, Zvi Galil, ACM Computing Surveys,
1986.
[R275] Julian J. McAuley, Luciano da Fontoura Costa, and Tibério S. Caetano, “The rich-club phe-
nomenon across complex network hierarchies”, Applied Physics Letters Vol 91 Issue 8, August 2007.
http://arxiv.org/abs/physics/0701290
[R276] R. Milo, N. Kashtan, S. Itzkovitz, M. E. J. Newman, U. Alon, “Uniform generation of random graphs with
arbitrary degree sequences”, 2006. http://arxiv.org/abs/cond-mat/0312028
[R277] R. Sedgewick, “Algorithms in C, Part 5: Graph Algorithms”, Addison Wesley Professional, 3rd ed., 2001.
[R278] C. Gkantsidis and M. Mihail and E. Zegura, The Markov chain simulation method for generating connected
power law random graphs, 2003. http://citeseer.ist.psu.edu/gkantsidis03markov.html
[R279] Ulrik Brandes, Sec. 3.6.2 in Network Analysis: Methodological Foundations, Springer, 2005.
http://books.google.com/books?id=TTNhSm7HYrIC
[R312] Vladimir Batagelj and Ulrik Brandes, “Efficient generation of large random networks”, Phys. Rev. E, 71,
036113, 2005.
[R313] 16. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
[R314] 5. (a) Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
[R309] Donald E. Knuth, The Art of Computer Programming, Volume 2/Seminumerical algorithms, Third Edition,
Addison-Wesley, 1997.
[R310] 16. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
[R311] 5. (a) Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
[R307] 16. Erdős and A. Rényi, On Random Graphs, Publ. Math. 6, 290 (1959).
[R308] 5. (a) Gilbert, Random Graphs, Ann. Math. Stat., 30, 1141 (1959).
[R315] M. E. J. Newman and D. J. Watts, Renormalization group analysis of the small-world network model, Physics
Letters A, 263, 341, 1999. http://dx.doi.org/10.1016/S0375-9601(99)00757-4
[R319] Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp.
440–442, 1998.
Bibliography 499
NetworkX Reference, Release 1.9.1
[R317] A. Steger and N. Wormald, Generating random regular graphs quickly, Probability and Computing 8 (1999),
377-396, 1999. http://citeseer.ist.psu.edu/steger99generating.html
[R318] Jeong Han Kim and Van H. Vu, Generating random regular graphs, Proceedings of the
thirty-fifth ACM symposium on Theory of computing, San Diego, CA, USA, pp 213–222, 2003.
http://portal.acm.org/citation.cfm?id=780542.780576
[R306] A. L. Barabási and R. Albert “Emergence of scaling in random networks”, Science 286, pp 509-512, 1999.
[R316] P. Holme and B. J. Kim, “Growing scale-free networks with tunable clustering”, Phys. Rev. E, 65, 026107,
2002.
[R283] M.E.J. Newman, “The structure and function of complex networks”, SIAM REVIEW 45-2, pp 167-256, 2003.
[R284] Newman, M. E. J. and Strogatz, S. H. and Watts, D. J. Random graphs with arbitrary degree distributions and
their applications Phys. Rev. E, 64, 026118 (2001)
[R286] Fan Chung and L. Lu, Connected components in random graphs with given expected degree sequences, Ann.
Combinatorics, 6, pp. 125-145, 2002.
[R287] Joel Miller and Aric Hagberg, Efficient generation of networks with given expected degrees, in Algorithms
and Models for the Web-Graph (WAW 2011), Alan Frieze, Paul Horn, and Paweł Prałat (Eds), LNCS 6732, pp.
115-126, 2011.
[R288] Hakimi S., On Realizability of a Set of Integers as Degrees of the Vertices of a Linear Graph. I, Journal of
SIAM, 10(3), pp. 496-506 (1962)
[R289] Kleitman D.J. and Wang D.L. Algorithms for Constructing Graphs and Digraphs with Given Valences and
Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
[R285] D.J. Kleitman and D.L. Wang Algorithms for Constructing Graphs and Digraphs with Given Valences and
Factors Discrete Mathematics, 6(1), pp. 79-88 (1973)
[R290] Moshen Bayati, Jeong Han Kim, and Amin Saberi, A sequential algorithm for generating random graphs.
Algorithmica, Volume 58, Number 4, 860-910, DOI: 10.1007/s00453-009-9340-1
[R304] J. C. Miller “Percolation and Epidemics on Random Clustered Graphs.” Physical Review E, Rapid Commu-
nication (to appear).
[R305] M.E.J. Newman, “Random clustered networks”. Physical Review Letters (to appear).
[R291] P. L. Krapivsky and S. Redner, Organization of Growing Random Networks, Phys. Rev. E, 63, 066123, 2001.
[R293] P. L. Krapivsky and S. Redner, Organization of Growing Random Networks, Phys. Rev. E, 63, 066123, 2001.
[R292] P. L. Krapivsky and S. Redner, Network Growth by Copying, Phys. Rev. E, 71, 036118, 2005k.},
[R294] B. Bollob{‘a}s, C. Borgs, J. Chayes, and O. Riordan, Directed scale-free graphs, Proceedings of the fourteenth
annual ACM-SIAM symposium on Discrete algorithms, 132–139, 2003.
[R298] Penrose, Mathew, Random Geometric Graphs, Oxford Studies in Probability, 5, 2003.
[R295] Masuda, N., Miwa, H., Konno, N.: Geographical threshold graphs with small-world and scale-free properties.
Physical Review E 71, 036108 (2005)
[R296] Milan Bradonjić, Aric Hagberg and Allon G. Percus, Giant component and connectivity in geographical
threshold graphs, in Algorithms and Models for the Web-Graph (WAW 2007), Antony Bonato and Fan Chung
(Eds), pp. 209–216, 2007
[R299] B. M. Waxman, Routing of multipoint connections. IEEE J. Select. Areas Commun. 6(9),(1988) 1617-1622.
[R297] J. Kleinberg. The small-world phenomenon: An algorithmic perspective. Proc. 32nd ACM Symposium on
Theory of Computing, 2000.
500 Bibliography
NetworkX Reference, Release 1.9.1
[R281] Jean-Loup Guillaume and Matthieu Latapy, Bipartite structure of all complex networks, Inf. Process. Lett. 90,
2004, pg. 215-221 http://dx.doi.org/10.1016/j.ipl.2004.03.007
[R282] Vladimir Batagelj and Ulrik Brandes, “Efficient generation of large random networks”, Phys. Rev. E, 71,
036113, 2005.
[R302] K.B. Singer-Cohen, Random Intersection Graphs, 1995, PhD thesis, Johns Hopkins University
[R303] Fill, J. A., Scheinerman, E. R., and Singer-Cohen, K. B., Random intersection graphs when m = !(n): An
equivalence theorem relating the evolution of the g(n, m, p) and g(n, p) models. Random Struct. Algorithms 16, 2
(2000), 156–176.
[R301] Godehardt, E., and Jaworski, J. Two models of random intersection graphs and their applications. Electronic
Notes in Discrete Mathematics 10 (2001), 129–132.
[R300] Nikoletseas, S. E., Raptopoulos, C., and Spirakis, P. G. The existence and efficient construction of large
independent sets in general random intersection graphs. In ICALP (2004), J. D´ıaz, J. Karhum¨aki, A. Lepist¨o,
and D. Sannella, Eds., vol. 3142 of Lecture Notes in Computer Science, Springer, pp. 1029–1040.
[R322] Zachary W. An information flow model for conflict and fission in small groups. Journal of Anthropological
Research, 33, 452-473, (1977).
[R323] Data file from: http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm
[R320] A. Davis, Gardner, B. B., Gardner, M. R., 1941. Deep South. University of Chicago Press, Chicago, IL.
[R321] Ronald L. Breiger and Philippa E. Pattison Cumulated social roles: The duality of persons and their algebras,1
Social Networks, Volume 8, Issue 3, September 1986, Pages 215-256
[R324] Gil Strang, Network applications: A = incidence matrix, http://academicearth.org/lectures/network-
applications-incidence-matrix
[R326] Fan Chung-Graham, Spectral Graph Theory, CBMS Regional Conference Series in Mathematics, Number 92,
1997.
[R327] Steve Butler, Interlacing For Weighted Graphs Using The Normalized Laplacian, Electronic Journal of Linear
Algebra, Volume 16, pp. 90-98, March 2007.
[R325] Fan Chung (2005). Laplacians and the Cheeger inequality for directed graphs. Annals of Combinatorics, 9(1),
2005
[R280] Scipy Dev. References, “Sparse Matrices”, http://docs.scipy.org/doc/scipy/reference/sparse.html
[R328] GEXF graph format, http://gexf.net/format/
[R329] GEXF graph format, http://gexf.net/format/
[R330] http://docs.python.org/library/pickle.html
[R331] http://docs.python.org/library/pickle.html
[R333] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
[R332] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
[R336] http://www.yaml.org
[R337] http://www.yaml.org
[R334] http://en.wikipedia.org/wiki/Shapefile
[R335] http://en.wikipedia.org/wiki/Shapefile
[R338] E. Cuthill and J. McKee. Reducing the bandwidth of sparse symmetric matrices, In Proc. 24th Nat. Conf.
ACM, pages 157-172, 1969. http://doi.acm.org/10.1145/800195.805928
Bibliography 501
NetworkX Reference, Release 1.9.1
[R339] Steven S. Skiena. 1997. The Algorithm Design Manual. Springer-Verlag New York, Inc., New York, NY,
USA.
[R340] E. Cuthill and J. McKee. Reducing the bandwidth of sparse symmetric matrices, In Proc. 24th Nat. Conf.
ACM, pages 157-72, 1969. http://doi.acm.org/10.1145/800195.805928
[R341] Steven S. Skiena. 1997. The Algorithm Design Manual. Springer-Verlag New York, Inc., New York, NY,
USA.
502 Bibliography
PYTHON MODULE INDEX
a networkx.algorithms.components.biconnected,
networkx.algorithms.approximation, 127 203
networkx.algorithms.approximation.clique,networkx.algorithms.components.connected,
127 194
networkx.algorithms.components.semiconnected,
networkx.algorithms.approximation.clustering_coefficient,
128 208
networkx.algorithms.components.strongly_connected,
networkx.algorithms.approximation.dominating_set,
128 197
networkx.algorithms.components.weakly_connected,
networkx.algorithms.approximation.independent_set,
130 200
networkx.algorithms.connectivity,
networkx.algorithms.approximation.matching, 208
130 networkx.algorithms.connectivity.connectivity,
networkx.algorithms.approximation.ramsey, 209
131 networkx.algorithms.connectivity.cuts,
networkx.algorithms.approximation.vertex_cover, 217
131 networkx.algorithms.connectivity.stoerwagner,
networkx.algorithms.assortativity, 132 223
networkx.algorithms.bipartite, 141 networkx.algorithms.connectivity.utils,
networkx.algorithms.bipartite.basic, 143 225
networkx.algorithms.bipartite.centrality,networkx.algorithms.core, 225
158 networkx.algorithms.cycles, 229
networkx.algorithms.bipartite.cluster, networkx.algorithms.dag, 231
153 networkx.algorithms.distance_measures,
networkx.algorithms.bipartite.projection, 234
147 networkx.algorithms.distance_regular,
networkx.algorithms.bipartite.redundancy, 236
157 networkx.algorithms.dominating, 237
networkx.algorithms.bipartite.spectral, networkx.algorithms.euler, 238
152 networkx.algorithms.flow, 240
networkx.algorithms.block, 161 networkx.algorithms.graphical, 264
networkx.algorithms.boundary, 162 networkx.algorithms.hierarchy, 268
networkx.algorithms.centrality, 163 networkx.algorithms.isolate, 269
networkx.algorithms.chordal.chordal_alg, networkx.algorithms.isomorphism, 270
184 networkx.algorithms.isomorphism.isomorphvf2,
networkx.algorithms.clique, 187 272
networkx.algorithms.cluster, 190 networkx.algorithms.link_analysis.hits_alg,
networkx.algorithms.community, 193 287
networkx.algorithms.community.kclique, networkx.algorithms.link_analysis.pagerank_alg,
193 283
networkx.algorithms.components, 194 networkx.algorithms.link_prediction, 290
networkx.algorithms.matching, 296
networkx.algorithms.components.attracting,
201 networkx.algorithms.mis, 298
503
NetworkX Reference, Release 1.9.1
g
networkx.generators.atlas, 349
networkx.generators.bipartite, 381
networkx.generators.classic, 349
networkx.generators.degree_seq, 367
networkx.generators.directed, 374
networkx.generators.ego, 387
networkx.generators.geometric, 377
networkx.generators.hybrid, 381
networkx.generators.intersection, 388
networkx.generators.line, 385
505
NetworkX Reference, Release 1.9.1
506 Index
NetworkX Reference, Release 1.9.1
Index 507
NetworkX Reference, Release 1.9.1
508 Index
NetworkX Reference, Release 1.9.1
Index 509
NetworkX Reference, Release 1.9.1
510 Index
NetworkX Reference, Release 1.9.1
Index 511
NetworkX Reference, Release 1.9.1
J M
jaccard_coefficient() (in module net- make_clique_bipartite() (in module net-
workx.algorithms.link_prediction), 291 workx.algorithms.clique), 189
make_max_clique_graph() (in module net-
K workx.algorithms.clique), 188
k_clique_communities() (in module net- make_small_graph() (in module net-
workx.algorithms.community.kclique), 194 workx.generators.small), 354
k_core() (in module networkx.algorithms.core), 226 make_str() (in module networkx.utils.misc), 476
k_corona() (in module networkx.algorithms.core), 229 match() (DiGraphMatcher method), 277
k_crust() (in module networkx.algorithms.core), 228 match() (GraphMatcher method), 275
k_nearest_neighbors() (in module net- max_clique() (in module net-
workx.algorithms.assortativity), 138 workx.algorithms.approximation.clique),
k_random_intersection_graph() (in module net- 127
workx.generators.intersection), 389 max_flow_min_cost() (in module net-
k_shell() (in module networkx.algorithms.core), 227 workx.algorithms.flow), 261
karate_club_graph() (in module net- max_weight_matching() (in module net-
workx.generators.social), 390 workx.algorithms.matching), 297
katz_centrality() (in module net- maximal_independent_set() (in module net-
workx.algorithms.centrality), 174 workx.algorithms.mis), 298
katz_centrality_numpy() (in module net- maximal_matching() (in module net-
workx.algorithms.centrality), 176 workx.algorithms.matching), 297
kl_connected_subgraph() (in module net- maximum_flow() (in module networkx.algorithms.flow),
workx.generators.hybrid), 381 240
kosaraju_strongly_connected_components() maximum_flow_value() (in module net-
(in module net- workx.algorithms.flow), 242
maximum_independent_set()
workx.algorithms.components.strongly_connected), (in module net-
199 workx.algorithms.approximation.independent_set),
krackhardt_kite_graph() (in module net- 130
workx.generators.small), 357 min_cost_flow() (in module networkx.algorithms.flow),
259
L min_cost_flow_cost() (in module net-
ladder_graph() (in module networkx.generators.classic), workx.algorithms.flow), 258
353 min_edge_dominating_set() (in module net-
laplacian_matrix() (in module net- workx.algorithms.approximation.dominating_set),
workx.linalg.laplacianmatrix), 393 129
laplacian_spectrum() (in module net- min_maximal_matching() (in module net-
workx.linalg.spectrum), 395 workx.algorithms.approximation.matching),
latapy_clustering() (in module net- 131
workx.algorithms.bipartite.cluster), 155 min_weighted_dominating_set() (in module net-
LCF_graph() (in module networkx.generators.small), 355 workx.algorithms.approximation.dominating_set),
lexicographic_product() (in module net- 129
workx.algorithms.operators.product), 306 min_weighted_vertex_cover() (in module net-
line_graph() (in module networkx.generators.line), 386 workx.algorithms.approximation.vertex_cover),
load_centrality() (in module net- 132
workx.algorithms.centrality), 183 minimum_cut() (in module networkx.algorithms.flow),
local_edge_connectivity() (in module net- 244
workx.algorithms.connectivity.connectivity), minimum_cut_value() (in module net-
211 workx.algorithms.flow), 246
local_node_connectivity() (in module net- minimum_edge_cut() (in module net-
workx.algorithms.connectivity.connectivity), workx.algorithms.connectivity.cuts), 217
213 minimum_node_cut() (in module net-
lollipop_graph() (in module networkx.generators.classic), workx.algorithms.connectivity.cuts), 218
353 minimum_spanning_edges() (in module net-
workx.algorithms.mst), 299
512 Index
NetworkX Reference, Release 1.9.1
Index 513
NetworkX Reference, Release 1.9.1
514 Index
NetworkX Reference, Release 1.9.1
Index 515
NetworkX Reference, Release 1.9.1
516 Index
NetworkX Reference, Release 1.9.1
Index 517
NetworkX Reference, Release 1.9.1
W
watts_strogatz_graph() (in module net-
workx.generators.random_graphs), 362
waxman_graph() (in module net-
workx.generators.geometric), 379
weakly_connected_component_subgraphs()
(in module net-
workx.algorithms.components.weakly_connected),
201
weakly_connected_components() (in module net-
workx.algorithms.components.weakly_connected),
201
weighted_choice() (in module net-
workx.utils.random_sequence), 479
518 Index