Networkx Reference
Networkx Reference
Networkx Reference
Release 2.3rc1.dev20190222214247
1 Introduction 1
1.1 NetworkX Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Graph Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Graph Reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.7 Data Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2 Graph types 7
2.1 Which graph class should I use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 Basic graph types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 Graph Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
3 Algorithms 129
3.1 Approximations and Heuristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
3.2 Assortativity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
3.3 Bipartite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
3.4 Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
3.5 Bridges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
3.6 Centrality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
3.7 Chains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
3.8 Chordal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
3.9 Clique . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
3.10 Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
3.11 Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
3.12 Communicability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
3.13 Communities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
3.14 Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
3.15 Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
3.16 Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
3.17 Covering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
3.18 Cycles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
3.19 Cuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
3.20 Directed Acyclic Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
3.21 Dispersion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
3.22 Distance Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
3.23 Distance-Regular Graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
3.24 Dominance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
3.25 Dominating Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
i
3.26 Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
3.27 Eulerian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
3.28 Flows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
3.29 Graphical degree sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
3.30 Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
3.31 Hybrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
3.32 Isolates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
3.33 Isomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
3.34 Link Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
3.35 Link Prediction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
3.36 Lowest Common Ancestor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
3.37 Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
3.38 Minors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
3.39 Maximal independent set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
3.40 Node Classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
3.41 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
3.42 Planarity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
3.43 Reciprocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
3.44 Rich Club . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
3.45 Shortest Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
3.46 Similarity Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
3.47 Simple Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
3.48 Similarity Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
3.49 s metric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
3.50 Sparsifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
3.51 Structural holes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
3.52 Swap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
3.53 Tournament . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
3.54 Traversal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
3.55 Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
3.56 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
3.57 Vitality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
3.58 Voronoi cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
3.59 Wiener index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
4 Functions 491
4.1 Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
4.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
4.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
4.4 Self loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
4.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
4.6 Freezing graph structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
ii
5.11 Geometric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
5.12 Line Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
5.13 Ego Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
5.14 Stochastic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
5.15 Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
5.16 Social Networks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
5.17 Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
5.18 Spectral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
5.19 Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
5.20 Non Isomorphic Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
5.21 Triads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
5.22 Joint Degree Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
5.23 Mycielski . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
10 Drawing 661
10.1 Matplotlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 661
10.2 Graphviz AGraph (dot) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
10.3 Graphviz with pydot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
10.4 Graph Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
11 Randomness 681
iii
12 Exceptions 683
12.1 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
13 Utilities 685
13.1 Helper Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
13.2 Data Structures and Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
13.3 Random Sequence Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
13.4 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
13.5 Cuthill-Mckee Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
13.6 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
14 Glossary 695
A Tutorial 697
A.1 Creating a graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
A.2 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
A.3 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
A.4 What to use as nodes and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
A.5 Accessing edges and neighbors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
A.6 Adding attributes to graphs, nodes, and edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
A.7 Directed graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
A.8 Multigraphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
A.9 Graph generators and graph operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
A.10 Analyzing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
A.11 Drawing graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Bibliography 707
Index 713
iv
CHAPTER
ONE
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 analyze 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)
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. Provides 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()
1
NetworkX Reference, Release 2.3rc1.dev20190222214247
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 dictio-
nary datastructures. The graph adjacency 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.
1.2 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 (𝑢, 𝑣) 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 clever users could design edge data attributes 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 be 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 by default to get the weight
for each edge.
Attributes can be assigned to an edge by using keyword/value pairs when adding edges. You can use any keyword to
name your attribute and can then query the edge data using 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.
2 Chapter 1. Introduction
NetworkX Reference, Release 2.3rc1.dev20190222214247
>>> elist = [(1, 2), (2, 3), (1, 4), (4, 2)]
>>> G.add_edges_from(elist)
>>> elist = [('a', 'b', 5.0), ('b', 'c', 3.0), ('a', 'c', 1.0), ('c', 'd', 7.3)]
>>> G.add_weighted_edges_from(elist)
Class views provide basic reporting of nodes, neighbors, edges and degree. These views provide iteration over the
properties as well as membership queries and data attribute lookup. The views refer to the graph data structure so
changes to the graph are reflected in the views. This is analogous to dictionary views in Python 3. If you want to
change the graph while iterating you will need to use e.g. for e in list(G.edges):. The views provide
set-like operations, e.g. union and intersection, as well as dict-like lookup and iteration of the data attributes us-
ing G.edges[u, v]['color'] and for e, datadict in G.edges.items():. Methods G.edges.
items() and G.edges.values() are familiar from python dicts. In addition G.edges.data() provides
specific attribute iteration e.g. for e, e_color in G.edges.data('color'):.
The basic graph relationship of an edge can be obtained in two ways. One can look for neighbors of a node or one can
look for edges. 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 choice of lookup notation like G[u] providing neighbors (adjacency) while edge
lookup is G.edges[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 undirected edges while neighbor reporting across all nodes will naturally report both
directions.
Any properties that are more complicated than edges, neighbors and degree are provided by functions. For exam-
ple nx.triangles(G, n) gives the number of triangles which include node n as a vertex. These functions are
1.5 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']
1.6 Drawing
While NetworkX is not designed as a network drawing 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 you provide via a dictionary
or the positions are computed with a layout function. The edges are lines between those dots.
4 Chapter 1. Introduction
NetworkX Reference, Release 2.3rc1.dev20190222214247
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. A view of the adjacency data structure is provided by the dict-like
object G.adj as e.g. for node, nbrsdict in G.adj.items():. The expression G[u][v] returns the
edge attribute dictionary itself. A dictionary of lists would have also been possible, but not allow 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 (𝐴, 𝐵) and (𝐵, 𝐶).
>>> G = nx.Graph()
>>> G.add_edge('A', 'B')
>>> G.add_edge('B', 'C')
>>> print(G.adj)
{'A': {'B': {}}, 'B': {'A': {}, 'C': {}}, 'C': {'B': {}}}
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 (G.succ) and one for predecessors (G.pred). For MultiGraph/MultiDiGraph
we use a dict-of-dicts-of-dicts-of-dicts1 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 provide two interfaces to the edge data attributes: adjacency and edges. So G[u][v]['width'] is the same
as G.edges[u, v]['width'].
>>> G = nx.Graph()
>>> G.add_edge(1, 2, color='red', weight=0.84, size=300)
>>> print(G[1][2]['size'])
300
>>> print(G.edges[1, 2]['color'])
red
• ;
• ;
• .
6 Chapter 1. Introduction
CHAPTER
TWO
GRAPH TYPES
Overview
7
NetworkX Reference, Release 2.3rc1.dev20190222214247
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.Graph()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
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,
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'}
Warning: we protect the graph data structure by making G.edges a read-only dict-like structure. However, you
can assign to attributes in e.g. G.edges[1, 2]. Thus, use 2 sets of brackets to add/change data attributes:
G.edges[1, 2]['weight'] = 4 (For multigraphs: MG.edges[u, v, key][name] = value).
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
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict G.adj or G.adjacency()
>>> for n, nbrsdict in G.adjacency():
... for nbr, eattr in nbrsdict.items():
... if 'weight' in eattr:
... # Do something useful with the edges
... pass
Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting typically provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. nodes.items(), nodes.
data('color'), nodes.data('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information
keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by
neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by
attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the
dict-like features should be maintained but extra features can be added. To replace one of the dicts create
a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The vari-
able names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory,
edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds edge data keyed by neighbor. It should require no arguments and return a dict-like object
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherit without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.
Examples
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.
Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.
Methods
networkx.Graph.__init__
Graph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
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:
convert()
Examples
networkx.Graph.add_node
Graph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
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.
networkx.Graph.add_nodes_from
Graph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (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 spec-
ified via keyword arguments.
See also:
add_node()
Examples
networkx.Graph.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
networkx.Graph.remove_nodes_from
Graph.remove_nodes_from(nodes)
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
networkx.Graph.add_edge
Notes
Examples
>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> G.edges[1, 2].update({0: 5})
networkx.Graph.add_edges_from
Graph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges must be given as as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a
dictionary containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:
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 an ebunch take precedence over attributes specified via keyword arguments.
Examples
networkx.Graph.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
networkx.Graph.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
networkx.Graph.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
networkx.Graph.update
Graph.update(edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also
take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword
nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> G.update(nx.complete_graph(range(4,10)))
>>> from itertools import combinations
>>> edges = ((u, v, {'power': u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225)
>>> nodes = [1000] # for singleton, use a container
>>> G.update(edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
>>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
See also:
networkx.Graph.clear
Graph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
networkx.Graph.nodes
Graph.nodes
A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node,
nodedata) 2-tuples and G.nodes[3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view G.nodes.data('foo') provides a dict-like interface to the foo attribute of each node.
G.nodes.data('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list(G.nodes(data='foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data('foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data('time'))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict(G.nodes(data='weight', default=1))
{0: 1, 1: 2, 2: 3}
networkx.Graph.__iter__
Graph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
networkx.Graph.has_node
Graph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
networkx.Graph.__contains__
Graph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
networkx.Graph.edges
Graph.edges
An EdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in G.edges.data('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type EdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
networkx.Graph.has_edge
Graph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True
networkx.Graph.get_edge_data
Graph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception is the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary
Examples
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']
>>> G[0][1]['weight'] = 7
>>> G[0][1]['weight']
7
>>> G[1][0]['weight']
7
networkx.Graph.neighbors
Graph.neighbors(n)
Returns an iterator over all neighbors of node n.
This is identical to iter(G[n])
Parameters n (node) – A node in the graph
Returns neighbors – An iterator over all neighbors of node n
Return type iterator
Raises NetworkXError – If the node n is not in the graph.
Examples
Notes
It is usually more convenient (and faster) to access the adjacency dictionary as G[n]:
networkx.Graph.adj
Graph.adj
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So G.adj[3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
networkx.Graph.__getitem__
Graph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
Examples
networkx.Graph.adjacency
Graph.adjacency()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
networkx.Graph.nbunch_iter
Graph.nbunch_iter(nbunch=None)
Returns an iterator over 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 (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
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.
networkx.Graph.order
Graph.order()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
networkx.Graph.number_of_nodes
Graph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
networkx.Graph.__len__
Graph.__len__()
Returns the number of nodes. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
Examples
networkx.Graph.degree
Graph.degree
A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_view (A DegreeView object capable of iterating (node, degree) pairs)
Examples
networkx.Graph.size
Graph.size(weight=None)
Returns the number of edges or total of all edge weights.
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
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Examples
networkx.Graph.number_of_edges
Graph.number_of_edges(u=None, v=None)
Returns 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 – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = nx.DiGraph()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1
networkx.Graph.copy
Graph.copy(as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
networkx.Graph.to_undirected
Graph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Parameters as_view (bool (optional, default=False)) – If True return a view of the original undi-
rected graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
See also:
Graph(), 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 = nx.DiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.
Examples
networkx.Graph.to_directed
Graph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type 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, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.
Examples
networkx.Graph.subgraph
Graph.subgraph(nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
networkx.Graph.edge_subgraph
Graph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
Overview
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.DiGraph()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
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,
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'}
Warning: we protect the graph data structure by making G.edges[1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. G.edges[1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: G.edges[1, 2]['weight'] = 4 (For multigraphs: MG.edges[u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict G.adj or G.adjacency()
Reporting:
Simple graph information is obtained using object-attributes and methods. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. nodes.items(), nodes.
data('color'), nodes.data('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The Graph class uses a dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adjacency information
keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds edge data keyed by
neighbor. The inner dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by
attribute names.
Each of these three dicts can be replaced in a subclass by a user defined dict-like object. In general, the
dict-like features should be maintained but extra features can be added. To replace one of the dicts create
a new graph class by changing the class(!) variable holding the factory for that dict-like structure. The vari-
able names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory, adjlist_outer_dict_factory,
edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, optional (default: dict)] Factory function to be used to create the adja-
cency list dict which holds edge data keyed by neighbor. It should require no arguments and return a
dict-like object
edge_attr_dict_factory [function, optional (default: dict)] Factory function to be used to create the edge at-
tribute dict which holds attribute values keyed by attribute name. It should require no arguments and return
a dict-like object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.
Examples
Create a low memory graph class that effectively disallows edge attributes by using a single attribute dict for all
edges. This reduces the memory used, but you lose edge attributes.
Please see ordered for more examples of creating graph subclasses by overwriting the base class dict with
a dictionary-like object.
Methods
networkx.DiGraph.__init__
DiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph (optional, default: None)) – Data to initialize graph. If
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:
convert()
Examples
networkx.DiGraph.add_node
DiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
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.
networkx.DiGraph.add_nodes_from
DiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (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 spec-
ified via keyword arguments.
See also:
add_node()
Examples
networkx.DiGraph.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
networkx.DiGraph.remove_nodes_from
DiGraph.remove_nodes_from(nodes)
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
networkx.DiGraph.add_edge
Notes
Examples
>>> G.add_edge(1, 2)
>>> G[1][2].update({0: 5})
>>> G.edges[1, 2].update({0: 5})
networkx.DiGraph.add_edges_from
DiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to the
graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary
containing edge data.
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
See also:
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 an ebunch take precedence over attributes specified via keyword arguments.
Examples
networkx.DiGraph.add_weighted_edges_from
• ebunch_to_add (container of edges) – Each edge given in the list or container will be added
to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
• weight (string, optional (default= ‘weight’)) – The attribute name for the edge weights to
be added.
• attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update
for all edges.
See also:
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph,
duplicate edges are stored.
Examples
networkx.DiGraph.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 – If there is not an edge between u and v.
See also:
Examples
networkx.DiGraph.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
networkx.DiGraph.update
DiGraph.update(edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also
take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword
nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> G.update(nx.complete_graph(range(4,10)))
>>> from itertools import combinations
>>> edges = ((u, v, {'power': u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225)
(continues on next page)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
>>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
See also:
networkx.DiGraph.clear
DiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
networkx.DiGraph.nodes
DiGraph.nodes
A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node,
nodedata) 2-tuples and G.nodes[3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view G.nodes.data('foo') provides a dict-like interface to the foo attribute of each node.
G.nodes.data('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list(G.nodes(data='foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data('foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data('time'))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict(G.nodes(data='weight', default=1))
{0: 1, 1: 2, 2: 3}
networkx.DiGraph.__iter__
DiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
networkx.DiGraph.has_node
DiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
networkx.DiGraph.__contains__
DiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
networkx.DiGraph.edges
DiGraph.edges
An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in G.edges.data('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
networkx.DiGraph.out_edges
DiGraph.out_edges
An OutEdgeView of the DiGraph as G.edges or G.edges().
edges(self, nbunch=None, data=False, default=None)
The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in G.edges.data('color', default='red'): iterates
through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges,
but can also be used for attribute lookup as edges[u, v]['foo'].
Return type OutEdgeView
See also:
in_edges, out_edges
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
networkx.DiGraph.in_edges
DiGraph.in_edges
An InEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, default=None):
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of
edges, but can also be used for attribute lookup as edges[u, v]['foo'].
Return type InEdgeView
See also:
edges
networkx.DiGraph.has_edge
DiGraph.has_edge(u, v)
Returns True if the edge (u, v) is in the graph.
This is the same as v in G[u] without KeyError exceptions.
Parameters u, v (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable
(and not None) Python objects.
Returns edge_ind – True if edge is in the graph, False otherwise.
Return type bool
Examples
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives KeyError if 0 not in G
True
networkx.DiGraph.get_edge_data
DiGraph.get_edge_data(u, v, default=None)
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v] except the default is returned instead of an exception is the edge doesn’t exist.
Parameters
• u, v (nodes)
• default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
Returns edge_dict – The edge attribute dictionary.
Return type dictionary
Examples
Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v]['foo']
>>> G[0][1]['weight'] = 7
>>> G[0][1]['weight']
7
>>> G[1][0]['weight']
7
networkx.DiGraph.neighbors
DiGraph.neighbors(n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Notes
networkx.DiGraph.adj
DiGraph.adj
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edge-data-dict. So G.adj[3][2]['color'] = 'blue' sets the color of the edge (3,
2) to "blue".
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
networkx.DiGraph.__getitem__
DiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
Examples
networkx.DiGraph.successors
DiGraph.successors(n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Notes
networkx.DiGraph.succ
DiGraph.succ
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So G.succ[3][2]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over G.succ behaves like a dict. Useful idioms include for nbr, datadict in G.succ[n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.succ[node].
data('foo'): and a default can be set via a default argument to the data method.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, G.adj is identical to G.succ.
networkx.DiGraph.predecessors
DiGraph.predecessors(n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()
networkx.DiGraph.pred
DiGraph.pred
Graph adjacency object holding the predecessors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is
keyed by neighbor to the edge-data-dict. So G.pred[2][3]['color'] = 'blue' sets the color of the
edge (3, 2) to "blue".
Iterating over G.pred behaves like a dict. Useful idioms include for nbr, datadict in G.pred[n].
items():. A data-view not provided by dicts also exists: for nbr, foovalue in G.pred[node].
data('foo'): A default can be set via a default argument to the data method.
networkx.DiGraph.adjacency
DiGraph.adjacency()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
networkx.DiGraph.nbunch_iter
DiGraph.nbunch_iter(nbunch=None)
Returns an iterator over 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 (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
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.
networkx.DiGraph.order
DiGraph.order()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
networkx.DiGraph.number_of_nodes
DiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
networkx.DiGraph.__len__
DiGraph.__len__()
Returns the number of nodes. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
Examples
networkx.DiGraph.degree
DiGraph.degree
A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
in_degree, out_degree
Examples
networkx.DiGraph.in_degree
DiGraph.in_degree
An InDegreeView for (node, in_degree) or in_degree for single node.
The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single node is requested
• deg (int) – In-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree
Examples
>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]
networkx.DiGraph.out_degree
DiGraph.out_degree
An OutDegreeView for (node, out_degree)
The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of
the edge weights for edges incident to that node.
This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single node is requested
• deg (int) – Out-degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree
Examples
>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]
networkx.DiGraph.size
DiGraph.size(weight=None)
Returns the number of edges or total of all edge weights.
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
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()
Examples
networkx.DiGraph.number_of_edges
DiGraph.number_of_edges(u=None, v=None)
Returns 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 – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected graphs, this method counts the total number of edges in the graph:
>>> G = nx.path_graph(4)
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
1
For directed graphs, this method can count the total number of directed edges from u to v:
>>> G = nx.DiGraph()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1
networkx.DiGraph.copy
DiGraph.copy(as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
networkx.DiGraph.to_undirected
DiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – 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.
Return type Graph
See also:
Graph(), copy(), add_edge(), add_edges_from()
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, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not
transfer to the Graph created by this method.
Examples
networkx.DiGraph.to_directed
DiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type 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, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not
transfer to the DiGraph created by this method.
Examples
networkx.DiGraph.subgraph
DiGraph.subgraph(nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
networkx.DiGraph.edge_subgraph
DiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
networkx.DiGraph.reverse
DiGraph.reverse(copy=True)
Returns 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 re-
versed edges. If False, the reverse graph is created using a view of the original graph.
Overview
Examples
Create an empty graph structure (a “null graph”) with no nodes and no edges.
>>> G = nx.MultiGraph()
>>> G.add_node(1)
Add the nodes from any container (a list, dict, set or even the lines from a file or the nodes from another graph).
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,
a list of edges,
or a collection of 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.
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'}
Warning: we protect the graph data structure by making G.edges[1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. G.edges[1, 2]. Thus, use 2 sets of brackets to add/change data
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are reported as an
adjacency-dict G.adj or G.adjacency().
Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. nodes.items(), nodes.
data('color'), nodes.data('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
For details on these and other miscellaneous methods, see below.
Subclasses (Advanced):
The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure. The outer dict (node_dict) holds adja-
cency information keyed by node. The next dict (adjlist_dict) represents the adjacency information and holds
edge_key dicts keyed by neighbor. The edge_key dict holds each edge_attr dict keyed by edge key. The inner
dict (edge_attr_dict) represents the edge data and holds edge attribute values keyed by attribute names.
Each of these four dicts in the dict-of-dict-of-dict-of-dict structure can be replaced by a user defined dict-like
object. In general, the dict-like features should be maintained but extra features can be added. To replace
one of the dicts create a new graph class by changing the class(!) variable holding the factory for that dict-
like structure. The variable names are node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory and graph_attr_dict_factory.
node_dict_factory [function, (default: dict)] Factory function to be used to create the dict containing node
attributes, keyed by node id. It should require no arguments and return a dict-like object
node_attr_dict_factory: function, (default: dict) Factory function to be used to create the node attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object
adjlist_outer_dict_factory [function, (default: dict)] Factory function to be used to create the outer-most dict
in the data structure that holds adjacency info keyed by node. It should require no arguments and return a
dict-like object.
adjlist_inner_dict_factory [function, (default: dict)] Factory function to be used to create the adjacency list
dict which holds multiedge key dicts keyed by neighbor. It should require no arguments and return a
dict-like object.
edge_key_dict_factory [function, (default: dict)] Factory function to be used to create the edge key dict which
holds edge data keyed by edge key. It should require no arguments and return a dict-like object.
edge_attr_dict_factory [function, (default: dict)] Factory function to be used to create the edge attribute dict
which holds attribute values keyed by attribute name. It should require no arguments and return a dict-like
object.
graph_attr_dict_factory [function, (default: dict)] Factory function to be used to create the graph attribute
dict which holds attribute values keyed by attribute name. It should require no arguments and return a
dict-like object.
Typically, if your extension doesn’t impact the data structure all methods will inherited without issue except:
to_directed/to_undirected. By default these methods create a DiGraph/Graph class and you probably
want them to create your extension of a DiGraph/Graph. To facilitate this we define two class variables that you
can set in your subclass.
to_directed_class [callable, (default: DiGraph or MultiDiGraph)] Class to create a new graph structure in the
to_directed method. If None, a NetworkX class (DiGraph or MultiDiGraph) is used.
to_undirected_class [callable, (default: Graph or MultiGraph)] Class to create a new graph structure in the
to_undirected method. If None, a NetworkX class (Graph or MultiGraph) is used.
Examples
Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.
Methods
networkx.MultiGraph.__init__
MultiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_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:
convert()
Examples
networkx.MultiGraph.add_node
MultiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
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.
networkx.MultiGraph.add_nodes_from
MultiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (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 spec-
ified via keyword arguments.
See also:
add_node()
Examples
networkx.MultiGraph.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
networkx.MultiGraph.remove_nodes_from
MultiGraph.remove_nodes_from(nodes)
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
networkx.MultiGraph.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.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
>>> G = nx.MultiGraph()
>>> e = (1, 2)
>>> ekey = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from( [(1, 2)] ) # add edges from iterable container
[2]
networkx.MultiGraph.add_edges_from
MultiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or
– 4-tuples (u, v, k, d) for an edge with data and key k
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
Return type A list of edge keys assigned to the edges in ebunch.
See also:
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 an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
networkx.MultiGraph.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
networkx.MultiGraph.new_edge_key
MultiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
Notes
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int
networkx.MultiGraph.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 be-
tween a pair of nodes. If None remove a single (arbitrary) 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()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e) # unpacks e from an edge tuple
networkx.MultiGraph.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
>>> G = nx.MultiGraph()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list(G.edges())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list(G.edges) # now empty graph
[]
networkx.MultiGraph.update
MultiGraph.update(edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also
take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword
nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> G.update(nx.complete_graph(range(4,10)))
>>> from itertools import combinations
>>> edges = ((u, v, {'power': u * v})
(continues on next page)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
>>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
See also:
networkx.MultiGraph.clear
MultiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
networkx.MultiGraph.nodes
MultiGraph.nodes
A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node,
nodedata) 2-tuples and G.nodes[3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view G.nodes.data('foo') provides a dict-like interface to the foo attribute of each node.
G.nodes.data('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list(G.nodes(data='foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data('foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data('time'))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
(continues on next page)
networkx.MultiGraph.__iter__
MultiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Returns niter – An iterator over all nodes in the graph.
Return type iterator
Examples
networkx.MultiGraph.has_node
MultiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
networkx.MultiGraph.__contains__
MultiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
networkx.MultiGraph.edges
MultiGraph.edges
Returns an iterator over the edges.
edges(self, nbunch=None, data=False, keys=False, default=None)
The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called,
it also provides an EdgeDataView object which allows control of access to edge attributes (but does not pro-
vide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute for
edge (u, v) while for (u, v, c) in G.edges(data='color', default='red'): iterates
through all the edges yielding the color attribute.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type MultiEdgeView
Notes
Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.
Examples
networkx.MultiGraph.has_edge
MultiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
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 – True if edge is in the graph, False otherwise.
Return type bool
Examples
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True
networkx.MultiGraph.get_edge_data
Examples
Warning: we protect the graph data structure by making G.edges and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. G.edges[1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.
>>> G[0][1]['a']['weight'] = 10
>>> G.edges[0, 1, 'a']['weight'] = 10
>>> G[0][1]['a']['weight']
10
>>> G.edges[1, 0, 'a']['weight']
10
networkx.MultiGraph.neighbors
MultiGraph.neighbors(n)
Returns an iterator over all neighbors of node n.
Examples
Notes
It is usually more convenient (and faster) to access the adjacency dictionary as G[n]:
networkx.MultiGraph.adj
MultiGraph.adj
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-data-dict. So G.adj[3][2][0]['color'] = 'blue' sets the color of the
edge (3, 2, 0) to "blue".
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, nbrdict in G.adj[n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
networkx.MultiGraph.__getitem__
MultiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
Examples
networkx.MultiGraph.adjacency
MultiGraph.adjacency()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
networkx.MultiGraph.nbunch_iter
MultiGraph.nbunch_iter(nbunch=None)
Returns an iterator over 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 (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
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.
networkx.MultiGraph.order
MultiGraph.order()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
networkx.MultiGraph.number_of_nodes
MultiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
networkx.MultiGraph.__len__
MultiGraph.__len__()
Returns the number of nodes. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
Examples
networkx.MultiGraph.degree
MultiGraph.degree
A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single node is requested
• deg (int) – Degree of the node, if a single node is passed as argument.
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
Examples
networkx.MultiGraph.size
MultiGraph.size(weight=None)
Returns the number of edges or total of all edge weights.
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
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Examples
networkx.MultiGraph.number_of_edges
MultiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=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 – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = nx.MultiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1
networkx.MultiGraph.copy
MultiGraph.copy(as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
networkx.MultiGraph.to_undirected
MultiGraph.to_undirected(as_view=False)
Returns an undirected copy of the graph.
Returns G – A deepcopy of the graph.
Return type Graph/MultiGraph
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 = nx.MultiGraph(D) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed MultiiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiGraph created by this method.
Examples
networkx.MultiGraph.to_directed
MultiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph
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, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.
Examples
networkx.MultiGraph.subgraph
MultiGraph.subgraph(nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
networkx.MultiGraph.edge_subgraph
MultiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
Overview
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.path_graph(10)
>>> 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,
>>> key = G.add_edge(1, 2)
a list of edges,
>>> keys = G.add_edges_from([(1, 2), (1, 3)])
or a collection of edges,
>>> keys = 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.
>>> keys = G.add_edges_from([(4,5,dict(route=282)), (4,5,dict(route=37))])
>>> G[4]
AdjacencyView({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'}
Warning: we protect the graph data structure by making G.edges[1, 2] a read-only dict-like structure.
However, you can assign to attributes in e.g. G.edges[1, 2]. Thus, use 2 sets of brackets to add/change data
attributes: G.edges[1, 2]['weight'] = 4 (For multigraphs: MG.edges[u, v, key][name] =
value).
Shortcuts:
Many common graph features allow python syntax to speed reporting.
Often the best way to traverse all edges of a graph is via the neighbors. The neighbors are available as an
adjacency-view G.adj object or via the method G.adjacency().
Reporting:
Simple graph information is obtained using methods and object-attributes. Reporting usually provides
views instead of containers to reduce memory usage. The views update as the graph is updated simi-
larly to dict-views. The objects nodes, `edges and adj provide access to data attributes via lookup
(e.g. nodes[n], `edges[u, v], adj[u][v]) and iteration (e.g. nodes.items(), nodes.
data('color'), nodes.data('color', default='blue') and similarly for edges) Views exist
for nodes, edges, neighbors()/adj and degree.
Examples
Please see ordered for examples of creating graph subclasses by overwriting the base class dict with a
dictionary-like object.
Methods
networkx.MultiDiGraph.__init__
MultiDiGraph.__init__(incoming_graph_data=None, **attr)
Initialize a graph with edges, name, or graph attributes.
Parameters
• incoming_graph_data (input graph) – Data to initialize graph. If incom-
ing_graph_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:
convert()
Examples
networkx.MultiDiGraph.add_node
MultiDiGraph.add_node(node_for_adding, **attr)
Add a single node node_for_adding and update node attributes.
Parameters
• node_for_adding (node) – A node can be any hashable Python object except None.
• attr (keyword arguments, optional) – Set or change node attributes using key=value.
See also:
add_nodes_from()
Examples
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.
networkx.MultiDiGraph.add_nodes_from
MultiDiGraph.add_nodes_from(nodes_for_adding, **attr)
Add multiple nodes.
Parameters
• nodes_for_adding (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 spec-
ified via keyword arguments.
See also:
add_node()
Examples
networkx.MultiDiGraph.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
networkx.MultiDiGraph.remove_nodes_from
MultiDiGraph.remove_nodes_from(nodes)
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
networkx.MultiDiGraph.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.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
>>> G = nx.MultiDiGraph()
>>> e = (1, 2)
>>> key = G.add_edge(1, 2) # explicit two-node form
>>> G.add_edge(*e) # single edge as tuple of two nodes
1
>>> G.add_edges_from( [(1, 2)] ) # add edges from iterable container
[2]
networkx.MultiDiGraph.add_edges_from
MultiDiGraph.add_edges_from(ebunch_to_add, **attr)
Add all the edges in ebunch_to_add.
Parameters
• ebunch_to_add (container of edges) – Each edge given in the container will be added to
the graph. The edges can be:
– 2-tuples (u, v) or
– 3-tuples (u, v, d) for an edge data dict d, or
– 3-tuples (u, v, k) for not iterable key k, or
– 4-tuples (u, v, k, d) for an edge with data and key k
• attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using
keyword arguments.
Returns
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 an ebunch take precedence over attributes specified via keyword arguments.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclass-
ing the base class and providing a custom new_edge_key() method.
Examples
networkx.MultiDiGraph.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
networkx.MultiDiGraph.new_edge_key
MultiDiGraph.new_edge_key(u, v)
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
Notes
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased
if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further
new_edge_keys may not be in this order.
Parameters u, v (nodes)
Returns key
Return type int
networkx.MultiDiGraph.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 be-
tween a pair of nodes. If None remove a single (arbitrary) 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()
>>> nx.add_path(G, [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)]) # key_list returned
[0, 1, 2]
>>> G.remove_edge(1, 2) # remove a single (arbitrary) edge
>>> G = nx.MultiDiGraph()
>>> G.add_edge(1, 2, key='first')
'first'
>>> G.add_edge(1, 2, key='second')
'second'
>>> G.remove_edge(1, 2, key='second')
networkx.MultiDiGraph.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
>>> G = nx.MultiGraph()
>>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
>>> G.remove_edges_from([(1, 2), (1, 2)])
>>> list(G.edges())
[(1, 2)]
>>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
>>> list(G.edges) # now empty graph
[]
networkx.MultiDiGraph.update
MultiDiGraph.update(edges=None, nodes=None)
Update the graph using nodes/edges/graphs as input.
Like dict.update, this method takes a graph as input, adding the graph’s noes and edges to this graph. It can also
take two inputs: edges and nodes. Finally it can take either edges or nodes. To specify only nodes the keyword
nodes must be used.
The collections of edges and nodes are treated similarly to the add_edges_from/add_nodes_from methods.
When iterated, they should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
Parameters
• edges (Graph object, collection of edges, or None) – The first parameter can be a graph or
some edges. If it has attributes nodes and edges, then it is taken to be a Graph-like object
and those attributes are used as collections of nodes and edges to be added to the graph. If
the first parameter does not have those attributes, it is treated as a collection of edges and
added to the graph. If the first argument is None, no edges are added.
• nodes (collection of nodes, or None) – The second parameter is treated as a collection of
nodes to be added to the graph unless it is None. If edges is None and nodes is
None an exception is raised. If the first parameter is a Graph, then nodes is ignored.
Examples
>>> G = nx.path_graph(5)
>>> G.update(nx.complete_graph(range(4,10)))
>>> from itertools import combinations
>>> edges = ((u, v, {'power': u * v})
... for u, v in combinations(range(10, 20), 2)
... if u * v < 225)
>>> nodes = [1000] # for singleton, use a container
>>> G.update(edges, nodes)
Notes
It you want to update the graph using an adjacency structure it is straightforward to obtain the edges/nodes from
adjacency. The following examples provide common cases, your adjacency may be slightly different and require
tweaks of these examples.
>>> # dict-of-set/list/tuple
>>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
>>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
>>> G.update(edges=e, nodes=adj)
>>> DG = nx.DiGraph()
>>> # dict-of-dict-of-attribute
>>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
>>> # dict-of-dict-of-dict
>>> adj = {1: {2: {'weight': 1.3}, 3: {'color': 0.7, 'weight':1.2}}}
>>> e = [(u, v, {'weight': d}) for u, nbrs in adj.items()
... for v, d in nbrs.items()]
>>> DG.update(edges=e, nodes=adj)
See also:
networkx.MultiDiGraph.clear
MultiDiGraph.clear()
Remove all nodes and edges from the graph.
This also removes the name, and all graph, node, and edge attributes.
Examples
networkx.MultiDiGraph.nodes
MultiDiGraph.nodes
A NodeView of the Graph as G.nodes or G.nodes().
Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.
nodes(data='color', default=None) to return a NodeDataView which reports specific node data
but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node,
nodedata) 2-tuples and G.nodes[3]['foo'] providing the value of the foo attribute for node 3. In
addition, a view G.nodes.data('foo') provides a dict-like interface to the foo attribute of each node.
G.nodes.data('foo', default=1) provides a default for nodes that do not have attribute foo.
Parameters
• data (string or bool, optional (default=False)) – The node attribute returned in 2-tuple (n,
ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the
nodes n.
• default (value, optional (default=None)) – Value used for nodes that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns
Allows set-like operations over the nodes as well as node attribute dict lookup and calling to
get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A
NodeView iterates over n and includes set operations.
When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node,
attribute value) where the attribute is specified in data. If data is True then the attribute becomes
the entire data dictionary.
Return type NodeView
Notes
If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).
Examples
There are two simple ways of getting a list of all nodes in the graph:
>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]
>>> list(G.nodes(data='foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data('foo'))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data='time'))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data('time'))
[(0, None), (1, '5pm'), (2, None)]
If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create
a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never
None:
>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict(G.nodes(data='weight', default=1))
{0: 1, 1: 2, 2: 3}
networkx.MultiDiGraph.__iter__
MultiDiGraph.__iter__()
Iterate over the nodes. Use: ‘for n in G’.
Examples
networkx.MultiDiGraph.has_node
MultiDiGraph.has_node(n)
Returns True if the graph contains the node n.
Identical to n in G
Parameters n (node)
Examples
>>> 0 in G
True
networkx.MultiDiGraph.__contains__
MultiDiGraph.__contains__(n)
Returns True if n is a node, False otherwise. Use: ‘n in G’.
Examples
networkx.MultiDiGraph.edges
MultiDiGraph.edges
An OutMultiEdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in G.edges(data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView
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()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges()]
[(0, 1), (1, 2), (2, 3)]
>>> list(G.edges(data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list(G.edges(data='weight', default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list(G.edges(keys=True)) # default keys are integers
[(0, 1, 0), (1, 2, 0), (2, 3, 0)]
>>> list(G.edges(data=True, keys=True))
[(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]
>>> list(G.edges(data='weight', default=1, keys=True))
[(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]
>>> list(G.edges([0, 2]))
[(0, 1), (2, 3)]
>>> list(G.edges(0))
[(0, 1)]
See also:
in_edges, out_edges
networkx.MultiDiGraph.out_edges
MultiDiGraph.out_edges
An OutMultiEdgeView of the Graph as G.edges or G.edges().
edges(self, nbunch=None, data=False, keys=False, default=None)
The OutMultiEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When
called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not
provide set-like operations). Hence, G.edges[u, v]['color'] provides the value of the color attribute
for edge (u, v) while for (u, v, c) in G.edges(data='color', default='red'): iter-
ates through all the edges yielding the color attribute with default 'red' if no color attribute exists.
Edges are returned as tuples with optional data and keys in the order (node, neighbor, key, data).
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns edges – A view of edge attributes, usually it iterates over (u, v) (u, v, k) or (u, v, k, d) tuples
of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type EdgeView
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()
>>> nx.add_path(G, [0, 1, 2])
>>> key = G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges()]
[(0, 1), (1, 2), (2, 3)]
>>> list(G.edges(data=True)) # default data is {} (empty dict)
[(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})]
>>> list(G.edges(data='weight', default=1))
[(0, 1, 1), (1, 2, 1), (2, 3, 5)]
>>> list(G.edges(keys=True)) # default keys are integers
[(0, 1, 0), (1, 2, 0), (2, 3, 0)]
>>> list(G.edges(data=True, keys=True))
[(0, 1, 0, {}), (1, 2, 0, {}), (2, 3, 0, {'weight': 5})]
>>> list(G.edges(data='weight', default=1, keys=True))
[(0, 1, 0, 1), (1, 2, 0, 1), (2, 3, 0, 5)]
>>> list(G.edges([0, 2]))
[(0, 1), (2, 3)]
(continues on next page)
See also:
in_edges, out_edges
networkx.MultiDiGraph.in_edges
MultiDiGraph.in_edges
An InMultiEdgeView of the Graph as G.in_edges or G.in_edges().
in_edges(self, nbunch=None, data=False, keys=False, default=None)
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• data (string or bool, optional (default=False)) – The edge attribute returned in 3-tuple (u, v,
ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple
(u, v).
• keys (bool, optional (default=False)) – If True, return edge keys with each edge.
• default (value, optional (default=None)) – Value used for edges that don’t have the re-
quested attribute. Only relevant if data is not True or False.
Returns in_edges – A view of edge attributes, usually it iterates over (u, v) or (u, v, k) or (u, v, k, d)
tuples of edges, but can also be used for attribute lookup as edges[u, v, k]['foo'].
Return type InMultiEdgeView
See also:
edges
networkx.MultiDiGraph.has_edge
MultiDiGraph.has_edge(u, v, key=None)
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
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 – True if edge is in the graph, False otherwise.
Return type bool
Examples
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G.has_edge(0, 1)
True
>>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
True
networkx.MultiDiGraph.get_edge_data
Examples
Warning: we protect the graph data structure by making G.edges and G[1][2] read-only dict-like structures.
However, you can assign values to attributes in e.g. G.edges[1, 2, 'a'] or G[1][2]['a'] using an
additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an
edge.
>>> G[0][1]['a']['weight'] = 10
>>> G.edges[0, 1, 'a']['weight'] = 10
>>> G[0][1]['a']['weight']
10
>>> G.edges[1, 0, 'a']['weight']
10
networkx.MultiDiGraph.neighbors
MultiDiGraph.neighbors(n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
networkx.MultiDiGraph.adj
MultiDiGraph.adj
Graph adjacency object holding the neighbors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So G.adj[3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
For directed graphs, G.adj holds outgoing (successor) info.
networkx.MultiDiGraph.__getitem__
MultiDiGraph.__getitem__(n)
Returns a dict of neighbors of node n. Use: ‘G[n]’.
Parameters n (node) – A node in the graph.
Returns adj_dict – The adjacency dictionary for nodes connected to n.
Return type dictionary
Notes
G[n] is the same as G.adj[n] and similar to G.neighbors(n) (which is an iterator over G.adj[n])
Examples
networkx.MultiDiGraph.successors
MultiDiGraph.successors(n)
Returns an iterator over successor nodes of n.
A successor of n is a node m such that there exists a directed edge from n to m.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
predecessors()
Notes
networkx.MultiDiGraph.succ
MultiDiGraph.succ
Graph adjacency object holding the successors of each node.
This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed
by neighbor to the edgekey-dict. So G.adj[3][2][0]['color'] = 'blue' sets the color of the edge
(3, 2, 0) to "blue".
Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].
items():.
The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in
G[node].data('foo', default=1): works.
networkx.MultiDiGraph.predecessors
MultiDiGraph.predecessors(n)
Returns an iterator over predecessor nodes of n.
A predecessor of n is a node m such that there exists a directed edge from m to n.
Parameters n (node) – A node in the graph
Raises NetworkXError – If n is not in the graph.
See also:
successors()
networkx.MultiDiGraph.adjacency
MultiDiGraph.adjacency()
Returns an iterator over (node, adjacency dict) tuples for all nodes.
For directed graphs, only outgoing neighbors/adjacencies are included.
Returns adj_iter – An iterator over (node, adjacency dictionary) for all nodes in the graph.
Return type iterator
Examples
networkx.MultiDiGraph.nbunch_iter
MultiDiGraph.nbunch_iter(nbunch=None)
Returns an iterator over 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 (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
Returns niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None,
iterate over all nodes in the graph.
Return type iterator
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.
networkx.MultiDiGraph.order
MultiDiGraph.order()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
number_of_nodes(), __len__()
networkx.MultiDiGraph.number_of_nodes
MultiDiGraph.number_of_nodes()
Returns the number of nodes in the graph.
Returns nnodes – The number of nodes in the graph.
Return type int
See also:
order(), __len__()
Examples
networkx.MultiDiGraph.__len__
MultiDiGraph.__len__()
Returns the number of nodes. Use: ‘len(G)’.
Returns nnodes – The number of nodes in the graph.
Return type int
Examples
networkx.MultiDiGraph.degree
MultiDiGraph.degree
A DegreeView for the Graph as G.degree or G.degree().
The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge
weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The name of an 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
• If a single nodes is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, degree).
See also:
out_degree, in_degree
Examples
>>> G = nx.MultiDiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.degree(0) # node 0 with degree 1
1
>>> list(G.degree([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]
networkx.MultiDiGraph.in_degree
MultiDiGraph.in_degree
A DegreeView for (node, in_degree) or in_degree for single node.
The node in-degree is the number of edges pointing in to the node. The weighted node degree is the sum of the
edge weights for edges incident to that node.
This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical 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
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, in-degree).
See also:
degree, out_degree
Examples
>>> G = nx.MultiDiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0) # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]
networkx.MultiDiGraph.out_degree
MultiDiGraph.out_degree
Returns an iterator for (node, out-degree) or out-degree for single node.
out_degree(self, nbunch=None, weight=None)
The node out-degree is the number of edges pointing out of the node. This function returns the out-degree for a
single node or an iterator for a bunch of nodes or if nothing is passed as argument.
Parameters
• nbunch (single node, container, or all nodes (default= all nodes)) – The view will only
report edges incident to these nodes.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1. The degree is the sum of
the edge weights.
Returns
• If a single node is requested
• deg (int) – Degree of the node
• OR if multiple nodes are requested
• nd_iter (iterator) – The iterator returns two-tuples of (node, out-degree).
See also:
degree, in_degree
Examples
>>> G = nx.MultiDiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0) # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]
networkx.MultiDiGraph.size
MultiDiGraph.size(weight=None)
Returns the number of edges or total of all edge weights.
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
size – The number of edges or (if weight keyword is provided) the total weight sum.
If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are
more general).
Return type numeric
See also:
number_of_edges()
Examples
networkx.MultiDiGraph.number_of_edges
MultiDiGraph.number_of_edges(u=None, v=None)
Returns the number of edges between two nodes.
Parameters u, v (nodes, optional (Gefault=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 – The number of edges in the graph. If nodes u and v are specified return the
number of edges between those nodes. If the graph is directed, this only returns the number of
edges from u to v.
Return type int
See also:
size()
Examples
For undirected multigraphs, this method counts the total number of edges in the graph:
>>> G = nx.MultiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
[0, 1, 0]
>>> G.number_of_edges()
3
If you specify two nodes, this counts the total number of edges joining the two nodes:
>>> G.number_of_edges(0, 1)
2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = nx.MultiDiGraph()
>>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
[0, 1, 0]
>>> G.number_of_edges(0, 1)
2
>>> G.number_of_edges(1, 0)
1
networkx.MultiDiGraph.copy
MultiDiGraph.copy(as_view=False)
Returns a copy of the graph.
The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an
attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for
new containers.
If as_view is True then a view is returned instead of a copy.
Notes
All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four
types of copies of a graph that people might want.
Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might
contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s
copy.deepcopy)
Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph at-
tribute dicts are references to those in the original graph. This saves time and memory but could cause confusion
if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this
level of shallow copy.
Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the
attributes. That is, any attributes that are containers are shared between the new graph and the original. This is
exactly what dict.copy() provides. You can obtain this style copy using:
>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)
Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The
resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not
enabled. Instead use:
>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)
View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy
of the original structure without requiring any memory for copying the information.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Parameters as_view (bool, optional (default=False)) – If True, the returned graph-view provides a
read-only view of the original graph without actually copying any data.
Returns G – A copy of the graph.
Return type Graph
See also:
Examples
networkx.MultiDiGraph.to_undirected
MultiDiGraph.to_undirected(reciprocal=False, as_view=False)
Returns an undirected representation of the digraph.
Parameters
• reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the
original digraph.
• as_view (bool (optional, default=False)) – If True return an undirected view of the original
directed graph.
Returns G – 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.
Return type MultiGraph
See also:
MultiGraph(), 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 D=MultiiGraph(G) which returns a shallow copy of the data.
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed MultiDiGraph to use dict-like objects in the data structure, those changes do
not transfer to the MultiGraph created by this method.
Examples
networkx.MultiDiGraph.to_directed
MultiDiGraph.to_directed(as_view=False)
Returns a directed representation of the graph.
Returns G – A directed graph with the same name, same nodes, and with each edge (u, v, data)
replaced by two directed edges (u, v, data) and (v, u, data).
Return type MultiDiGraph
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, https://docs.python.org/2/library/
copy.html.
Warning: If you have subclassed MultiGraph to use dict-like objects in the data structure, those changes do not
transfer to the MultiDiGraph created by this method.
Examples
networkx.MultiDiGraph.subgraph
MultiDiGraph.subgraph(nodes)
Returns a SubGraph view of the subgraph induced on nodes.
The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.
Parameters nodes (list, iterable) – A container of nodes which will be iterated through once.
Returns G – A subgraph view of the graph. The graph structure cannot be changed but node/edge
attributes can and are shared with the original graph.
Return type SubGraph View
Notes
The graph, edge and node attributes are shared with the original graph. Changes to the graph structure is ruled
out by the view, but changes to attributes are reflected in the original graph.
To create a subgraph with its own copy of the edge/node attributes use: G.subgraph(nodes).copy()
For an inplace reduction of a graph to a subgraph you can remove nodes: G.remove_nodes_from([n for n in G
if n not in set(nodes)])
Subgraph views are sometimes NOT what you want. In most cases where you want to do more than simply look
at the induced edges, it makes more sense to just create the subgraph as its own graph with code like:
Examples
networkx.MultiDiGraph.edge_subgraph
MultiDiGraph.edge_subgraph(edges)
Returns the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any one of those edges.
Parameters edges (iterable) – An iterable of edges in this graph.
Returns G – An edge-induced subgraph of this graph with the same edge attributes.
Return type Graph
Notes
The graph, edge, and node attributes in the returned subgraph view are references to the corresponding attributes
in the original graph. The view is read-only.
To create a full graph version of the subgraph with its own copy of the edge or node attributes, use:
>>> G.edge_subgraph(edges).copy()
Examples
>>> G = nx.path_graph(5)
>>> H = G.edge_subgraph([(0, 1), (3, 4)])
>>> list(H.nodes)
[0, 1, 3, 4]
>>> list(H.edges)
[(0, 1), (3, 4)]
networkx.MultiDiGraph.reverse
MultiDiGraph.reverse(copy=True)
Returns 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 re-
versed edges. If False, the reverse graph is created using a view of the original graph.
Consistently ordered variants of the default base classes. Note that if you are using Python 3.6+, you shouldn’t need
these classes because the dicts in Python 3.6+ are ordered. Note also that there are many differing expectations for the
word “ordered” and that these classes may not provide the order you expect. The intent here is to give a consistent
order not a particular order.
The Ordered (Di/Multi/MultiDi) Graphs give a consistent order for reporting of nodes and edges. The order of node
reporting agrees with node adding, but for edges, the order is not necessarily the order that the edges were added.
In general, you should use the default (i.e., unordered) graph classes. However, there are times (e.g., when testing)
when you may need the order preserved.
Special care is required when using subgraphs of the Ordered classes. The order of nodes in the subclass is not
necessarily the same order as the original class. In general it is probably better to avoid using subgraphs and replace
with code similar to:
# instead of SG = G.subgraph(ordered_nodes) SG=nx.OrderedGraph()
SG.add_nodes_from(ordered_nodes) SG.add_edges_from((u, v) for (u, v) in G.edges() if u in SG
if v in SG)
class OrderedGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of Graph.
class OrderedDiGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of DiGraph.
class OrderedMultiGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of MultiGraph.
class OrderedMultiDiGraph(incoming_graph_data=None, **attr)
Consistently ordered variant of MultiDiGraph.
Note: NetworkX uses dicts to store the nodes and neighbors in a graph. So the reporting of nodes and edges for
the base graph classes will not necessarily be consistent across versions and platforms. If you need the order of nodes
and edges to be consistent (e.g., when writing automated tests), please see OrderedGraph, OrderedDiGraph,
OrderedMultiGraph, or OrderedMultiDiGraph, which behave like the base graph classes but give a consis-
tent order for reporting of nodes and edges.
generic_graph_view(G[, create_using])
subgraph_view(G[, filter_node, filter_edge])
reverse_view(G)
2.3.1 networkx.classes.graphviews.generic_graph_view
generic_graph_view(G, create_using=None)
2.3.2 networkx.classes.graphviews.subgraph_view
2.3.3 networkx.classes.graphviews.reverse_view
reverse_view(G)
THREE
ALGORITHMS
3.1.1 Connectivity
networkx.algorithms.approximation.connectivity.all_pairs_node_connectivity
129
NetworkX Reference, Release 2.3rc1.dev20190222214247
References
networkx.algorithms.approximation.connectivity.local_node_connectivity
Examples
1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
http://eclectic.ss.uci.edu/~drwhite/working.pdf
Notes
This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
Note that the authors propose a further refinement, losing accuracy and gaining speed, which is not implemented
yet.
See also:
all_pairs_node_connectivity(), node_connectivity()
References
networkx.algorithms.approximation.connectivity.node_connectivity
Examples
1 White, Douglas R., and Mark Newman. 2001 A Fast Algorithm for Node-Independent Paths. Santa Fe Institute Working Paper #01-07-035
http://eclectic.ss.uci.edu/~drwhite/working.pdf
Notes
This algorithm1 finds node independents paths between two nodes by computing their shortest path using BFS,
marking the nodes of the path found as ‘used’ and then searching other shortest paths excluding the nodes
marked as used until no more paths exist. It is not exact because a shortest path could use nodes that, if the path
were longer, may belong to two different node independent paths. Thus it only guarantees an strict lower bound
on node connectivity.
See also:
all_pairs_node_connectivity(), local_node_connectivity()
References
3.1.2 K-components
networkx.algorithms.approximation.kcomponents.k_components
k_components(G, min_density=0.95)
Returns the approximate k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
This implementation is based on the fast heuristics to approximate the k-component structure of a graph1 .
Which, in turn, it is based on a fast approximation algorithm for finding good lower bounds of the number of
node independent paths between two nodes2 .
Parameters
• G (NetworkX graph) – Undirected graph
• min_density (Float) – Density relaxation threshold. Default value 0.95
Returns k_components – Dictionary with connectivity level k as key and a list of sets of nodes that
form a k-component of level k as values.
Return type dict
Examples
Notes
The logic of the approximation algorithm for computing the k-component structure1 is based on repeatedly
applying simple and fast algorithms for k-cores and biconnected components in order to narrow down the
number of pairs of nodes over which we have to compute White and Newman’s approximation algorithm for
finding node independent paths2 . More formally, this algorithm is based on Whitney’s theorem, which states
an inclusion relation among node connectivity, edge connectivity, and minimum degree for any graph G. This
theorem implies that every k-component is nested inside a k-edge-component, which in turn, is contained in a
k-core. Thus, this algorithm computes node independent paths among pairs of nodes in each biconnected part
of each k-core, and repeats this procedure for each k from 3 to the maximal core number of a node in the input
graph.
Because, in practice, many nodes of the core of level k inside a bicomponent actually are part of a component
of level k, the auxiliary graph needed for the algorithm is likely to be very dense. Thus, we use a complement
graph data structure (see AntiGraph) to save memory. AntiGraph only stores information of the edges that
are not present in the actual auxiliary graph. When applying algorithms to this complement graph data structure,
it behaves as if it were the dense version.
See also:
k_components()
References
3.1.3 Clique
networkx.algorithms.approximation.clique.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 – The apx-maximum clique of the graph
Return type set
Notes
A clique in an undirected graph G = (V, E) is a subset of the vertex set C subseteq V 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 omega(G) 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.
https://en.wikipedia.org/wiki/Maximum_clique
References
networkx.algorithms.approximation.clique.clique_removal
clique_removal(G)
Repeatedly remove cliques from the graph.
Results in a 𝑂(|𝑉 |/(log |𝑉 |)2 ) approximation of maximum clique and independent set. Returns the largest
independent set found, along with found maximal cliques.
Parameters G (NetworkX graph) – Undirected graph
Returns max_ind_cliques – 2-tuple of Maximal Independent Set and list of maximal cliques (sets).
Return type (set, list) tuple
References
networkx.algorithms.approximation.clique.large_clique_size
large_clique_size(G)
Find the size of a large clique in a graph.
A clique is a subset of nodes in which each pair of nodes is adjacent. This function is a heuristic for finding the
size of a large clique in the graph.
Parameters G (NetworkX graph)
Returns The size of a large clique in the graph.
Return type int
Notes
This implementation is from1 . Its worst case time complexity is 𝑂(𝑛𝑑2 ), where n is the number of nodes in the
graph and d is the maximum degree.
This function is a heuristic, which means it may work well in practice, but there is no rigorous mathematical
guarantee on the ratio between the returned number and the actual largest clique size in the graph.
References
See also:
3.1.4 Clustering
networkx.algorithms.approximation.clustering_coefficient.average_clustering
References
networkx.algorithms.approximation.dominating_set.min_weighted_dominating_set
min_weighted_dominating_set(G, weight=None)
Returns a dominating set that approximates the minimum weight node dominating set.
Parameters
1Schank, Thomas, and Dorothea Wagner. Approximating clustering coefficient and transitivity. Universität Karlsruhe, Fakultät für Informatik,
2004. http://www.emis.ams.org/journals/JGAA/accepted/2005/SchankWagner2005.9.2.pdf
Notes
This algorithm computes an approximate minimum weighted dominating set for the graph G. The returned
solution has weight (log w(V)) w(V^*), where w(V) denotes the sum of the weights of each node in the
graph and w(V^*) denotes the sum of the weights of each node in the minimum weight dominating set for the
graph.
This implementation of the algorithm runs in 𝑂(𝑚) time, where 𝑚 is the number of edges in the graph.
References
networkx.algorithms.approximation.dominating_set.min_edge_dominating_set
min_edge_dominating_set(G)
Returns minimum cardinality edge dominating set.
Parameters G (NetworkX graph) – Undirected graph
Returns min_edge_dominating_set – Returns a set of dominating edges whose size is no more
than 2 * OPT.
Return type set
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.
Wikipedia: Independent set
Independent set algorithm is based on the following paper:
networkx.algorithms.approximation.independent_set.maximum_independent_set
maximum_independent_set(G)
Returns an approximate maximum independent set.
Parameters G (NetworkX graph) – Undirected graph
Returns iset – The apx-maximum independent set
Return type Set
Notes
Finds the 𝑂(|𝑉 |/(𝑙𝑜𝑔|𝑉 |)2 ) apx of independent set in the worst case.
References
3.1.7 Matching
Graph 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.
Wikipedia: Matching
networkx.algorithms.approximation.matching.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 – 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.
Return type set
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
3.1.8 Ramsey
Ramsey numbers.
networkx.algorithms.approximation.ramsey.ramsey_R2
ramsey_R2(G)
Approximately computes the Ramsey number R(2;s,t) for graph.
Parameters G (NetworkX graph) – Undirected graph
Returns max_pair – Maximum clique, Maximum independent set.
Return type (set, set) tuple
networkx.algorithms.approximation.steinertree.metric_closure
metric_closure(G, weight=’weight’)
Return the metric closure of a graph.
The metric closure of a graph G is the complete graph in which each edge is weighted by the shortest path
distance between the nodes in G .
Parameters G (NetworkX graph)
Returns Metric closure of the graph G.
Return type NetworkX graph
networkx.algorithms.approximation.steinertree.steiner_tree
Notes
Steiner tree can be approximated by computing the minimum spanning tree of the subgraph of the metric closure
of the graph induced by the terminal nodes, where the metric closure of G is the complete graph in which each
edge is weighted by the shortest path distance between the nodes in G . This algorithm produces a tree whose
weight is within a (2 - (2 / t)) factor of the weight of the optimal Steiner tree where t is number of terminal
nodes.
3.1.10 Treewidth
networkx.algorithms.approximation.treewidth.treewidth_min_degree
treewidth_min_degree(G)
Returns a treewidth decomposition using the Minimum Degree heuristic.
The heuristic chooses the nodes according to their degree, i.e., first the node with the lowest degree is chosen,
then the graph is updated and the corresponding node is removed. Next, a new node with the lowest degree is
chosen, and so on.
Parameters G (NetworkX graph)
Returns Treewidth decomposition – 2-tuple with treewidth and the corresponding decomposed
tree.
Return type (int, Graph) tuple
networkx.algorithms.approximation.treewidth.treewidth_min_fill_in
treewidth_min_fill_in(G)
Returns a treewidth decomposition using the Minimum Fill-in heuristic.
The heuristic chooses a node from the graph, where the number of edges added turning the neighbourhood of
the chosen node into clique is as small as possible.
1 Hans L. Bodlaender and Arie M. C. A. Koster. 2010. “Treewidth computations I.Upper bounds”. Inf. Comput. 208, 3 (March 2010),259-275.
http://dx.doi.org/10.1016/j.ic.2009.03.008
2 Hand L. Bodlaender. “Discovering Treewidth”. Institute of Information and Computing Sciences, Utrecht University. Technical Report
UU-CS-2005-018. http://www.cs.uu.nl
networkx.algorithms.approximation.vertex_cover.min_weighted_vertex_cover
min_weighted_vertex_cover(G, weight=None)
Returns an approximate minimum weighted vertex cover.
The set of nodes returned by this function is guaranteed to be a vertex cover, and the total weight of the set is
guaranteed to be at most twice the total weight of the minimum weight vertex cover. In other words,
𝑤(𝑆) ≤ 2 * 𝑤(𝑆 * ),
where 𝑆 is the vertex cover returned by this function, 𝑆 * is the vertex cover of minimum weight out of all vertex
covers of the graph, and 𝑤 is the function that computes the sum of the weights of each node in that given set.
Parameters
• G (NetworkX graph)
• weight (string, optional (default = None)) – If None, every node has weight 1. If a string,
use this node attribute as the node weight. A node without this attribute is assumed to have
weight 1.
Returns min_weighted_cover – Returns a set of nodes whose weight sum is no more than twice
the weight sum of the minimum weight vertex cover.
Return type set
Notes
For a directed graph, a vertex cover has the same definition: a set of nodes such that each edge in the graph is
incident to at least one node in the set. Whether the node is the head or tail of the directed edge is ignored.
This is the local-ratio algorithm for computing an approximate vertex cover. The algorithm greedily reduces
the costs over edges, iteratively building a cover. The worst-case runtime of this implementation is 𝑂(𝑚 log 𝑛),
where 𝑛 is the number of nodes and 𝑚 the number of edges in the graph.
References
3.2 Assortativity
3.2.1 Assortativity
networkx.algorithms.assortativity.degree_assortativity_coefficient
Examples
>>> G=nx.path_graph(4)
>>> r=nx.degree_assortativity_coefficient(G)
>>> print("%3.1f"%r)
-0.5
See also:
attribute_assortativity_coefficient(), numeric_assortativity_coefficient(),
neighbor_connectivity(), degree_mixing_dict(), degree_mixing_matrix()
Notes
This computes Eq. (21) in Ref.1 , 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.
1 M. E. J. Newman, Mixing patterns in networks, Physical Review E, 67 026126, 2003
References
networkx.algorithms.assortativity.attribute_assortativity_coefficient
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
Notes
This computes Eq. (2) in Ref.1 , trace(M)-sum(M))/(1-sum(M), where M is the joint probability distribution
(mixing matrix) of the specified attribute.
References
networkx.algorithms.assortativity.numeric_assortativity_coefficient
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
Notes
This computes Eq. (21) in Ref.1 , for the mixing matrix of of the specified attribute.
References
networkx.algorithms.assortativity.degree_pearson_correlation_coefficient
Examples
>>> G=nx.path_graph(4)
>>> r=nx.degree_pearson_correlation_coefficient(G)
>>> print("%3.1f"%r)
-0.5
Notes
References
average_neighbor_degree(G[, source, target, Returns the average degree of the neighborhood of each
. . . ]) node.
networkx.algorithms.assortativity.average_neighbor_degree
where N(i) are the neighbors of node i and k_j is the degree of node j which belongs to N(i). For weighted
graphs, an analogous measure can be defined1 ,
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j and N(i)
are the neighbors of node i.
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 numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns d – A dictionary keyed by node with average neighbors degree value.
Return type dict
Examples
1 A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).
>>> G=nx.path_graph(4)
>>> G.edges[0, 1]['weight'] = 5
>>> G.edges[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()
>>> nx.add_path(G, [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}
Notes
For directed graphs you can also specify in-degree or out-degree by passing keyword arguments.
See also:
average_degree_connectivity()
References
networkx.algorithms.assortativity.average_degree_connectivity
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
1A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).
Examples
>>> G=nx.path_graph(4)
>>> G.edges[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}
See also:
neighbors_average_degree()
Notes
This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.
References
networkx.algorithms.assortativity.k_nearest_neighbors
𝑤 1 ∑︁
𝑘𝑛𝑛,𝑖 = 𝑤𝑖𝑗 𝑘𝑗
𝑠𝑖
𝑗∈𝑁 (𝑖)
where s_i is the weighted degree of node i, w_{ij} is the weight of the edge that links i and j, and N(i)
are the neighbors of node i.
Parameters
• G (NetworkX graph)
1 A. Barrat, M. Barthélemy, R. Pastor-Satorras, and A. Vespignani, “The architecture of complex weighted networks”. PNAS 101 (11):
3747–3752 (2004).
Examples
>>> G=nx.path_graph(4)
>>> G.edges[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}
See also:
neighbors_average_degree()
Notes
This algorithm is sometimes called “k nearest neighbors” and is also available as k_nearest_neighbors.
References
3.2.4 Mixing
networkx.algorithms.assortativity.attribute_mixing_matrix
networkx.algorithms.assortativity.degree_mixing_matrix
networkx.algorithms.assortativity.numeric_mixing_matrix
networkx.algorithms.assortativity.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
networkx.algorithms.assortativity.degree_mixing_dict
networkx.algorithms.assortativity.mixing_dict
mixing_dict(xy, normalized=False)
Returns a dictionary representation of mixing matrix.
Parameters
• xy (list or container of two-tuples) – Pairs of (x,y) items.
• attribute (string) – Node attribute key
• normalized (bool (default=False)) – Return counts if False or probabilities if True.
Returns d – Counts or Joint probability of occurrence of values in xy.
Return type dictionary
3.3 Bipartite
This module provides functions and operations for bipartite graphs. Bipartite graphs B = (U, V, E) have two
node sets U,V and edges in E 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:
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. This convention is not enforced in the source code of
bipartite functions, it’s only a recommendation.
For example:
>>> B = nx.Graph()
>>> # Add nodes with the node attribute "bipartite"
>>> B.add_nodes_from([1, 2, 3, 4], bipartite=0)
>>> B.add_nodes_from(['a', 'b', 'c'], bipartite=1)
>>> # Add edges only between nodes of opposite node sets
>>> 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 B. The functions in the bipartite package do not check that the node
set is actually correct nor that the input graph is actually bipartite. If B is connected, you can find the two node sets
using a two-coloring algorithm:
>>> nx.is_connected(B)
True
>>> bottom_nodes, top_nodes = bipartite.sets(B)
However, if the input graph is not connected, there are more than one possible colorations. This is the reason why we
require the user to pass a container with all nodes of one bipartite node set as an argument to most bipartite functions.
In the face of ambiguity, we refuse the temptation to guess and raise an AmbiguousSolution Exception if the
input graph for bipartite.sets is disconnected.
Using the bipartite node attribute, you can easily get the two node sets:
So you can easily use the bipartite algorithms that require, as an argument, a container with all nodes that belong to
one node set:
All bipartite graph generators in NetworkX build bipartite graphs with the bipartite node attribute. Thus, you can
use the same approach:
networkx.algorithms.bipartite.basic.is_bipartite
is_bipartite(G)
Returns True if graph G is bipartite, False if not.
Parameters G (NetworkX graph)
Examples
See also:
color(), is_bipartite_node_set()
networkx.algorithms.bipartite.basic.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.
Examples
Notes
For connected graphs the bipartite sets are unique. This function handles disconnected graphs.
networkx.algorithms.bipartite.basic.sets
sets(G, top_nodes=None)
Returns bipartite node sets of graph G.
Raises an exception if the graph is not bipartite or if the input graph is disconnected and thus more than one valid
solution exists. See bipartite documentation for further details on how bipartite graphs are handled in
NetworkX.
Parameters
• G (NetworkX graph)
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns (X,Y) – One set of nodes for each part of the bipartite graph.
Return type two-tuple of sets
Raises
• AmbiguousSolution : Exception – Raised if the input bipartite graph is disconnected and no
container with all nodes in one bipartite set is provided. When determining the nodes in
each bipartite set more than one valid solution is possible if the input graph is disconnected.
• NetworkXError: Exception – Raised if the input graph is not bipartite.
Examples
See also:
color()
networkx.algorithms.bipartite.basic.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 – A dictionary keyed by node with a 1 or 0 as data for each node color.
Return type dictionary
Raises exc:NetworkXError if the graph is not two-colorable.
Examples
You can use this to set a node attribute indicating the biparite set:
networkx.algorithms.bipartite.basic.density
density(B, nodes)
Returns density of bipartite graph B.
Parameters
• G (NetworkX graph)
• nodes (list or container) – Nodes in one node set of the bipartite graph.
Returns d – The bipartite density
Examples
Notes
The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color()
networkx.algorithms.bipartite.basic.degrees
Examples
Notes
The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid
ambiguity in the case of disconnected graphs. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
See also:
color(), density()
3.3.2 Matching
The dictionary returned by maximum_matching() includes a mapping for vertices in both the left and right vertex
sets.
networkx.algorithms.bipartite.matching.eppstein_matching
eppstein_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns matches – The matching is returned as a dictionary, matching, such that matching[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in mate.
Return type dictionary
Raises AmbiguousSolution : Exception – Raised if the input bipartite graph is disconnected and no
container with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
Notes
This function is implemented with David Eppstein’s version of the algorithm Hopcroft–Karp algorithm (see
hopcroft_karp_matching()), which originally appeared in the Python Algorithms and Data Structures
library (PADS).
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
hopcroft_karp_matching()
networkx.algorithms.bipartite.matching.hopcroft_karp_matching
hopcroft_karp_matching(G, top_nodes=None)
Returns the maximum cardinality matching of the bipartite graph G.
Parameters
• G (NetworkX graph) – Undirected bipartite graph
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns matches – The matching is returned as a dictionary, matches, such that matches[v]
== w if node v is matched to node w. Unmatched nodes do not occur as a key in mate.
Return type dictionary
Raises AmbiguousSolution : Exception – Raised if the input bipartite graph is disconnected and no
container with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
Notes
This function is implemented with the Hopcroft–Karp matching algorithm for bipartite graphs.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
eppstein_matching()
References
networkx.algorithms.bipartite.matching.to_vertex_cover
• matching (dictionary) – A dictionary whose keys are vertices in G and whose values are the
distinct neighbors comprising the maximum matching for G, as returned by, for example,
maximum_matching(). The dictionary must represent the maximum matching.
• top_nodes (container) – Container with all nodes in one bipartite node set. If not supplied
it will be computed. But if more than one solution exists an exception will be raised.
Returns vertex_cover – The minimum vertex cover in G.
Return type set
Raises AmbiguousSolution : Exception – Raised if the input bipartite graph is disconnected and no
container with all nodes in one bipartite set is provided. When determining the nodes in each
bipartite set more than one valid solution is possible if the input graph is disconnected.
Notes
This function is implemented using the procedure guaranteed by Konig’s theorem, which proves an equivalence
between a maximum matching and a minimum vertex cover in bipartite graphs.
Since a minimum vertex cover is the complement of a maximum independent set for any graph, one can compute
the maximum independent set of a bipartite graph this way:
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
3.3.3 Matrix
Biadjacency matrices
networkx.algorithms.bipartite.matrix.biadjacency_matrix
• row_order (list of nodes) – The rows of the matrix are ordered according to the list of nodes.
• column_order (list, optional) – The columns of the matrix are ordered according to the list
of nodes. If column_order is None, then the ordering of columns is arbitrary.
• dtype (NumPy data-type, optional) – A valid NumPy dtype used to initialize the array. If
None, then the NumPy default is used.
• weight (string or None, optional (default=’weight’)) – The edge data key used to provide
each value in the matrix. If None, then each edge has weight 1.
• format (str in {‘bsr’, ‘csr’, ‘csc’, ‘coo’, ‘lil’, ‘dia’, ‘dok’}) – The type of the matrix to be
returned (default ‘csr’). For some algorithms different implementations of sparse matrices
can perform better. See2 for details.
Returns M – Biadjacency matrix representation of the bipartite graph G.
Return type SciPy sparse matrix
Notes
References
networkx.algorithms.bipartite.matrix.from_biadjacency_matrix
Notes
The nodes are labeled with the attribute bipartite set to an integer 0 or 1 representing membership in part 0
or part 1 of the bipartite graph.
If create_using is an instance of networkx.MultiGraph or networkx.MultiDiGraph and the
entries of A are of type int, then this function returns a multigraph (of the same type as create_using)
with parallel edges. In this case, edge_attribute will be ignored.
See also:
biadjacency_matrix(), from_numpy_matrix()
2 Scipy Dev. References, “Sparse Matrices”, https://docs.scipy.org/doc/scipy/reference/sparse.html
References
[1] https://en.wikipedia.org/wiki/Adjacency_matrix#Adjacency_matrix_of_a_bipartite_graph
3.3.4 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.
Newman’s weighted projection of B onto one of its node
collaboration_weighted_projected_graph(B,
nodes) sets.
overlap_weighted_projected_graph(B, Overlap weighted projection of B onto one of its node
nodes[, . . . ]) sets.
generic_weighted_projected_graph(B, Weighted projection of B with a user-specified weight
nodes[, . . . ]) function.
networkx.algorithms.bipartite.projection.projected_graph
Examples
If nodes a, and b are connected through both nodes 1 and 2 then building a multigraph results in two edges in
the projection onto [a, 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']]
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.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
generic_weighted_projected_graph()
networkx.algorithms.bipartite.projection.weighted_projected_graph
Examples
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
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.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), collaboration_weighted_projected_graph(),
overlap_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
References
networkx.algorithms.bipartite.projection.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 model1 :
∑︁ 𝛿 𝑘 𝛿 𝑘
𝑢 𝑣
𝑤𝑢,𝑣 =
𝑑𝑘 − 1
𝑘
where u and v are nodes from the bottom bipartite node set, and k is a node of the top node set. The value d_k
is the degree of node k in the bipartite network and delta_{u}^{k} is 1 if node u is linked to node k 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 – A graph that is the projection onto the given nodes.
Return type NetworkX graph
1 Scientific collaboration networks: II. Shortest paths, weighted networks, and centrality, M. E. J. Newman, Phys. Rev. E 64, 016132 (2001).
Examples
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.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
overlap_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
References
networkx.algorithms.bipartite.projection.overlap_weighted_projected_graph
or if the parameter ‘jaccard’ is False, the fraction of common neighbors by minimum of both nodes degree in
the original bipartite graph1 :
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑤𝑣,𝑢 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
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.
1 Borgatti, S.P. and Halgin, D. In press. Analyzing Affiliation Networks. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
Examples
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.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), generic_weighted_projected_graph(),
projected_graph()
References
networkx.algorithms.bipartite.projection.generic_weighted_projected_graph
Returns Graph – A graph that is the projection onto the given nodes.
Return type NetworkX graph
Examples
>>> print(list(G.edges(data=True)))
[(0, 1, {'weight': 1.0})]
>>> G = bipartite.generic_weighted_projected_graph(B, [0, 1], weight_function=my_
˓→weight)
>>> print(list(G.edges(data=True)))
[(0, 1, {'weight': 10})]
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.
See bipartite documentation for further details on how bipartite graphs are handled in NetworkX.
See also:
is_bipartite(), is_bipartite_node_set(), sets(), weighted_projected_graph(),
collaboration_weighted_projected_graph(), overlap_weighted_projected_graph(),
projected_graph()
3.3.5 Spectral
networkx.algorithms.bipartite.spectral.spectral_bipartivity
Examples
Notes
This implementation uses Numpy (dense) matrices which are not efficient for storing large sparse graphs.
See also:
color()
References
3.3.6 Clustering
networkx.algorithms.bipartite.cluster.clustering
where N(N(u)) are the second order neighbors of u in G excluding u, and c_{uv} is the pairwise clustering
coefficient between nodes u and v.
The mode selects the function for c_{uv} which can be:
dot:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
|𝑁 (𝑢) ∪ 𝑁 (𝑣)|
min:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑖𝑛(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
max:
|𝑁 (𝑢) ∩ 𝑁 (𝑣)|
𝑐𝑢𝑣 =
𝑚𝑎𝑥(|𝑁 (𝑢)|, |𝑁 (𝑣)|)
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 – A dictionary keyed by node with the clustering coefficient value.
Return type dictionary
Examples
See also:
robins_alexander_clustering(), square_clustering(), average_clustering()
1 Latapy, Matthieu, Clémence Magnien, and Nathalie Del Vecchio (2008). Basic notions for the analysis of large two-mode networks. Social
References
networkx.algorithms.bipartite.cluster.average_clustering
Examples
See also:
clustering()
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. See bipartite
documentation for further details on how bipartite graphs are handled in NetworkX.
1Latapy, 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.
References
networkx.algorithms.bipartite.cluster.latapy_clustering
Examples
See also:
robins_alexander_clustering(), square_clustering(), average_clustering()
1Latapy, 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.
References
networkx.algorithms.bipartite.cluster.robins_alexander_clustering
robins_alexander_clustering(G)
Compute the bipartite clustering of G.
Robins and Alexander1 defined bipartite clustering coefficient as four times the number of four cycles C_4
divided by the number of three paths L_3 in a bipartite graph:
4 * 𝐶4
𝐶𝐶4 =
𝐿3
Parameters G (graph) – a bipartite graph
Returns clustering – The Robins and Alexander bipartite clustering for the input graph.
Return type float
Examples
See also:
latapy_clustering(), square_clustering()
References
3.3.7 Redundancy
networkx.algorithms.bipartite.redundancy.node_redundancy
node_redundancy(G, nodes=None)
Computes the node redundancy coefficients for the nodes in the bipartite graph G.
The redundancy coefficient of a node v is the fraction of pairs of neighbors of v that are both linked to other
nodes. In a one-mode projection these nodes would be linked together even if v were not there.
More formally, for any vertex v, the redundancy coefficient of ‘v‘ is defined by
Parameters
• G (graph) – A bipartite graph
• nodes (list or iterable (optional)) – Compute redundancy for these nodes. The default is all
nodes in G.
Returns redundancy – A dictionary keyed by node with the node redundancy value.
Return type dictionary
Examples
Raises NetworkXError – If any of the nodes in the graph (or in nodes, if specified) has (out-
)degree less than two (which would result in division by zero, according to the definition of the
redundancy coefficient).
References
3.3.8 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.
Continued on next page
networkx.algorithms.bipartite.centrality.closeness_centrality
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. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.
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
set1 . Thus the closeness centrality for node v in the two bipartite sets U with n nodes and V with m nodes is
𝑚 + 2(𝑛 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑈,
𝑑
𝑛 + 2(𝑚 − 1)
𝑐𝑣 = , for𝑣 ∈ 𝑉,
𝑑
where d is the sum of the distances from v 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
networkx.algorithms.bipartite.centrality.degree_centrality
degree_centrality(G, nodes)
Compute the degree centrality for nodes in a bipartite network.
1Borgatti, 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/research/publications/bhaffiliations.pdf
The degree centrality for a node v 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 keyed by node with bipartite degree centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), closeness_centrality(), sets(), is_bipartite()
Notes
The nodes input parameter must contain all nodes in one bipartite node set, but the dictionary returned con-
tains all nodes from both bipartite node sets. See bipartite documentation for further details on how
bipartite graphs are handled in NetworkX.
For unipartite networks, the degree centrality values are normalized by dividing by the maximum possible degree
(which is n-1 where n 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 set1 . The degree centrality for a node v in the bipartite sets U with n nodes and V with m nodes is
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑈,
𝑚
𝑑𝑒𝑔(𝑣)
𝑑𝑣 = , for𝑣 ∈ 𝑉,
𝑛
where deg(v) is the degree of node v.
References
networkx.algorithms.bipartite.centrality.betweenness_centrality
betweenness_centrality(G, nodes)
Compute betweenness centrality for nodes in a bipartite network.
Betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v.
Values of betweenness are normalized by the maximum possible value which for bipartite graphs is limited by
the relative size of the two node sets1 .
Let n be the number of nodes in the node set U and m be the number of nodes in the node set V, then nodes in U
are normalized by dividing by
1 2
[𝑚 (𝑠 + 1)2 + 𝑚(𝑠 + 1)(2𝑡 − 𝑠 − 1) − 𝑡(2𝑠 − 𝑡 + 3)],
2
where
𝑠 = (𝑛 − 1) ÷ 𝑚, 𝑡 = (𝑛 − 1) mod 𝑚,
1 Borgatti, S.P. and Halgin, D. In press. “Analyzing Affiliation Networks”. In Carrington, P. and Scott, J. (eds) The Sage Handbook of Social
𝑝 = (𝑚 − 1) ÷ 𝑛, 𝑟 = (𝑚 − 1) mod 𝑛.
Parameters
• G (graph) – A bipartite graph
• nodes (list or container) – Container with all nodes in one bipartite node set.
Returns betweenness – Dictionary keyed by node with bipartite betweenness centrality as the value.
Return type dictionary
See also:
degree_centrality(), closeness_centrality(), sets(), is_bipartite()
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. See bipartite documentation for further details on how bipartite graphs
are handled in NetworkX.
References
3.3.9 Generators
networkx.algorithms.bipartite.generators.complete_bipartite_graph
Notes
networkx.algorithms.bipartite.generators.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.
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
networkx.algorithms.bipartite.generators.havel_hakimi_graph
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
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.
networkx.algorithms.bipartite.generators.reverse_havel_hakimi_graph
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
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.
networkx.algorithms.bipartite.generators.alternating_havel_hakimi_graph
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
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.
networkx.algorithms.bipartite.generators.preferential_attachment_graph
References
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
networkx.algorithms.bipartite.generators.random_graph
Parameters
• n (int) – The number of nodes in the first bipartite set.
• m (int) – The number of nodes in the second bipartite set.
• p (float) – Probability for edge creation.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
• directed (bool, optional (default=False)) – If True return a directed graph
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
The bipartite random graph algorithm chooses each of the n*m (undirected) or 2*nm (directed) possible edges
with probability p.
This algorithm is 𝑂(𝑛 + 𝑚) where 𝑚 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.
See also:
gnp_random_graph(), configuration_model()
References
networkx.algorithms.bipartite.generators.gnmk_random_graph
Examples
Notes
This function is not imported in the main namespace. To use it you have to explicitly import the bipartite
package.
If k > m * n then a complete bipartite graph is returned.
This graph is a bipartite version of the G_{nm} random graph model.
3.3.10 Covering
networkx.algorithms.bipartite.covering.min_edge_cover
min_edge_cover(G, matching_algorithm=None)
Returns a set of edges which constitutes the minimum edge cover of the graph.
The smallest edge cover can be found in polynomial time by finding a maximum matching and extending it
greedily so that all nodes are covered.
Parameters
• G (NetworkX graph) – An undirected bipartite graph.
• matching_algorithm (function) – A function that returns a maximum cardinality matching
in a given bipartite graph. The function must take one input, the graph G, and return a dic-
tionary mapping each node to its mate. If not specified, hopcroft_karp_matching()
will be used. Other possibilities include eppstein_matching(),
Returns A set of the edges in a minimum edge cover of the graph, given as pairs of nodes. It contains
both the edges (u, v) and (v, u) for given nodes u and v among the edges of minimum
edge cover.
Return type set
Notes
An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of
the set. A minimum edge cover is an edge covering of smallest cardinality.
Due to its implementation, the worst-case running time of this algorithm is bounded by the worst-case running
time of the function matching_algorithm.
3.4 Boundary
3.4.1 networkx.algorithms.boundary.edge_boundary
Notes
3.4.2 networkx.algorithms.boundary.node_boundary
• nbunch2 (iterable) – Iterable of nodes representing the target (or “exterior”) set of nodes.
(This is the set T from the definition above.) If not specified, this is assumed to be the set of
all nodes in G not in nbunch1.
Returns The node boundary of nbunch1 with respect to nbunch2.
Return type set
Notes
3.5 Bridges
Bridge-finding algorithms.
3.5.1 networkx.algorithms.bridges.bridges
bridges(G, root=None)
Generate all bridges in a graph.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase. Equivalently, a bridge is an edge that does not belong to any cycle.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be returned.
Yields e (edge) – An edge in the graph whose removal disconnects the graph (or causes the number
of connected components to increase).
Raises NodeNotFound – If root is not in the graph G.
Examples
>>> G = nx.barbell_graph(10, 0)
>>> list(nx.bridges(G))
[(9, 10)]
Notes
This is an implementation of the algorithm described in _[1]. An edge is a bridge if and only if it is not contained
in any chain. Chains are found using the networkx.chain_decomposition() function.
Ignoring polylogarithmic factors, the worst-case time complexity is the same as the networkx.
chain_decomposition() function, 𝑂(𝑚 + 𝑛), where 𝑛 is the number of nodes in the graph and 𝑚 is
the number of edges.
References
3.5.2 networkx.algorithms.bridges.has_bridges
has_bridges(G, root=None)
Decide whether a graph has any bridges.
A bridge in a graph is an edge whose removal causes the number of connected components of the graph to
increase.
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the bridges in the connected
component containing this node will be considered.
Returns Whether the graph (or the connected component containing root) has any bridges.
Return type bool
Raises NodeNotFound – If root is not in the graph G.
Examples
>>> G = nx.barbell_graph(10, 0)
>>> nx.has_bridges(G)
True
>>> G = nx.cycle_graph(5)
>>> nx.has_bridges(G)
False
Notes
This implementation uses the networkx.bridges() function, so it shares its worst-case time complexity,
𝑂(𝑚 + 𝑛), ignoring polylogarithmic factors, where 𝑛 is the number of nodes in the graph and 𝑚 is the number
of edges.
3.5.3 networkx.algorithms.bridges.local_bridges
Examples
A cycle graph has every edge a local bridge with span N-1.
>>> G = nx.cycle_graph(9)
>>> (0, 8, 8) in set(nx.local_bridges(G))
True
3.6 Centrality
3.6.1 Degree
networkx.algorithms.centrality.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 of nodes with degree centrality as the value.
Return type dictionary
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.
networkx.algorithms.centrality.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 of nodes with in-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented: – If G is undirected.
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.
networkx.algorithms.centrality.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 of nodes with out-degree centrality as values.
Return type dictionary
Raises NetworkXNotImplemented: – If G is undirected.
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.
3.6.2 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.
networkx.algorithms.centrality.eigenvector_centrality
𝐴𝑥 = 𝜆𝑥
where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique solution 𝑥, all of whose entries are positive, if 𝜆 is the largest eigenvalue of the adjacency
matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
• max_iter (integer, optional (default=100)) – 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 (default=None)) – Starting value of eigenvector iteration for
each node.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary
2 Mark E. J. Newman. Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality(G)
>>> sorted((v, '{:0.2f}'.format(c)) for v, c in centrality.items())
[(0, '0.37'), (1, '0.60'), (2, '0.60'), (3, '0.37')]
Raises
• NetworkXPointlessConcept – If the graph G is the null graph.
• NetworkXError – If each value in nstart is zero.
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.
See also:
eigenvector_centrality_numpy(), pagerank(), hits()
Notes
References
networkx.algorithms.centrality.eigenvector_centrality_numpy
𝐴𝑥 = 𝜆𝑥
where 𝐴 is the adjacency matrix of the graph G with eigenvalue 𝜆. By virtue of the Perron–Frobenius theorem,
there is a unique and positive solution if 𝜆 is the largest eigenvalue associated with the eigenvector of the
adjacency matrix 𝐴 (2 ).
Parameters
• G (graph) – A networkx graph
1 Phillip Bonacich. “Power and Centrality: A Family of Measures.” American Journal of Sociology 92(5):1170–1182, 1986 <http://www.
leonidzhukov.net/hse/2014/socialnetworks/papers/Bonacich-Centrality.pdf>
2 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, pp. 169.
• weight (None or string, optional (default=None)) – The name of the edge attribute used as
weight. If None, all edge weights are considered equal.
• max_iter (integer, optional (default=100)) – Maximum number of iterations in power
method.
• tol (float, optional (default=1.0e-6)) – Relative accuracy for eigenvalues (stopping crite-
rion). The default value of 0 implies machine precision.
Returns nodes – Dictionary of nodes with eigenvector centrality as the value.
Return type dictionary
Examples
>>> G = nx.path_graph(4)
>>> centrality = nx.eigenvector_centrality_numpy(G)
>>> print(['{} {:0.2f}'.format(node, centrality[node]) for node in centrality])
['0 0.37', '1 0.60', '2 0.60', '3 0.37']
See also:
eigenvector_centrality(), pagerank(), hits()
Notes
References
networkx.algorithms.centrality.katz_centrality
Katz centrality computes the relative influence of a node within a network by measuring the number of the
immediate neighbors (first degree nodes) and also all other nodes in the network that connect to the node under
consideration through these immediate neighbors.
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 in1 .
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 (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns nodes – Dictionary of nodes with Katz centrality as the value.
Return type dictionary
Raises
• NetworkXError – If the parameter beta is not a scalar but lacks a value for at least one
node
• PowerIterationFailedConvergence – If the algorithm fails to converge to the
specified tolerance within the specified number of iterations of the power iteration method.
Examples
See also:
katz_centrality_numpy(), eigenvector_centrality(), eigenvector_centrality_numpy(),
pagerank(), hits()
1 Mark E. J. Newman: Networks: An Introduction. Oxford University Press, USA, 2010, p. 720.
Notes
References
networkx.algorithms.centrality.katz_centrality_numpy
Examples
See also:
katz_centrality(), eigenvector_centrality_numpy(), eigenvector_centrality(),
pagerank(), hits()
Notes
References
3.6.3 Closeness
networkx.algorithms.centrality.closeness_centrality
socialnetworks/papers/freeman79-centrality.pdf
reachable nodes.
𝑛−1
𝐶(𝑢) = ∑︀𝑛−1 ,
𝑣=1 𝑑(𝑣, 𝑢)
where d(v, u) is the shortest-path distance between v and u, and n is the number of nodes that can reach u.
Notice that higher values of closeness indicate higher centrality.
Wasserman and Faust propose an improved formula for graphs with more than one connected component. The
result is “a ratio of the fraction of actors in the group who are reachable, to the average distance” from the
reachable actors2 . You might think this scale factor is inverted but it is not. As is, nodes from small components
receive a smaller closeness value. Letting N denote the number of nodes in the graph,
𝑛−1 𝑛−1
𝐶𝑊 𝐹 (𝑢) = ∑︀𝑛−1 ,
𝑁 − 1 𝑣=1 𝑑(𝑣, 𝑢)
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
• wf_improved (bool, optional (default=True)) – If True, scale by the fraction of nodes reach-
able. This gives the Wasserman and Faust improved formula. For single component graphs
it is the same as the original formula.
• reverse (bool, optional (default=False)) – If True and G is a digraph, reverse the edges of
G, using successors instead of predecessors.
Returns nodes – Dictionary of nodes with closeness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality()
Notes
The closeness centrality is normalized to (n-1)/(|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 close-
ness centrality for each connected part separately scaled by that parts size.
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
2 pg. 201 of Wasserman, S. and Faust, K., Social Network Analysis: Methods and Applications, 1994, Cambridge University Press.
networkx.algorithms.centrality.current_flow_closeness_centrality
Notes
References
networkx.algorithms.centrality.information_centrality
1016/0378-8733(89)90016-6
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• dtype (data type (default=float)) – Default data type for internal matrices. Set to np.float32
for lower memory consumption.
• solver (string (default=’lu’)) – Type of linear solver to use for computing the flow matrix.
Options are “full” (uses most memory), “lu” (recommended), and “cg” (uses least memory).
Returns nodes – Dictionary of nodes with current flow closeness centrality as the value.
Return type dictionary
See also:
closeness_centrality()
Notes
References
networkx.algorithms.centrality.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 𝑣 ∈ 𝑠, 𝑡, 𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
1 Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science
1016/0378-8733(89)90016-6
2 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
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. 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/
((n-1)(n-2)) for graphs, and 1/((n-1)(n-2)) for directed graphs where n is the
number of nodes in G.
• weight (None or string, optional (default=None)) – 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.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns nodes – Dictionary of nodes with betweenness centrality as the value.
Return type dictionary
See also:
edge_betweenness_centrality(), load_centrality()
Notes
The algorithm is from Ulrik Brandes1 . See4 for the original first published version and2 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 see3 .
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
networkx.algorithms.centrality.edge_betweenness_centrality
where 𝑉 is the set of nodes, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒) is the number of those
paths passing through edge 𝑒2 .
Parameters
• G (graph) – A NetworkX graph.
1 Ulrik Brandes: A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. http://www.inf.
uni-konstanz.de/algo/publications/b-fabc-01.pdf
4 Linton C. Freeman: A set of measures of centrality based on betweenness. Sociometry 40: 35–41, 1977 http://moreno.ss.uci.edu/23.pdf
3 Ulrik Brandes and Christian Pich: Centrality Estimation in Large Networks. International Journal of Bifurcation and Chaos 17(7):2303-2318,
2007. http://www.inf.uni-konstanz.de/algo/publications/bp-celn-06.pdf
2 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
• k (int, optional (default=None)) – If k is not None use k node samples to estimate between-
ness. 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)) for graphs, and 1/(𝑛(𝑛 − 1)) for directed graphs where 𝑛 is the number of nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness. Note that this is only used if k is not None.
Returns edges – Dictionary of edges with betweenness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), edge_load()
Notes
References
networkx.algorithms.centrality.betweenness_centrality_subset
where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑣)
is the number of those paths passing through some node 𝑣 other than 𝑠, 𝑡. If 𝑠 = 𝑡, 𝜎(𝑠, 𝑡) = 1, and if 𝑣 ∈ 𝑠, 𝑡,
𝜎(𝑠, 𝑡|𝑣) = 02 .
Parameters
• G (graph) – A NetworkX graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• 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 (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
1 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
2 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
Notes
References
networkx.algorithms.centrality.edge_betweenness_centrality_subset
where 𝑆 is the set of sources, 𝑇 is the set of targets, 𝜎(𝑠, 𝑡) is the number of shortest (𝑠, 𝑡)-paths, and 𝜎(𝑠, 𝑡|𝑒)
is the number of those paths passing through edge 𝑒2 .
Parameters
• G (graph) – A networkx graph.
• sources (list of nodes) – Nodes to use as sources for shortest paths in betweenness
• targets (list of nodes) – Nodes to use as targets for shortest paths in betweenness
• normalized (bool, optional) – If True the betweenness values are normalized by 2/
(n(n-1)) for graphs, and 1/(n(n-1)) for directed graphs where n is the number of
nodes in G.
• weight (None or string, optional (default=None)) – If None, all edge weights are considered
equal. Otherwise holds the name of the edge attribute used as weight.
Returns edges – Dictionary of edges with Betweenness centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), edge_load()
1 Ulrik Brandes, A Faster Algorithm for Betweenness Centrality. Journal of Mathematical Sociology 25(2):163-177, 2001. http://www.inf.
uni-konstanz.de/algo/publications/b-fabc-01.pdf
2 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
Notes
References
networkx.algorithms.centrality.current_flow_betweenness_centrality
uni-konstanz.de/algo/publications/b-fabc-01.pdf
2 A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
See also:
approximate_current_flow_betweenness_centrality(), betweenness_centrality(),
edge_betweenness_centrality(), edge_current_flow_betweenness_centrality()
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 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
networkx.algorithms.centrality.edge_current_flow_betweenness_centrality
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 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
networkx.algorithms.centrality.approximate_current_flow_betweenness_centrality
Notes
√
The running time is 𝑂((1/𝜖2 )𝑚 𝑘 log 𝑛) and the space required is 𝑂(𝑚) for 𝑛 nodes and 𝑚 edges.
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
networkx.algorithms.centrality.current_flow_betweenness_centrality_subset
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
2A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
1Centrality 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://algo.uni-konstanz.de/publications/bf-cmbcf-05.pdf
The space required is 𝑂(𝑛𝑤) where 𝑤 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
networkx.algorithms.centrality.edge_current_flow_betweenness_centrality_subset
Notes
Current-flow betweenness can be computed in 𝑂(𝐼(𝑛 − 1) + 𝑚𝑛 log 𝑛) time1 , where 𝐼(𝑛 − 1) is the time
3
√ the inverse Laplacian. For a full matrix this is 𝑂(𝑛 ) but using sparse methods you can
needed to compute
achieve 𝑂(𝑛𝑚 𝑘) where 𝑘 is the Laplacian matrix condition number.
The space required is 𝑂(𝑛𝑤) where 𝑤 is the width of the sparse Laplacian matrix. Worse case is 𝑤 = 𝑛 for
𝑂(𝑛2 ).
2A measure of betweenness centrality based on random walks, M. E. J. Newman, Social Networks 27, 39-54 (2005).
1Centrality 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://algo.uni-konstanz.de/publications/bf-cmbcf-05.pdf
If the edges have a ‘weight’ attribute they will be used as weights in this algorithm. Unspecified weights are set
to 1.
References
networkx.algorithms.centrality.communicability_betweenness_centrality
communicability_betweenness_centrality(G, normalized=True)
Returns subgraph communicability 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 of nodes with communicability betweenness as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.
Notes
Let G=(V,E) be a simple undirected graph with n nodes and m edges, and A denote the adjacency matrix of G.
Let G(r)=(V,E(r)) be the graph resulting from removing all edges connected to node r but not the node
itself.
The adjacency matrix for G(r) is A+E(r), where E(r) has nonzeros only in row and column r.
The subraph betweenness of a node r is1
1 ∑︁ ∑︁ 𝐺𝑝𝑟𝑞
𝜔𝑟 = , 𝑝 ̸= 𝑞, 𝑞 ̸= 𝑟,
𝐶 𝑝 𝑞 𝐺𝑝𝑞
References
Examples
1 Ernesto Estrada, Desmond J. Higham, Naomichi Hatano, “Communicability Betweenness in Complex Networks” Physica A 388 (2009) 764-
774. https://arxiv.org/abs/0905.4102
>>> 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)
3.6.8 Load
networkx.algorithms.centrality.load_centrality
Notes
Load centrality is slightly different than betweenness. It was originally introduced by2 . For this load algorithm
see1 .
References
networkx.algorithms.centrality.edge_load_centrality
edge_load_centrality(G, cutoff=False)
Compute edge load.
WARNING: This concept of edge load has not been analysed or discussed outside of NetworkX that we know
of. It is based loosely on load_centrality in the sense that it counts the number of shortest paths which cross
each edge. This function is for demonstration and testing purposes.
2 Kwang-Il Goh, Byungnam Kahng and Doochul Kim Universal behavior of Load Distribution in Scale-Free Networks. Physical Review Letters
2001. http://journals.aps.org/pre/abstract/10.1103/PhysRevE.64.016132
Parameters
• G (graph) – A networkx graph
• cutoff (bool, optional (default=False)) – If specified, only consider paths of length <= cut-
off.
Returns
• A dict keyed by edge 2-tuple to the number of shortest paths
• which use that edge. Where more than one path is shortest
• the count is divided equally among paths.
3.6.9 Subgraph
networkx.algorithms.centrality.subgraph_centrality
subgraph_centrality(G)
Returns subgraph centrality for each node in G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
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.
Subgraph centrality of a node u in G can be found using a spectral decomposition of the adjacency matrix1 ,
𝑁
∑︁
𝑆𝐶(𝑢) = (𝑣𝑗𝑢 )2 𝑒𝜆𝑗 ,
𝑗=1
where v_j is an eigenvector of the adjacency matrix A of G corresponding corresponding to the eigenvalue
lambda_j.
1 Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review E 71, 056103 (2005). https:
//arxiv.org/abs/cond-mat/0504730
Examples
References
networkx.algorithms.centrality.subgraph_centrality_exp
subgraph_centrality_exp(G)
Returns the subgraph centrality for each node of G.
Subgraph centrality of a node n is the sum of weighted closed walks of all lengths starting and ending at node
n. The weights decrease with path length. Each closed walk is associated with a connected subgraph (1 ).
Parameters G (graph)
Returns nodes – Dictionary of nodes with subgraph centrality as the value.
Return type dictionary
Raises NetworkXError – If the graph is not undirected and simple.
See also:
Notes
References
Examples
networkx.algorithms.centrality.estrada_index
estrada_index(G)
Returns the Estrada index of a the graph G.
The Estrada Index is a topological index of folding or 3D “compactness” (1 ).
1 Ernesto Estrada, Juan A. Rodriguez-Velazquez, “Subgraph centrality in complex networks”, Physical Review E 71, 056103 (2005). https:
//arxiv.org/abs/cond-mat/0504730
1 E. Estrada, “Characterization of 3D molecular structure”, Chem. Phys. Lett. 319, 713 (2000). https://doi.org/10.1016/S0009-2614(00)00158-5
Parameters G (graph)
Returns estrada index
Return type float
Raises NetworkXError – If the graph is not undirected and simple.
Notes
References
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)
networkx.algorithms.centrality.harmonic_centrality
https://doi.org/10.1016/j.laa.2007.06.020
1 Boldi, Paolo, and Sebastiano Vigna. “Axioms for centrality.” Internet Mathematics 10.3-4 (2014): 222-262.
• distance (edge attribute key, optional (default=None)) – Use the specified edge attribute as
the edge distance in shortest path calculations. If None, then each edge will have distance
equal to 1.
Returns nodes – Dictionary of nodes with harmonic centrality as the value.
Return type dictionary
See also:
betweenness_centrality(), load_centrality(), eigenvector_centrality(),
degree_centrality(), closeness_centrality()
Notes
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
3.6.11 Reaching
local_reaching_centrality(G, v[, paths, Returns the local reaching centrality of a node in a di-
. . . ]) rected graph.
global_reaching_centrality(G[, weight, Returns the global reaching centrality of a directed
. . . ]) graph.
networkx.algorithms.centrality.local_reaching_centrality
Examples
See also:
global_reaching_centrality()
References
networkx.algorithms.centrality.global_reaching_centrality
Examples
10.1371/journal.pone.0033799
See also:
local_reaching_centrality()
References
3.6.12 Percolation
networkx.algorithms.centrality.percolation_centrality
Notes
The algorithm is from Mahendra Piraveenan, Mikhail Prokopenko, and Liaquat Hossain1 Pair dependecies are
calculated and accumulated using2
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
networkx.algorithms.centrality.second_order_centrality
second_order_centrality(G)
Compute the second order centrality for nodes of G.
The second order centrality of a given node is the standard deviation of the return times to that node of a
perpetual random walk on G:
Parameters G (graph) – A NetworkX connected and undirected graph.
Returns nodes – Dictionary keyed by node with second order centrality as the value.
Return type dictionary
Examples
>>> G = nx.star_graph(10)
>>> soc = nx.second_order_centrality(G)
>>> print(sorted(soc.items(), key=lambda x:x[1])[0][0]) # pick first id
0
Raises NetworkXException – If the graph G is empty, non connected or has negative weights.
See also:
betweenness_centrality()
Notes
uni-konstanz.de/algo/publications/b-fabc-01.pdf
1 Anne-Marie Kermarrec, Erwan Le Merrer, Bruno Sericola, Gilles Trédan “Second order centrality: Distributed assessment of nodes criticity
This code implements the analytical version of the algorithm, i.e., there is no simulation of a random walk
process involved. The random walk is here unbiased (corresponding to eq 6 of the paper1 ), thus the centrality
values are the standard deviations for random walk return times on the transformed input graph G (equal in-
degree at each nodes by adding self-loops).
Complexity of this implementation, made to run locally on a single machine, is O(n^3), with n the size of G,
which makes it viable only for small graphs.
References
3.7 Chains
3.7.1 networkx.algorithms.chains.chain_decomposition
chain_decomposition(G, root=None)
Returns the chain decomposition of a graph.
The chain decomposition of a graph with respect a depth-first search tree is a set of cycles or paths derived from
the set of fundamental cycles of the tree in the following manner. Consider each fundamental cycle with respect
to the given tree, represented as a list of edges beginning with the nontree edge oriented away from the root of
the tree. For each fundamental cycle, if it overlaps with any previous fundamental cycle, just take the initial
non-overlapping segment, which is a path instead of a cycle. Each cycle or path is called a chain. For more
information, see1 .
Parameters
• G (undirected graph)
• root (node (optional)) – A node in the graph G. If specified, only the chain decomposition
for the connected component containing this node will be returned. This node indicates the
root of the depth-first search tree.
Yields chain (list) – A list of edges representing a chain. There is no guarantee on the orientation
of the edges in each chain (for example, if a chain includes the edge joining nodes 1 and 2, the
chain may include either (1, 2) or (2, 1)).
Raises NodeNotFound – If root is not in the graph G.
Notes
The worst-case running time of this implementation is linear in the number of nodes and number of edges1 .
1 Jens M. Schmidt (2013). “A simple test on 2-vertex- and 2-edge-connectivity.” Information Processing Letters, 113, 241–244. Elsevier.
<https://doi.org/10.1016/j.ipl.2013.01.016>
References
3.8 Chordal
3.8.1 networkx.algorithms.chordal.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 – True if G is a chordal graph and False otherwise.
Return type bool
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. If the input graph is an instance of one of these classes, a NetworkXError is raised.
Examples
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 in1 .
References
3.8.2 networkx.algorithms.chordal.chordal_graph_cliques
chordal_graph_cliques(G)
Returns the set of maximal cliques of a chordal graph.
1 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.
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
Return type A set containing the maximal cliques in G.
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. 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
3.8.3 networkx.algorithms.chordal.chordal_graph_treewidth
chordal_graph_treewidth(G)
Returns the treewidth of the chordal graph G.
Parameters G (graph) – A NetworkX graph
Returns treewidth – The size of the largest clique in the graph minus one.
Return type int
Raises NetworkXError – The algorithm does not support DiGraph, MultiGraph and MultiDi-
Graph. 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
References
3.8.4 networkx.algorithms.chordal.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
Examples
Notes
References
3.9 Clique
papers/volume9/elidan08a/elidan08a.pdf
1 clique problem:: https://en.wikipedia.org/wiki/Clique_problem
3.9.1 networkx.algorithms.clique.enumerate_all_cliques
enumerate_all_cliques(G)
Returns all cliques in an undirected graph.
This function returns an iterator over cliques, each of which is a list of nodes. The iteration is ordered by
cardinality of the cliques: first all cliques of size one, then all cliques of size two, etc.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over cliques, each of which is a list of nodes in G. The cliques are ordered
according to size.
Return type iterator
Notes
To obtain a list of all cliques, use list(enumerate_all_cliques(G)). However, be aware that in the
worst-case, the length of this list can be exponential in the number of nodes in the graph (for example, when
the graph is the complete graph). This function avoids storing all cliques in memory by only keeping current
candidate node lists in memory during its search.
The implementation is adapted from the algorithm by Zhang, et al. (2005)1 to output all cliques discovered.
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.
References
3.9.2 networkx.algorithms.clique.find_cliques
find_cliques(G)
Returns all maximal cliques in an undirected graph.
For each node v, a maximal clique for v is a largest complete subgraph containing v. The largest maximal clique
is sometimes called the maximum clique.
This function returns an iterator over cliques, each of which is a list of nodes. It is an iterative implementation,
so should not suffer from recursion depth issues.
Parameters G (NetworkX graph) – An undirected graph.
Returns An iterator over maximal cliques, each of which is a list of nodes in G. The order of cliques
is arbitrary.
Return type iterator
1 Yun Zhang, Abu-Khzam, F.N., Baldwin, N.E., Chesler, E.J., Langston, M.A., Samatova, N.F., “Genome-Scale Computational Approaches to
Memory-Intensive Applications in Systems Biology”. Supercomputing, 2005. Proceedings of the ACM/IEEE SC 2005 Conference, pp. 12, 12–18
Nov. 2005. <https://doi.org/10.1109/SC.2005.29>.
See also:
Notes
To obtain a list of all maximal cliques, use list(find_cliques(G)). However, be aware that in the worst-
case, the length of this list can be exponential in the number of nodes in the graph (for example, when the graph
is the complete graph). This function avoids storing all cliques in memory by only keeping current candidate
node lists in memory during its search.
This implementation is based on the algorithm published by Bron and Kerbosch (1973)1 , as adapted by Tomita,
Tanaka and Takahashi (2006)2 and discussed in Cazals and Karande (2008)3 . It essentially unrolls the re-
cursion used in the references to avoid issues of recursion stack depth (for a recursive implementation, see
find_cliques_recursive()).
This algorithm ignores self-loops and parallel edges, since cliques are not conventionally defined with such
edges.
References
3.9.3 networkx.algorithms.clique.make_max_clique_graph
make_max_clique_graph(G, create_using=None)
Returns the maximal clique graph of the given graph.
The nodes of the maximal clique graph of G are the cliques of G and an edge joins two cliques if the cliques are
not disjoint.
Parameters
• G (NetworkX graph)
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns A graph whose nodes are the cliques of G and whose edges join two cliques if they are not
disjoint.
Return type NetworkX graph
Notes
import networkx as nx
G = nx.make_clique_bipartite(G)
cliques = [v for v in G.nodes() if G.nodes[v]['bipartite'] == 0]
G = nx.bipartite.project(G, cliques)
G = nx.relabel_nodes(G, {-v: v - 1 for v in G})
1 Bron, C. and Kerbosch, J. “Algorithm 457: finding all cliques of an undirected graph”. Communications of the ACM 16, 9 (Sep. 1973),
575–577. <http://portal.acm.org/citation.cfm?doid=362342.362367>
2 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 <https://doi.org/10.1016/j.tcs.2006.06.015>
3 F. Cazals, C. Karande, “A note on the problem of reporting maximal cliques”, Theoretical Computer Science, Volume 407, Issues 1–3, 6
3.9.4 networkx.algorithms.clique.make_clique_bipartite
3.9.5 networkx.algorithms.clique.graph_clique_number
graph_clique_number(G, cliques=None)
Returns the clique number of the graph.
The clique number of a graph is the size of the largest clique in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The size of the largest clique in G.
Return type int
Notes
You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.
3.9.6 networkx.algorithms.clique.graph_number_of_cliques
graph_number_of_cliques(G, cliques=None)
Returns the number of maximal cliques in the graph.
Parameters
• G (NetworkX graph) – An undirected graph.
• cliques (list) – A list of cliques, each of which is itself a list of nodes. If not specified, the
list of all cliques will be computed, as by find_cliques().
Returns The number of maximal cliques in G.
Return type int
Notes
You should provide cliques if you have already computed the list of maximal cliques, in order to avoid an
exponential time search for maximal cliques.
3.9.7 networkx.algorithms.clique.node_clique_number
3.9.8 networkx.algorithms.clique.number_of_cliques
3.9.9 networkx.algorithms.clique.cliques_containing_node
3.10 Clustering
3.10.1 networkx.algorithms.cluster.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 – Number of triangles keyed by node label.
Return type dictionary
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]
Notes
When computing triangles for the entire graph each triangle is counted three times, once at each node. Self
loops are ignored.
3.10.2 networkx.algorithms.cluster.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 – Transitivity
Return type float
Examples
>>> G = nx.complete_graph(5)
>>> print(nx.transitivity(G))
1.0
3.10.3 networkx.algorithms.cluster.clustering
where 𝑇 (𝑢) is the number of triangles through node 𝑢 and 𝑑𝑒𝑔(𝑢) is the degree of 𝑢.
For weighted graphs, there are several ways to define clustering1 . the one used here is defined as the geometric
average of the subgraph edge weights2 ,
1 ∑︁
𝑐𝑢 = (𝑤
ˆ𝑢𝑣 𝑤 ˆ𝑣𝑤 )1/3 .
ˆ𝑢𝑤 𝑤
𝑑𝑒𝑔(𝑢)(𝑑𝑒𝑔(𝑢) − 1)) 𝑣𝑤
where 𝑇 (𝑢) is the number of directed triangles through node 𝑢, 𝑑𝑒𝑔 𝑡𝑜𝑡 (𝑢) is the sum of in degree and out degree
of 𝑢 and 𝑑𝑒𝑔 ↔ (𝑢) is the reciprocal degree of 𝑢.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute clustering for
nodes in this container.
• weight (string or None, optional (default=None)) – The edge attribute that holds the numer-
ical value used as a weight. If None, then each edge has weight 1.
Returns out – Clustering coefficient at specified nodes
Return type float, or dictionary
1 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
2 Intensity and coherence of motifs in weighted complex networks by J. P. Onnela, J. Saramäki, J. Kertész, and K. Kaski, Physical Review E,
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}
Notes
References
3.10.4 networkx.algorithms.cluster.average_clustering
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.average_clustering(G))
1.0
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
3.10.5 networkx.algorithms.cluster.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 node1
∑︀𝑘𝑣 ∑︀𝑘𝑣
𝑤=𝑢+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 – A dictionary keyed by node with the square clustering coefficient value.
Return type dictionary
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}
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
3.10.6 networkx.algorithms.cluster.generalized_degree
generalized_degree(G, nodes=None)
Compute the generalized degree for nodes.
For each node, the generalized degree shows how many edges of given triangle multiplicity the node is connected
to. The triangle multiplicity of an edge is the number of triangles an edge participates in. The generalized degree
(0) (𝑁 −2) (𝑗)
of node 𝑖 can be written as a vector k𝑖 = (𝑘𝑖 , . . . , 𝑘𝑖 ) where 𝑘𝑖 is the number of edges attached to node
𝑖 that participate in 𝑗 triangles.
1 Pedro G. Lind, Marta C. González, and Hans J. Herrmann. 2005 Cycles and clustering in bipartite networks. Physical Review E (72) 056127.
Parameters
• G (graph)
• nodes (container of nodes, optional (default=all nodes in G)) – Compute the generalized
degree for nodes in this container.
Returns out – Generalized degree of specified nodes. The Counter is keyed by edge triangle multi-
plicity.
Return type Counter, or dictionary of Counters
Examples
>>> G=nx.complete_graph(5)
>>> print(nx.generalized_degree(G,0))
Counter({3: 4})
>>> print(nx.generalized_degree(G))
{0: Counter({3: 4}), 1: Counter({3: 4}), 2: Counter({3: 4}), 3: Counter({3: 4}),
˓→4: Counter({3: 4})}
>>> k1 = nx.generalized_degree(G,0)
>>> sum([k*v for k,v in k1.items()])/2 == nx.triangles(G,0)
True
Notes
In a network of N nodes, the highest triangle multiplicty an edge can have is N-2.
The return value does not include a zero entry if no edges of a particular triangle multiplicity are present.
The number of triangles node 𝑖 is attached to can be recovered from the generalized degree k𝑖 =
(0) (𝑁 −2) (1) (2) (𝑁 −2)
(𝑘𝑖 , . . . , 𝑘𝑖 ) by (𝑘𝑖 + 2𝑘𝑖 + . . . + (𝑁 − 2)𝑘𝑖 )/2.
References
3.11 Coloring
greedy_color(G[, strategy, interchange]) Color a graph using various strategies of greedy graph
coloring.
3.11.1 networkx.algorithms.coloring.greedy_color
Parameters
• G (NetworkX graph)
• strategy (string or function(G, colors)) – A function (or a string representing a function) that
provides the coloring strategy, by returning nodes in the ordering they should be colored. G
is the graph, and colors is a dictionary of the currently assigned colors, keyed by nodes.
The function must return an iterable over all the nodes in G.
If the strategy function is an iterator generator (that is, a function with yield statements),
keep in mind that the colors dictionary will be updated after each yield, since this
function chooses colors greedily.
If strategy is a string, it must be one of the following, each of which represents one of
the built-in strategy functions.
– 'largest_first'
– 'random_sequential'
– 'smallest_last'
– 'independent_set'
– 'connected_sequential_bfs'
– 'connected_sequential_dfs'
– 'connected_sequential' (alias for the previous strategy)
– 'strategy_saturation_largest_first'
– 'DSATUR' (alias for the previous strategy)
• interchange (bool) – Will use the color interchange algorithm described by3 if set to True.
Note that strategy_saturation_largest_first and
strategy_independent_set do not work with interchange. Furthermore, if
you use interchange with your own strategy function, you cannot rely on the values in the
colors argument.
Returns
• A dictionary with keys representing nodes and values representing
• corresponding coloring.
Examples
>>> G = nx.cycle_graph(4)
>>> d = nx.coloring.greedy_color(G, strategy='largest_first')
>>> d in [{0: 0, 1: 1, 2: 0, 3: 1}, {0: 1, 1: 0, 2: 1, 3: 0}]
True
45353-7.
References
Some node ordering strategies are provided for use with greedy_color().
3.11.2 networkx.algorithms.coloring.strategy_connected_sequential
3.11.3 networkx.algorithms.coloring.strategy_connected_sequential_dfs
strategy_connected_sequential_dfs(G, colors)
Returns an iterable over nodes in G in the order given by a depth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.
3.11.4 networkx.algorithms.coloring.strategy_connected_sequential_bfs
strategy_connected_sequential_bfs(G, colors)
Returns an iterable over nodes in G in the order given by a breadth-first traversal.
The generated sequence has the property that for each node except the first, at least one neighbor appeared
earlier in the sequence.
G is a NetworkX graph. colors is ignored.
3.11.5 networkx.algorithms.coloring.strategy_independent_set
strategy_independent_set(G, colors)
Uses a greedy independent set removal strategy to determine the colors.
This function updates colors in-place and return None, unlike the other strategy functions in this module.
This algorithm repeatedly finds and removes a maximal independent set, assigning each node in the set an
unused color.
G is a NetworkX graph.
This strategy is related to strategy_smallest_last(): in that strategy, an independent set of size one is
chosen at each step instead of a maximal independent set.
3.11.6 networkx.algorithms.coloring.strategy_largest_first
strategy_largest_first(G, colors)
Returns a list of the nodes of G in decreasing order by degree.
G is a NetworkX graph. colors is ignored.
3.11.7 networkx.algorithms.coloring.strategy_random_sequential
3.11.8 networkx.algorithms.coloring.strategy_saturation_largest_first
strategy_saturation_largest_first(G, colors)
Iterates over all the nodes of G in “saturation order” (also known as “DSATUR”).
G is a NetworkX graph. colors is a dictionary mapping nodes of G to colors, for those nodes that have already
been colored.
3.11.9 networkx.algorithms.coloring.strategy_smallest_last
strategy_smallest_last(G, colors)
Returns a deque of the nodes of G, “smallest” last.
Specifically, the degrees of each node are tracked in a bucket queue. From this, the node of minimum degree is
repeatedly popped from the graph, updating its neighbors’ degrees.
G is a NetworkX graph. colors is ignored.
This implementation of the strategy runs in 𝑂(𝑛 + 𝑚) time (ignoring polylogarithmic factors), where 𝑛 is the
number of nodes and 𝑚 is the number of edges.
This strategy is related to strategy_independent_set(): if we interpret each node removed as an
independent set of size one, then this strategy chooses an independent set of size one instead of a maximal
independent set.
3.12 Communicability
Communicability.
3.12.1 networkx.algorithms.communicability_alg.communicability
communicability(G)
Returns 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)
Returns comm – Dictionary of dictionaries keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
Raises NetworkXError – If the graph is not undirected and simple.
See also:
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 u and v based on the graph spectrum is1
𝑛
∑︁
𝐶(𝑢, 𝑣) = 𝜑𝑗 (𝑢)𝜑𝑗 (𝑣)𝑒𝜆𝑗 ,
𝑗=1
where phi_{j}(u) is the urm{th} element of the jrm{th} orthonormal eigenvector of the adjacency
matrix associated with the eigenvalue lambda_{j}.
References
Examples
>>> G = nx.Graph([(0,1),(1,2),(1,5),(5,4),(2,4),(2,3),(4,3),(3,6)])
>>> c = nx.communicability(G)
1 Ernesto Estrada, Naomichi Hatano, “Communicability in complex networks”, Phys. Rev. E 77, 036111 (2008). https://arxiv.org/abs/0707.0756
3.12.2 networkx.algorithms.communicability_alg.communicability_exp
communicability_exp(G)
Returns 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 keyed by nodes with communicability as the value.
Return type dictionary of dictionaries
Raises NetworkXError – If the graph is not undirected and simple.
See also:
Notes
References
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)
3.13 Communities
3.13.1 Bipartitions
networkx.algorithms.community.kernighan_lin.kernighan_lin_bisection
References
3.13.2 Generators
LFR_benchmark_graph(n, tau1, tau2, mu[, . . . ]) Returns the LFR benchmark graph for testing
community-finding algorithms.
networkx.algorithms.community.community_generators.LFR_benchmark_graph
Parameters
• n (int) – Number of nodes in the created graph.
• tau1 (float) – Power law exponent for the degree distribution of the created graph. This
value must be strictly greater than one.
• tau2 (float) – Power law exponent for the community size distribution in the created graph.
This value must be strictly greater than one.
• mu (float) – Fraction of intra-community edges incident to each node. This value must be
in the interval [0, 1].
• average_degree (float) – Desired average degree of nodes in the created graph. This value
must be in the interval [0, n]. Exactly one of this and min_degree must be specified,
otherwise a NetworkXError is raised.
• min_degree (int) – Minimum degree of nodes in the created graph. This value must be in
the interval [0, n]. Exactly one of this and average_degree must be specified, otherwise
a NetworkXError is raised.
• max_degree (int) – Maximum degree of nodes in the created graph. If not specified, this is
set to n, the total number of nodes in the graph.
• min_community (int) – Minimum size of communities in the graph. If not specified, this is
set to min_degree.
• max_community (int) – Maximum size of communities in the graph. If not specified, this
is set to n, the total number of nodes in the graph.
• tol (float) – Tolerance when comparing floats, specifically when comparing average degree
values.
• max_iters (int) – Maximum number of iterations to try to create the community sizes, de-
gree distribution, and community affiliations.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns
G – The LFR benchmark graph generated according to the specified parameters.
Each node in the graph has a node attribute 'community' that stores the community (that is,
the set of nodes) that includes it.
Return type NetworkX graph
Raises
• NetworkXError – If any of the parameters do not meet their upper and lower bounds:
– tau1 and tau2 must be strictly greater than 1.
– mu must be in [0, 1].
– max_degree must be in {1, . . . , n}.
– min_community and max_community must be in {0, . . . , n}.
If not exactly one of average_degree and min_degree is specified.
If min_degree is not specified and a suitable min_degree cannot be found.
• ExceededMaxIterations – If a valid degree sequence cannot be created within
max_iters number of iterations.
If a valid set of community sizes cannot be created within max_iters number of iterations.
If a valid community assignment cannot be created within 10 * n * max_iters num-
ber of iterations.
Examples
Basic usage:
Continuing the example above, you can get the communities from the node attributes of the graph:
Notes
This algorithm differs slightly from the original way it was presented in [1].
1) Rather than connecting the graph via a configuration model then rewiring to match the intra-community
and inter-community degrees, we do this wiring explicitly at the end, which should be equivalent.
2) The code posted on the author’s website [2] calculates the random power law distributed variables and their
average using continuous approximations, whereas we use the discrete distributions here as both degree
and community size are discrete.
Though the authors describe the algorithm as quite robust, testing during development indicates that a somewhat
narrower parameter set is likely to successfully produce a graph. Some suggestions have been provided in the
event of exceptions.
References
3.13.3 K-Clique
k_clique_communities(G, k[, cliques]) Find k-clique communities in graph using the percola-
tion method.
networkx.algorithms.community.kclique.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
Return type Yields sets of nodes, one for each k-clique community.
Examples
References
networkx.algorithms.community.modularity_max.greedy_modularity_communities
greedy_modularity_communities(G, weight=None)
Find communities in graph using Clauset-Newman-Moore greedy modularity maximization. This method cur-
rently supports the Graph class and does not consider edge weights.
Greedy modularity maximization begins with each node in its own community and joins the pair of communities
that most increases modularity until no such pair exists.
Parameters G (NetworkX graph)
Returns
Return type Yields sets of nodes, one for each community.
Examples
References
networkx.algorithms.community.label_propagation.asyn_lpa_communities
Notes
References
networkx.algorithms.community.label_propagation.label_propagation_communities
label_propagation_communities(G)
Generates community sets determined by label propagation
Finds communities in G using a semi-synchronous label propagation method[1]_. This method combines the
advantages of both the synchronous and asynchronous models. Not implemented for directed graphs.
Parameters G (graph) – An undirected NetworkX graph.
Yields communities (generator) – Yields sets of the nodes in each community.
Raises NetworkXNotImplemented – If the graph is directed
References
networkx.algorithms.community.asyn_fluid.asyn_fluidc
//arxiv.org/pdf/1703.09307.pdf].
fluids interacting in an environment, expanding and pushing each other. It’s initialization is random, so found
communities may vary on different executions.
The algorithm proceeds as follows. First each of the initial k communities is initialized in a random vertex in the
graph. Then the algorithm iterates over all vertices in a random order, updating the community of each vertex
based on its own community and the communities of its neighbours. This process is performed several times
until convergence. At all times, each community has a total density of 1, which is equally distributed among
the vertices it contains. If a vertex changes of community, vertex densities of affected communities are adjusted
immediately. When a complete iteration over all vertices is done, such that no vertex changes the community it
belongs to, the algorithm has converged and returns.
This is the original version of the algorithm described in1 . Unfortunately, it does not support weighted graphs
yet.
Parameters
• G (Graph)
• k (integer) – The number of communities to be found.
• max_iter (integer) – The number of maximum iterations allowed. By default 15.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns communities – Iterable of communities given as sets of nodes.
Return type iterable
Notes
References
networkx.algorithms.community.quality.coverage
coverage(G, partition)
Returns the coverage of a partition.
The coverage of a partition is the ratio of the number of intra-community edges to the total number of edges in
the graph.
Parameters
• G (NetworkX graph)
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The coverage of the partition, as defined above.
Notes
References
networkx.algorithms.community.quality.performance
performance(G, partition)
Returns the performance of a partition.
The performance of a partition is the ratio of the number of intra-community edges plus inter-community non-
edges with the total number of potential edges.
Parameters
• G (NetworkX graph) – A simple graph (directed or undirected).
• partition (sequence) – Partition of the nodes of G, represented as a sequence of sets of
nodes. Each block of the partition represents a community.
Returns The performance of the partition, as defined above.
Return type float
Raises NetworkXError – If partition is not a valid partition of the nodes of G.
References
networkx.algorithms.community.centrality.girvan_newman
girvan_newman(G, most_valuable_edge=None)
Finds communities in a graph using the Girvan–Newman method.
Parameters
• G (NetworkX graph)
• most_valuable_edge (function) – Function that takes a graph as input and outputs an edge.
The edge returned by this function will be recomputed and removed at each iteration of the
algorithm.
If not specified, the edge with the highest networkx.
edge_betweenness_centrality() will be used.
Returns Iterator over tuples of sets of nodes in G. Each set of node is a community, each tuple is a
sequence of communities at a particular level of the algorithm.
Return type iterator
Examples
>>> G = nx.path_graph(10)
>>> comp = girvan_newman(G)
>>> tuple(sorted(c) for c in next(comp))
([0, 1, 2, 3, 4], [5, 6, 7, 8, 9])
To stop getting tuples of communities once the number of communities is greater than k, use itertools.
takewhile():
To utilize edge weights when choosing an edge with, for example, the highest betweenness centrality:
To specify a different ranking algorithm for edges, use the most_valuable_edge keyword argument:
Notes
The Girvan–Newman algorithm detects communities by progressively removing edges from the original graph.
The algorithm removes the “most valuable” edge, traditionally the edge with the highest betweenness centrality,
at each step. As the graph breaks down into pieces, the tightly knit community structure is exposed and the
result can be depicted as a dendrogram.
networkx.algorithms.community.community_utils.is_partition
is_partition(G, communities)
Returns True if and only if communities is a partition of the nodes of G.
A partition of a universe set is a family of pairwise disjoint sets whose union is the entire universe set.
G is a NetworkX graph.
communities is an iterable of sets of nodes of G. This iterable will be consumed multiple times during the
execution of this function.
3.14 Components
3.14.1 Connectivity
networkx.algorithms.components.is_connected
is_connected(G)
Returns True if the graph is connected, False otherwise.
Parameters G (NetworkX Graph) – An undirected graph.
Returns connected – True if the graph is connected, false otherwise.
Return type bool
Raises NetworkXNotImplemented: – If G is directed.
Examples
>>> G = nx.path_graph(4)
>>> print(nx.is_connected(G))
True
See also:
is_strongly_connected(), is_weakly_connected(), is_semiconnected(),
is_biconnected(), connected_components()
Notes
networkx.algorithms.components.number_connected_components
number_connected_components(G)
Returns the number of connected components.
Parameters G (NetworkX graph) – An undirected graph.
Returns n – Number of connected components
Return type integer
See also:
connected_components(), number_weakly_connected_components(),
number_strongly_connected_components()
Notes
networkx.algorithms.components.connected_components
connected_components(G)
Generate connected components.
Parameters G (NetworkX graph) – An undirected graph
Returns comp – A generator of sets of nodes, one for each component of G.
Return type generator of sets
Raises NetworkXNotImplemented: – If G is directed.
Examples
>>> G = nx.path_graph(4)
>>> nx.add_path(G, [10, 11, 12])
>>> [len(c) for c in sorted(nx.connected_components(G), key=len, reverse=True)]
[4, 3]
If you only want the largest connected component, it’s more efficient to use max instead of sort.
See also:
strongly_connected_components(), weakly_connected_components()
Notes
networkx.algorithms.components.connected_component_subgraphs
connected_component_subgraphs(G, copy=True)
DEPRECATED: Use (G.subgraph(c) for c in connected_components(G))
Or (G.subgraph(c).copy() for c in connected_components(G))
networkx.algorithms.components.node_connected_component
node_connected_component(G, n)
Returns the set of nodes in the component of graph containing node n.
Parameters
• G (NetworkX Graph) – An undirected graph.
• n (node label) – A node in G
Notes
networkx.algorithms.components.is_strongly_connected
is_strongly_connected(G)
Test directed graph for strong connectivity.
A directed graph is strongly connected if and only if every vertex in the graph is reachable from every other
vertex.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is strongly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented: – If G is undirected.
See also:
is_weakly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
strongly_connected_components()
Notes
networkx.algorithms.components.number_strongly_connected_components
number_strongly_connected_components(G)
Returns number of strongly connected components in graph.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of strongly connected components
Return type integer
Raises NetworkXNotImplemented: – If G is undirected.
See also:
strongly_connected_components(), number_connected_components(),
number_weakly_connected_components()
Notes
networkx.algorithms.components.strongly_connected_components
strongly_connected_components(G)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented : – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort.
See also:
connected_components(), weakly_connected_components(),
kosaraju_strongly_connected_components()
Notes
References
networkx.algorithms.components.strongly_connected_component_subgraphs
strongly_connected_component_subgraphs(G, copy=True)
DEPRECATED: Use (G.subgraph(c) for c in strongly_connected_components(G))
Or (G.subgraph(c).copy() for c in strongly_connected_components(G))
networkx.algorithms.components.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) – A directed graph.
Returns comp – A generator of sets of nodes, one for each strongly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented : – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort.
See also:
connected_components()
Notes
References
networkx.algorithms.components.kosaraju_strongly_connected_components
kosaraju_strongly_connected_components(G, source=None)
Generate nodes in strongly connected components of graph.
Parameters G (NetworkX Graph) – A directed graph.
Returns comp – A genrator of sets of nodes, one for each strongly connected component of G.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort.
See also:
strongly_connected_components()
Notes
networkx.algorithms.components.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 pro-
vided, the elements in scc must partition the nodes in G. If not provided, it will be calculated
as scc=nx.strongly_connected_components(G).
Returns C – 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 set of original nodes in G
that form the SCC that the node in C represents.
Return type NetworkX DiGraph
Raises NetworkXNotImplemented: – If G is undirected.
Notes
After contracting all strongly connected components to a single node, the resulting graph is a directed acyclic
graph.
networkx.algorithms.components.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.
Note that if a graph is strongly connected (i.e. the graph is connected even when we account for directionality),
it is by definition weakly connected as well.
Parameters G (NetworkX Graph) – A directed graph.
Returns connected – True if the graph is weakly connected, False otherwise.
Return type bool
Raises NetworkXNotImplemented: – If G is undirected.
See also:
is_strongly_connected(), is_semiconnected(), is_connected(), is_biconnected(),
weakly_connected_components()
Notes
networkx.algorithms.components.number_weakly_connected_components
number_weakly_connected_components(G)
Returns the number of weakly connected components in G.
Parameters G (NetworkX graph) – A directed graph.
Returns n – Number of weakly connected components
Return type integer
Raises NetworkXNotImplemented: – If G is undirected.
See also:
weakly_connected_components(), number_connected_components(),
number_strongly_connected_components()
Notes
networkx.algorithms.components.weakly_connected_components
weakly_connected_components(G)
Generate weakly connected components of G.
Parameters G (NetworkX graph) – A directed graph
Returns comp – A generator of sets of nodes, one for each weakly connected component of G.
Return type generator of sets
Raises NetworkXNotImplemented: – If G is undirected.
Examples
If you only want the largest component, it’s more efficient to use max instead of sort:
See also:
connected_components(), strongly_connected_components()
Notes
networkx.algorithms.components.weakly_connected_component_subgraphs
weakly_connected_component_subgraphs(G, copy=True)
DEPRECATED: Use (G.subgraph(c) for c in weakly_connected_components(G))
Or (G.subgraph(c).copy() for c in weakly_connected_components(G))
networkx.algorithms.components.is_attracting_component
is_attracting_component(G)
Returns True if G consists of a single attracting component.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns attracting – True if G has a single attracting component. Otherwise, False.
Return type bool
Raises NetworkXNotImplemented : – If the input graph is undirected.
See also:
attracting_components(), number_attracting_components()
networkx.algorithms.components.number_attracting_components
number_attracting_components(G)
Returns the number of attracting components in G.
Parameters G (DiGraph, MultiDiGraph) – The graph to be analyzed.
Returns n – The number of attracting components in G.
Return type int
Raises NetworkXNotImplemented : – If the input graph is undirected.
See also:
attracting_components(), is_attracting_component()
networkx.algorithms.components.attracting_components
attracting_components(G)
Generates the attracting components in G.
An attracting component in a directed graph G 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 – A generator of sets of nodes, one for each attracting component of G.
Return type generator of sets
Raises NetworkXNotImplemented : – If the input graph is undirected.
See also:
number_attracting_components(), is_attracting_component()
networkx.algorithms.components.attracting_component_subgraphs
attracting_component_subgraphs(G, copy=True)
DEPRECATED: Use (G.subgraph(c) for c in attracting_components(G))
Or (G.subgraph(c).copy() for c in attracting_components(G))
networkx.algorithms.components.is_biconnected
is_biconnected(G)
Returns 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 – True if the graph is biconnected, False otherwise.
Return type bool
Raises NetworkXNotImplemented : – If the input graph is not undirected.
Examples
>>> G = nx.path_graph(4)
>>> print(nx.is_biconnected(G))
False
>>> G.add_edge(0, 3)
>>> print(nx.is_biconnected(G))
True
See also:
biconnected_components(), articulation_points(), biconnected_component_edges(),
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_semiconnected()
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 n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n 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
networkx.algorithms.components.biconnected_components
biconnected_components(G)
Returns 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 of sets of nodes, one set for each biconnected component.
Return type generator
Raises NetworkXNotImplemented : – If the input graph is not undirected.
See also:
Examples
>>> G = nx.lollipop_graph(5, 1)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
2
>>> G.add_edge(0, 5)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents = list(nx.biconnected_components(G))
>>> len(bicomponents)
1
You can generate a sorted list of biconnected components, largest first, using sort.
>>> G.remove_edge(0, 5)
>>> [len(c) for c in sorted(nx.biconnected_components(G), key=len, reverse=True)]
[5, 2]
If you only want the largest connected component, it’s more efficient to use max instead of sort.
See also:
is_biconnected(), articulation_points(), biconnected_component_edges()
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 n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n 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
networkx.algorithms.components.biconnected_component_edges
biconnected_component_edges(G)
Returns 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 of edges, one list for each bicomponent.
Return type generator of lists
Raises NetworkXNotImplemented : – If the input graph is not undirected.
Examples
>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
>>> len(bicomponents_edges)
5
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> bicomponents_edges = list(nx.biconnected_component_edges(G))
(continues on next page)
See also:
is_biconnected(), biconnected_components(), articulation_points()
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 n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n 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
networkx.algorithms.components.biconnected_component_subgraphs
biconnected_component_subgraphs(G, copy=True)
DEPRECATED: Use (G.subgraph(c) for c in biconnected_components(G))
Or (G.subgraph(c).copy() for c in biconnected_components(G))
networkx.algorithms.components.articulation_points
articulation_points(G)
Yield the 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.
Yields node – An articulation point in the graph.
Raises NetworkXNotImplemented : – If the input graph is not undirected.
Examples
>>> G = nx.barbell_graph(4, 2)
>>> print(nx.is_biconnected(G))
False
>>> len(list(nx.articulation_points(G)))
4
>>> G.add_edge(2, 8)
>>> print(nx.is_biconnected(G))
True
>>> len(list(nx.articulation_points(G)))
0
See also:
is_biconnected(), biconnected_components(), biconnected_component_edges()
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 n
is an articulation point if, and only if, there exists a subtree rooted at n such that there is no back edge from
any successor of n that links to a predecessor of n 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
3.14.6 Semiconnectedness
networkx.algorithms.components.is_semiconnected
is_semiconnected(G)
Returns 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 – True if the graph is semiconnected, False otherwise.
Return type bool
Raises
• NetworkXNotImplemented : – If the input graph is undirected.
• NetworkXPointlessConcept : – If the graph is empty.
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
See also:
is_strongly_connected(), is_weakly_connected(), is_connected(),
is_biconnected()
3.15 Connectivity
3.15.1 Edge-augmentation
networkx.algorithms.connectivity.edge_augmentation.k_edge_augmentation
minimizes the number of k-edge-connected components and maximizes the edge connectiv-
ity between those components. For details, see partial_k_edge_augmentation().
Yields edge (tuple) – Edges that, once added to G, would cause G to become k-edge-connected.
If partial is False, an error is raised if this is not possible. Otherwise, generated edges form a
partial augmentation, which k-edge-connects any part of G where it is possible, and maximally
connects the remaining parts.
Raises
• NetworkXUnfeasible: – If partial is False and no k-edge-augmentation exists.
• NetworkXNotImplemented: – If the input graph is directed or a multigraph.
• ValueError: – If k is less than 1
Notes
Example
Example
networkx.algorithms.connectivity.edge_augmentation.is_k_edge_connected
is_k_edge_connected(G, k)
Tests to see if a graph is k-edge-connected.
Is it impossible to disconnect the graph by removing fewer than k edges? If so, then G is k-edge-connected.
Parameters
• G (NetworkX graph) – An undirected graph.
• k (integer) – edge connectivity to test for
Returns True if G is k-edge-connected.
Return type boolean
See also:
is_locally_k_edge_connected()
Example
>>> G = nx.barbell_graph(10, 0)
>>> nx.is_k_edge_connected(G, k=1)
True
>>> nx.is_k_edge_connected(G, k=2)
False
networkx.algorithms.connectivity.edge_augmentation.is_locally_k_edge_connected
is_locally_k_edge_connected(G, s, t, k)
Tests to see if an edge in a graph is locally k-edge-connected.
Is it impossible to disconnect s and t by removing fewer than k edges? If so, then s and t are locally k-edge-
connected in G.
Parameters
• G (NetworkX graph) – An undirected graph.
• s (node) – Source node
• t (node) – Target node
• k (integer) – local edge connectivity for nodes s and t
Returns True if s and t are locally k-edge-connected in G.
Example
3.15.2 K-edge-components
networkx.algorithms.connectivity.edge_kcomponents.k_edge_components
k_edge_components(G, k)
Generates nodes in each maximal k-edge-connected component in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_components – will have k-edge-connectivity in the graph G.
Return type a generator of k-edge-ccs. Each set of returned nodes
See also:
local_edge_connectivity()
k_edge_subgraphs() similar to this function, but the subgraph defined by the nodes must also have k-
edge-connectivity.
Raises
• NetworkXNotImplemented: – If the input graph is a multigraph.
• ValueError: – If k is less than 1
Notes
Attempts to use the most efficient implementation available based on k. If k=1, this is simply simply connected
components for directed graphs and connected components for undirected graphs. If k=2 on an efficient bridge
connected component algorithm from _[1] is run based on the chain decomposition. Otherwise, the algorithm
from _[2] is used.
Example
References
networkx.algorithms.connectivity.edge_kcomponents.k_edge_subgraphs
k_edge_subgraphs(G, k)
Generates nodes in each maximal k-edge-connected subgraph in G.
Parameters
• G (NetworkX graph)
• k (Integer) – Desired edge connectivity
Returns k_edge_subgraphs – Each k-edge-subgraph is a maximal set of nodes that defines a sub-
graph of G that is k-edge-connected.
Return type a generator of k-edge-subgraphs
See also:
edge_connectivity()
k_edge_components() similar to this function, but nodes only need to have k-edge-connctivity within the
graph G and the subgraphs might not be k-edge-connected.
Raises
• NetworkXNotImplemented: – If the input graph is a multigraph.
Notes
Attempts to use the most efficient implementation available based on k. If k=1, or k=2 and the graph is undi-
rected, then this simply calls k_edge_components. Otherwise the algorithm from _[1] is used.
Example
References
networkx.algorithms.connectivity.edge_kcomponents.bridge_components
bridge_components(G)
Finds all bridge-connected components G.
Parameters G (NetworkX undirected graph)
Returns bridge_components
Return type a generator of 2-edge-connected components
See also:
k_edge_subgraphs() this function is a special case for an undirected graph where k=2.
biconnected_components() similar to this function, but is defined using 2-node-connectivity instead of
2-edge-connectivity.
Notes
Example
>>> # The barbell graph with parameter zero has a single bridge
>>> G = nx.barbell_graph(5, 0)
>>> from networkx.algorithms.connectivity.edge_kcomponents import bridge_
˓→components
networkx.algorithms.connectivity.edge_kcomponents.EdgeComponentAuxGraph
class EdgeComponentAuxGraph
A simple algorithm to find all k-edge-connected components in a graph.
Constructing the AuxillaryGraph (which may take some time) allows for the k-edge-ccs to be found in linear
time for arbitrary k.
Notes
This implementation is based on1 . The idea is to construct an auxiliary graph from which the k-edge-ccs can be
extracted in linear time. The auxiliary graph is constructed in 𝑂(|𝑉 | · 𝐹 ) operations, where F is the complexity
of max flow. Querying the components takes an additional 𝑂(|𝑉 |) operations. This algorithm can be slow for
large graphs, but it handles an arbitrary k and works for both directed and undirected inputs.
The undirected case for k=1 is exactly connected components. The undirected case for k=2 is exactly bridge
connected components. The directed case for k=1 is exactly strongly connected components.
References
Example
Example
__init__()
Initialize self. See help(type(self)) for accurate signature.
Methods
3.15.3 K-node-components
networkx.algorithms.connectivity.kcomponents.k_components
k_components(G, flow_func=None)
Returns the k-component structure of a graph G.
A k-component is a maximal subgraph of a graph G that has, at least, node connectivity k: we need to remove at
least k nodes to break it into more components. k-components have an inherent hierarchical structure because
they are nested in terms of connectivity: a connected graph can contain several 2-components, each of which
can contain one or more 3-components, and so forth.
Parameters
• G (NetworkX graph)
• flow_func (function) – Function to perform the underlying flow computations. Default value
edmonds_karp(). This function performs better in sparse graphs with right tailed degree
distributions. shortest_augmenting_path() will perform better in denser graphs.
Returns k_components – Dictionary with all connectivity levels k in the input Graph as keys and a
list of sets of nodes that form a k-component of level k as values.
Return type dict
Raises NetworkXNotImplemented: – If the input graph is directed.
Examples
Notes
Moody and White1 (appendix A) provide an algorithm for identifying k-components in a graph, which is
based on Kanevsky’s algorithm2 for finding all minimum-size node cut-sets of a graph (implemented in
all_node_cuts() function):
1. Compute node connectivity, k, of the input graph G.
2. Identify all k-cutsets at the current level of connectivity using Kanevsky’s algorithm.
3. Generate new graph components based on the removal of these cutsets. Nodes in a cutset belong to both
sides of the induced cut.
4. If the graph is neither complete nor trivial, return to 1; else end.
This implementation also uses some heuristics (see3 for details) to speed up the computation.
See also:
node_connectivity(), all_node_cuts()
biconnected_components() special case of this function when k=2
k_edge_components() similar to this function, but uses edge-connectivity instead of node-connectivity
References
3.15.4 K-node-cutsets
1 Moody, J. and D. White (2003). Social cohesion and embeddedness: A hierarchical conception of social groups. American Sociological
doi/10.1002/net.3230230604/abstract
3 Torrents, J. and F. Ferraro (2015). Structural Cohesion: Visualization and Heuristics for Fast Computation. https://arxiv.org/pdf/1503.04476v1
networkx.algorithms.connectivity.kcutsets.all_node_cuts
Examples
Notes
This implementation is based on the sequential algorithm for finding all minimum-size separating vertex sets in
a graph1 . The main idea is to compute minimum cuts using local maximum flow computations among a set of
nodes of highest degree and all other non-adjacent nodes in the Graph. Once we find a minimum cut, we add an
edge between the high degree node and the target node of the local maximum flow computation to make sure
that we will not find that minimum cut again.
See also:
node_connectivity(), edmonds_karp(), shortest_augmenting_path()
1 Kanevsky, A. (1993). Finding all minimum-size separating vertex sets in a graph. Networks 23(6), 533–541. http://onlinelibrary.wiley.com/
doi/10.1002/net.3230230604/abstract
References
edge_disjoint_paths(G, s, t[, flow_func, . . . ]) Returns the edges disjoint paths between source and tar-
get.
node_disjoint_paths(G, s, t[, flow_func, . . . ]) Computes node disjoint paths between source and tar-
get.
networkx.algorithms.connectivity.disjoint_paths.edge_disjoint_paths
Examples
We use in this example the platonic icosahedral graph, which has node edge connectivity 5, thus there are 5 edge
disjoint paths between any pair of nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.edge_disjoint_paths(G, 0, 6)))
5
If you need to compute edge disjoint paths 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 edge disjoint paths among all pairs of nodes of the platonic icosahedral graph
reusing the data structures.
You can also use alternative flow algorithms for computing edge disjoint paths. 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.
Notes
This is a flow based implementation of edge disjoint paths. We compute the maximum flow between source and
target on an auxiliary directed network. The saturated edges in the residual network after running the maximum
flow algorithm correspond to edge disjoint paths between source and target in the original network. This function
handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow package.
networkx.algorithms.connectivity.disjoint_paths.node_disjoint_paths
Examples
We use in this example the platonic icosahedral graph, which has node node connectivity 5, thus there are 5
node disjoint paths between any pair of non neighbor nodes.
>>> G = nx.icosahedral_graph()
>>> len(list(nx.node_disjoint_paths(G, 0, 6)))
5
If you need to compute node disjoint paths 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 con-
nectivity and node cuts, and the residual network for the underlying maximum flow computation.
Example of how to compute node disjoint paths reusing the data structures:
You can also use alternative flow algorithms for computing node disjoint paths. 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.
Notes
This is a flow based implementation of node disjoint paths. We compute the maximum flow between source
and target on an auxiliary directed network. The saturated edges in the residual network after running the
maximum flow algorithm correspond to node disjoint paths between source and target in the original network.
This function handles both directed and undirected graphs, and can use all flow algorithms from NetworkX flow
package.
See also:
edge_disjoint_paths(), node_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
networkx.algorithms.connectivity.connectivity.average_node_connectivity
average_node_connectivity(G, flow_func=None)
Returns the average connectivity of a graph G.
The average connectivity bar{kappa} of a graph G is the average of local node connectivity over all pairs of
nodes of G1 .
∑︀
𝑢,𝑣 𝜅𝐺 (𝑢, 𝑣)
𝜅
¯ (𝐺) = (︀𝑛)︀
2
Parameters
• G (NetworkX graph) – Undirected graph
• 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 details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See local_node_connectivity() for details. The
choice of the default function may change from version to version and should not be relied
on. Default value: None.
Returns K – Average node connectivity
Return type float
See also:
local_node_connectivity(), node_connectivity(), edge_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
networkx.algorithms.connectivity.connectivity.all_pairs_node_connectivity
//www.sciencedirect.com/science/article/pii/S0012365X01001807
See also:
local_node_connectivity(), edge_connectivity(), local_edge_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
networkx.algorithms.connectivity.connectivity.edge_connectivity
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.
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.
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 in1 ) 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 in1 . For directed graphs, the algorithm does n calls to the maximum
flow function. This is an implementation of algorithm 8 in1 .
See also:
local_edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path(),
k_edge_components(), k_edge_subgraphs()
References
networkx.algorithms.connectivity.connectivity.local_edge_connectivity
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
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.
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.
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 (u,‘v‘) with two reciprocal arcs (u, v) and (v, u) 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 in1 .
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).
See also:
edge_connectivity(), local_node_connectivity(), node_connectivity(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
networkx.algorithms.connectivity.connectivity.local_node_connectivity
• 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 parameter: edmonds_karp() and shortest_augmenting_path(). Other
algorithms will ignore this parameter. Default value: None.
Returns K – local node connectivity for nodes s and t
Return type integer
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
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.
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.
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 n nodes and m edges we derive a directed graph H with 2n nodes and 2m+n
arcs by replacing each original node v with two nodes v_A, v_B linked by an (internal) arc in H. Then for each
edge (u, v) in G we add two arcs (u_B, v_A) and (v_B, u_A) in H. Finally we set the attribute capacity = 1 for
each arc in H1 .
For a directed graph G having n nodes and m arcs we derive a directed graph H with 2n nodes and m+n arcs by
replacing each original node v with two nodes v_A, v_B linked by an (internal) arc (v_A, v_B) in H. Then for
each arc (u, v) in G we add one arc (u_B, v_A) 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.
See also:
local_edge_connectivity(), node_connectivity(), minimum_node_cut(),
maximum_flow(), edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
networkx.algorithms.connectivity.connectivity.node_connectivity
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.
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.
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 in1 .
See also:
local_node_connectivity(), edge_connectivity(), maximum_flow(),
edmonds_karp(), preflow_push(), shortest_augmenting_path()
References
networkx.algorithms.connectivity.cuts.minimum_edge_cut
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.
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.
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 in1 ) 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
in1 . For directed graphs, the algorithm does n calls to the max flow function. The function raises an error if the
directed graph is not weakly connected and returns an empty set if it is weakly connected. It is an implementation
of algorithm 8 in1 .
See also:
minimum_st_edge_cut(), minimum_node_cut(), stoer_wagner(),
node_connectivity(), edge_connectivity(), maximum_flow(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
References
networkx.algorithms.connectivity.cuts.minimum_node_cut
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.
If you specify a pair of nodes (source and target) as parameters, this function returns a local st node cut.
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.
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 in1 .
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()
References
networkx.algorithms.connectivity.cuts.minimum_st_edge_cut
• auxiliary (NetworkX DiGraph) – Auxiliary digraph to compute flow based node connectiv-
ity. It has to have a graph attribute called mapping with a dictionary mapping node names
in G and in the auxiliary digraph. If provided it will be reused instead of recreated. 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 details). If flow_func is None, the default maximum flow function
(edmonds_karp()) is used. See node_connectivity() for details. The choice of
the default function may change from version to version and should not be relied on. Default
value: None.
• residual (NetworkX DiGraph) – Residual network to compute maximum flow. If provided
it will be reused instead of recreated. Default value: None.
Returns cutset – Set of edges that, if removed from the graph, will disconnect it.
Return type set
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())
(continues on next page)
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.
networkx.algorithms.connectivity.cuts.minimum_st_node_cut
Examples
This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the
connectivity package:
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 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.
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 in1 .
See also:
minimum_node_cut(), minimum_edge_cut(), stoer_wagner(), node_connectivity(),
edge_connectivity(), maximum_flow(), edmonds_karp(), preflow_push(),
shortest_augmenting_path()
1 Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
References
stoer_wagner(G[, weight, heap]) Returns the weighted minimum edge cut using the
Stoer-Wagner algorithm.
networkx.algorithms.connectivity.stoerwagner.stoer_wagner
Parameters
• G (NetworkX graph) – Edges of the graph are expected to have an attribute named by the
weight parameter below. If this attribute is not present, the edge is considered to have unit
weight.
• weight (string) – Name of the weight attribute of the edges. If the attribute is not present,
unit weight is assumed. Default value: ‘weight’.
• heap (class) – Type of heap to be used in the algorithm. It should be a subclass of MinHeap
or implement a compatible interface.
If a stock heap implementation is to be used, BinaryHeap is recommended over
PairingHeap for Python implementations without optimized attribute accesses (e.g.,
CPython) despite a slower asymptotic running time. For Python implementations with opti-
mized attribute accesses (e.g., PyPy), PairingHeap provides better performance. Default
value: BinaryHeap.
Returns
• cut_value (integer or float) – The sum of weights of edges in a minimum cut.
• partition (pair of node lists) – A partitioning of the nodes that defines a minimum cut.
Raises
• NetworkXNotImplemented – If the graph is directed or a multigraph.
• NetworkXError – If the graph has less than two nodes, is not connected or has a negative-
weighted edge.
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
networkx.algorithms.connectivity.utils.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 (u,‘v‘) with two reciprocal arcs (u, v) and (v, u) 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 in1 .
References
networkx.algorithms.connectivity.utils.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 n nodes and m edges we derive a directed graph D with 2n nodes and 2m+n
arcs by replacing each original node v with two nodes vA, vB linked by an (internal) arc in D. Then for each
edge (u, v) in G we add two arcs (uB, vA) and (vB, uA) in D. Finally we set the attribute capacity = 1 for each
arc in D1 .
For a directed graph having n nodes and m arcs we derive a directed graph D with 2n nodes and m+n arcs by
replacing each original node v with two nodes vA, vB linked by an (internal) arc (vA, vB) in D. Then for each
arc (u, v) in G we add one arc (uB, vA) in D. Finally we set the attribute capacity = 1 for each arc in D.
1 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
1 Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, ‘Network Analysis: Methodological Foundations’,
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
3.16 Cores
3.16.1 networkx.algorithms.core.core_number
core_number(G)
Returns 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 – A dictionary keyed by node to the core number.
Return type dictionary
Raises NetworkXError – The k-core is not implemented for graphs with self loops or parallel
edges.
Notes
References
3.16.2 networkx.algorithms.core.k_core
Notes
References
3.16.3 networkx.algorithms.core.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.
See also:
core_number(), k_corona()
References
3.16.4 networkx.algorithms.core.k_crust
Notes
This definition of k-crust is different than the definition in1 . The k-crust in1 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.
See also:
core_number()
1 A model of Internet topology using k-shell decomposition Shai Carmi, Shlomo Havlin, Scott Kirkpatrick, Yuval Shavitt, and Eran Shir, PNAS
References
3.16.5 networkx.algorithms.core.k_corona
k_corona(G, k, core_number=None)
Returns 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 – The k-corona subgraph
Return type NetworkX graph
Raises NetworkXError – The k-cornoa is not defined for graphs with self loops or parallel edges.
Notes
References
3.17 Covering
3.17.1 networkx.algorithms.covering.min_edge_cover
min_edge_cover(G, matching_algorithm=None)
Returns a set of edges which constitutes the minimum edge cover of the graph.
A smallest edge cover can be found in polynomial time by finding a maximum matching and extending it
greedily so that all nodes are covered.
Parameters
• G (NetworkX graph) – An undirected bipartite graph.
Notes
An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of
the set. The minimum edge cover is an edge covering of smallest cardinality.
Due to its implementation, the worst-case running time of this algorithm is bounded by the worst-case running
time of the function matching_algorithm.
Minimum edge cover for bipartite graph can also be found using the function present in networkx.
algorithms.bipartite.covering
3.17.2 networkx.algorithms.covering.is_edge_cover
is_edge_cover(G, cover)
Decides whether a set of edges is a valid edge cover of the graph.
Given a set of edges, whether it is an edge covering can be decided if we just check whether all nodes of the
graph has an edge from the set, incident on it.
Parameters
• G (NetworkX graph) – An undirected bipartite graph.
• cover (set) – Set of edges to be checked.
Returns Whether the set of edges is a valid edge cover of the graph.
Return type bool
Notes
An edge cover of a graph is a set of edges such that every node of the graph is incident to at least one edge of
the set.
3.18 Cycles
cycle_basis(G[, root]) Returns a list of cycles which form a basis for cycles of
G.
Continued on next page
3.18.2 networkx.algorithms.cycles.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.
Parameters
• G (NetworkX Graph)
• root (node, optional) – Specify starting node for basis.
Returns
• A list of cycle lists. Each cycle list is a list of nodes
• which forms a cycle (loop) in G.
Examples
>>> G = nx.Graph()
>>> nx.add_cycle(G, [0, 1, 2, 3])
>>> nx.add_cycle(G, [0, 3, 4, 5])
>>> print(nx.cycle_basis(G, 0))
[[3, 4, 5, 0], [1, 2, 3, 0]]
Notes
References
See also:
simple_cycles()
3.18.3 networkx.algorithms.cycles.simple_cycles
simple_cycles(G)
Find simple cycles (elementary circuits) of a directed graph.
A simple cycle, or elementary circuit, is a closed path where no node appears twice. Two elemen-
tary circuits are distinct if they are not cyclic permutations of each other.
1 Paton, K. An algorithm for finding a fundamental set of cycles of a graph. Comm. ACM 12, 9 (Sept 1969), 514-518.
This is a nonrecursive, iterator/generator version of Johnson’s algorithm1 . There may be better algorithms for
some cases23 .
Parameters G (NetworkX DiGraph) – A directed graph
Returns cycle_generator – A generator that produces elementary cycles of the graph. Each cycle
is represented by a list of nodes along the cycle.
Return type generator
Examples
>>> edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> G = nx.DiGraph(edges)
>>> len(list(nx.simple_cycles(G)))
5
To filter the cycles so that they don’t include certain nodes or edges, copy your graph and eliminate those nodes
or edges before calling
Notes
References
See also:
cycle_basis()
3.18.4 networkx.algorithms.cycles.find_cycle
1137/0204007
2 Enumerating the cycles of a digraph: a new preprocessing strategy. G. Loizou and P. Thanish, Information Sciences, v. 27, 163-182, 1982.
3 A search strategy for the elementary cycles of a directed graph. J.L. Szwarcfiter and P.E. Lauer, BIT NUMERICAL MATHEMATICS, v. 16,
• source (node, list of nodes) – The node from which the traversal begins. If None, then a
source is chosen arbitrarily and repeatedly until all edges from each node in the graph are
searched.
• orientation (None | ‘original’ | ‘reverse’ | ‘ignore’ (default: None)) – For directed graphs
and directed multigraphs, edge traversals need not respect the original orientation of the
edges. When set to ‘reverse’ every edge is traversed in the reverse direction. When set to
‘ignore’, every edge is treated as undirected. When set to ‘original’, every edge is treated as
directed. In all three cases, the yielded edge tuples add a last entry to indicate the direction
in which that edge was traversed. If orientation is None, the yielded edge has no direction
indicated. The direction is respected, but not reported.
Returns edges – A list of directed edges indicating the path taken for the loop. If no cycle is found,
then an exception is raised. For graphs, an edge is of the form (u, v) where u and v are the
tail and head of the edge as determined by the traversal. For multigraphs, an edge is of the form
(u, v, key), where key is the key of the edge. When the graph is directed, then u and v
are always in the order of the actual directed edge. If orientation is not None then the edge tuple
is extended to include the direction of traversal (‘forward’ or ‘reverse’) on that edge.
Return type directed edges
Raises NetworkXNoCycle – If no cycle was found.
Examples
In this example, we construct a DAG and find, in the first call, that there are no directed cycles, and so an
exception is raised. In the second call, we ignore edge orientations and find that there is an undirected cycle.
Note that the second call finds a directed cycle while effectively traversing an undirected graph, and so, we
found an “undirected cycle”. This means that this DAG structure does not form a directed tree (which is also
known as a polytree).
3.18.5 networkx.algorithms.cycles.minimum_cycle_basis
minimum_cycle_basis(G, weight=None)
Returns a minimum weight cycle basis for G
Minimum weight means a cycle basis for which the total weight (length for unweighted graphs) of all the cycles
is minimum.
Parameters
• G (NetworkX Graph)
• weight (string) – name of the edge attribute to use for edge weights
Returns
• A list of cycle lists. Each cycle list is a list of nodes
• which forms a cycle (loop) in G. Note that the nodes are not
• necessarily returned in a order by which they appear in the cycle
Examples
>>> G=nx.Graph()
>>> G.add_cycle([0,1,2,3])
>>> G.add_cycle([0,3,4,5])
>>> print(nx.minimum_cycle_basis(G))
[[0, 1, 2, 3], [0, 3, 4, 5]]
References
[1] Kavitha, Telikepalli, et al. “An O(m^2n) Algorithm for Minimum Cycle Basis of Graphs.” http://link.
springer.com/article/10.1007/s00453-007-9064-z [2] de Pina, J. 1995. Applications of shortest path methods.
Ph.D. thesis, University of Amsterdam, Netherlands
See also:
simple_cycles(), cycle_basis()
3.19 Cuts
3.19.1 networkx.algorithms.cuts.boundary_expansion
boundary_expansion(G, S)
Returns the boundary expansion of the set S.
The boundary expansion is the quotient of the size of the edge boundary and the cardinality of S. [1]
Parameters
• G (NetworkX graph)
• S (sequence) – A sequence of nodes in G.
Returns The boundary expansion of the set S.
Return type number
See also:
References
3.19.2 networkx.algorithms.cuts.conductance
References
3.19.3 networkx.algorithms.cuts.cut_size
Examples
In the graph with two cliques joined by a single edges, the natural bipartition of the graph into two blocks, one
for each clique, yields a cut of weight one:
>>> G = nx.barbell_graph(3, 0)
>>> S = {0, 1, 2}
>>> T = {3, 4, 5}
>>> nx.cut_size(G, S, T)
1
Each parallel edge in a multigraph is counted when determining the cut size:
Notes
In a multigraph, the cut size is the total weight of edges including multiplicity.
3.19.4 networkx.algorithms.cuts.edge_expansion
References
3.19.5 networkx.algorithms.cuts.mixing_expansion
Parameters
• G (NetworkX graph)
• S (sequence) – A sequence of nodes in G.
• T (sequence) – A sequence of nodes in G.
• weight (object) – Edge attribute key to use as weight. If not specified, edges have weight
one.
Returns The mixing expansion between the two sets S and T.
Return type number
See also:
boundary_expansion(), edge_expansion(), node_expansion()
References
3.19.6 networkx.algorithms.cuts.node_expansion
node_expansion(G, S)
Returns the node expansion of the set S.
The node expansion is the quotient of the size of the node boundary of S and the cardinality of S. [1]
Parameters
• G (NetworkX graph)
• S (sequence) – A sequence of nodes in G.
Returns The node expansion of the set S.
Return type number
See also:
boundary_expansion(), edge_expansion(), mixing_expansion()
References
3.19.7 networkx.algorithms.cuts.normalized_cut_size
Notes
In a multigraph, the cut size is the total weight of edges including multiplicity.
See also:
conductance(), cut_size(), edge_expansion(), volume()
References
3.19.8 networkx.algorithms.cuts.volume
volume(G, S, weight=None)
Returns the volume of a set of nodes.
The volume of a set S is the sum of the (out-)degrees of nodes in S (taking into account parallel edges in
multigraphs). [1]
Parameters
• G (NetworkX graph)
• S (sequence) – A sequence of nodes in G.
• weight (object) – Edge attribute key to use as weight. If not specified, edges have weight
one.
Returns The volume of the set of nodes represented by S in the graph G.
Return type number
See also:
conductance(), cut_size(), edge_expansion(), edge_boundary(),
normalized_cut_size()
References
3.20.1 networkx.algorithms.dag.ancestors
ancestors(G, source)
Returns all nodes having a path to source in G.
Parameters
• G (NetworkX DiGraph) – A directed acyclic graph (DAG)
• source (node in G)
Returns The ancestors of source in G
Return type set()
3.20.2 networkx.algorithms.dag.descendants
descendants(G, source)
Returns all nodes reachable from source in G.
Parameters
• G (NetworkX DiGraph) – A directed acyclic graph (DAG)
• source (node in G)
Returns The descendants of source in G
Return type set()
3.20.3 networkx.algorithms.dag.topological_sort
topological_sort(G)
Returns a generator of nodes in topologically sorted order.
A topological sort is a nonunique permutation of the nodes such that an edge from u to v implies that u appears
before v in the topological sort order.
Parameters G (NetworkX digraph) – A directed acyclic graph (DAG)
Returns An iterable of node names in topological sorted order.
Return type iterable
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 NetworkXUnfeasible exception is raised. This can also be raised if G is
changed while the returned iterator is being processed
• RuntimeError – If G is changed while the returned iterator is being processed.
Examples
If your DiGraph naturally has the edges representing tasks/inputs and nodes representing people/processes that
initiate tasks, then topological_sort is not quite what you need. You will have to change the tasks to nodes with
dependence reflected by edges. The result is a kind of topological sort of the edges. This can be done with
networkx.line_graph() as follows:
>>> list(nx.topological_sort(nx.line_graph(DG)))
[(1, 2), (2, 3)]
Notes
This algorithm is based on a description and proof in “Introduction to Algorithms: A Creative Approach”1 .
See also:
is_directed_acyclic_graph(), lexicographical_topological_sort()
References
3.20.4 networkx.algorithms.dag.all_topological_sorts
all_topological_sorts(G)
Returns a generator of _all_ topological sorts of the directed graph G.
A topological sort is a nonunique permutation of the nodes such that an edge from u to v implies that u appears
before v in the topological sort order.
Parameters G (NetworkX DiGraph) – A directed graph
Returns All topological sorts of the digraph G
Return type generator
Raises
• NetworkXNotImplemented – If G is not directed
• NetworkXUnfeasible – If G is not acyclic
1 Manber, U. (1989). Introduction to Algorithms - A Creative Approach. Addison-Wesley.
Examples
Notes
References
3.20.5 networkx.algorithms.dag.lexicographical_topological_sort
lexicographical_topological_sort(G, key=None)
Returns a generator of nodes in lexicographically topologically sorted order.
A topological sort is a nonunique permutation of the nodes such that an edge from u to v implies that u appears
before v in the topological sort order.
Parameters
• G (NetworkX digraph) – A directed acyclic graph (DAG)
• key (function, optional) – This function maps nodes to keys with which to resolve ambigui-
ties in the sort order. Defaults to the identity function.
Returns An iterable of node names in lexicographical topological sort order.
Return type iterable
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 NetworkXUnfeasible exception is raised. This can also be raised if G is
changed while the returned iterator is being processed
• RuntimeError – If G is changed while the returned iterator is being processed.
Notes
This algorithm is based on a description and proof in “Introduction to Algorithms: A Creative Approach”1 .
See also:
topological_sort()
1 Manber, U. (1989). Introduction to Algorithms - A Creative Approach. Addison-Wesley.
References
3.20.6 networkx.algorithms.dag.is_directed_acyclic_graph
is_directed_acyclic_graph(G)
Returns True if the graph G is a directed acyclic graph (DAG) or False if not.
Parameters G (NetworkX graph)
Returns True if G is a DAG, False otherwise
Return type bool
3.20.7 networkx.algorithms.dag.is_aperiodic
is_aperiodic(G)
Returns 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) – A directed graph
Returns True if the graph is aperiodic False otherwise
Return type bool
Raises NetworkXError – If G is not directed
Notes
This uses the method outlined in1 , which runs in 𝑂(𝑚) time given 𝑚 edges in G. Note that a graph is not
aperiodic if it is acyclic as every integer trivial divides length 0 cycles.
References
3.20.8 networkx.algorithms.dag.transitive_closure
transitive_closure(G)
Returns transitive closure of a directed graph
The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that for all v,w in V there is an edge (v,w) in E+
if and only if there is a non-null path from v to w in G.
Parameters G (NetworkX DiGraph) – A directed graph
Returns The transitive closure of G
Return type NetworkX DiGraph
Raises NetworkXNotImplemented – If G is not directed
1 Jarvis, J. P.; Shier, D. R. (1996), “Graph-theoretic analysis of finite Markov chains,” in Shier, D. R.; Wallenius, K. T., Applied Mathematical
References
3.20.9 networkx.algorithms.dag.transitive_reduction
transitive_reduction(G)
Returns transitive reduction of a directed graph
The transitive reduction of G = (V,E) is a graph G- = (V,E-) such that for all v,w in V there is an edge (v,w) in
E- if and only if (v,w) is in E and there is no path from v to w in G with length greater than 1.
Parameters G (NetworkX DiGraph) – A directed acyclic graph (DAG)
Returns The transitive reduction of G
Return type NetworkX DiGraph
Raises NetworkXError – If G is not a directed acyclic graph (DAG) transitive reduction is not
uniquely defined and a NetworkXError exception is raised.
References
https://en.wikipedia.org/wiki/Transitive_reduction
3.20.10 networkx.algorithms.dag.antichains
antichains(G)
Generates antichains from a directed acyclic graph (DAG).
An antichain is a subset of a partially ordered set such that any two elements in the subset are incomparable.
Parameters G (NetworkX DiGraph) – A directed acyclic graph (DAG)
Returns
Return type generator object
Raises
• NetworkXNotImplemented – If G is not directed
• NetworkXUnfeasible – If G contains a cycle
Notes
This function was originally developed by Peter Jipsen and Franco Saliola for the SAGE project. It’s included
in NetworkX with permission from the authors. Original SAGE code at:
https://github.com/sagemath/sage/blob/master/src/sage/combinat/posets/hasse_diagram.py
References
3.20.11 networkx.algorithms.dag.dag_longest_path
Parameters
• G (NetworkX DiGraph) – A directed acyclic graph (DAG)
• weight (str, optional) – Edge data key to use for weight
• default_weight (int, optional) – The weight of edges that do not have a weight attribute
Returns Longest path
Return type list
Raises NetworkXNotImplemented – If G is not directed
See also:
dag_longest_path_length()
3.20.12 networkx.algorithms.dag.dag_longest_path_length
3.20.13 networkx.algorithms.dag.dag_to_branching
dag_to_branching(G)
Returns a branching representing all (overlapping) paths from root nodes to leaf nodes in the given directed
acyclic graph.
As described in networkx.algorithms.tree.recognition, a branching is a directed forest in which
each node has at most one parent. In other words, a branching is a disjoint union of arborescences. For this
function, each node of in-degree zero in G becomes a root of one of the arborescences, and there will be one leaf
node for each distinct path from that root to a leaf node in G.
Each node v in G with k parents becomes k distinct nodes in the returned branching, one for each parent, and
the sub-DAG rooted at v is duplicated for each copy. The algorithm then recurses on the children of each copy
of v.
Parameters G (NetworkX graph) – A directed acyclic graph.
Returns
The branching in which there is a bijection between root-to-leaf paths in G (in which multiple
paths may share the same leaf) and root-to-leaf paths in the branching (in which there is a unique
path from a root to a leaf).
Each node has an attribute ‘source’ whose value is the original node to which this node corre-
sponds. No other graph, node, or edge attributes are copied into this new graph.
Return type DiGraph
Raises
• NetworkXNotImplemented – If G is not directed, or if G is a multigraph.
• HasACycle – If G is not acyclic.
Examples
To examine which nodes in the returned branching were produced by which original node in the directed acyclic
graph, we can collect the mapping from source node to new nodes into a dictionary. For example, consider the
directed diamond graph:
To copy node attributes from the original graph to the new graph, you can use a dictionary like the one con-
structed in the above example:
Notes
This function is not idempotent in the sense that the node labels in the returned branching may be uniquely
generated each time the function is invoked. In fact, the node labels may not be integers; in order to relabel
the nodes to be more readable, you can use the networkx.convert_node_labels_to_integers()
function.
The current implementation of this function uses networkx.prefix_tree(), so it is subject to the limita-
tions of that function.
3.21 Dispersion
3.21.1 Dispersion
networkx.algorithms.centrality.dispersion
Notes
This implementation follows Lars Backstrom and Jon Kleinberg1 . Typical usage would be to run dispersion on
the ego network 𝐺𝑢 if 𝑢 were specified. Running dispersion() with neither 𝑢 nor 𝑣 specified can take some
time to complete.
References
3.22.1 networkx.algorithms.distance_measures.center
Kleinberg. https://arxiv.org/pdf/1310.6753v1.pdf
3.22.2 networkx.algorithms.distance_measures.diameter
3.22.3 networkx.algorithms.distance_measures.eccentricity
3.22.4 networkx.algorithms.distance_measures.extrema_bounding
extrema_bounding(G, compute=’diameter’)
Compute requested extreme distance metric of undirected graph G
Computation is based on smart lower and upper bounds, and in practice linear in the number of nodes, rather
than quadratic (except for some border cases such as complete graphs or circle shaped graphs).
Parameters
• G (NetworkX graph) – An undirected graph
• compute (string denoting the requesting metric) – “diameter” for the maximal eccentricity
value, “radius” for the minimal eccentricity value, “periphery” for the set of nodes with
eccentricity equal to the diameter “center” for the set of nodes with eccentricity equal to the
radius
Returns value – int for “diameter” and “radius” or list of nodes for “center” and “periphery”
Return type value of the requested metric
Raises NetworkXError – If the graph consists of multiple components
Notes
3.22.5 networkx.algorithms.distance_measures.periphery
3.22.6 networkx.algorithms.distance_measures.radius
3.23.2 networkx.algorithms.distance_regular.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 True if the graph is Distance Regular, False otherwise
Return type bool
Examples
>>> G=nx.hypercube_graph(6)
>>> nx.is_distance_regular(G)
True
See also:
intersection_array(), global_parameters()
Notes
References
3.23.3 networkx.algorithms.distance_regular.is_strongly_regular
is_strongly_regular(G)
Returns True if and only if the given graph is strongly regular.
An undirected graph is strongly regular if
• it is regular,
• each pair of adjacent vertices has the same number of neighbors in common,
• each pair of nonadjacent vertices has the same number of neighbors in common.
Each strongly regular graph is a distance-regular graph. Conversely, if a distance-regular graph has di-
ameter two, then it is a strongly regular graph. For more information on distance-regular graphs, see
is_distance_regular().
Parameters G (NetworkX graph) – An undirected graph.
Returns Whether G is strongly regular.
Return type bool
Examples
The cycle graph on five vertices is strongly regular. It is two-regular, each pair of adjacent vertices has no shared
neighbors, and each pair of nonadjacent vertices has one shared neighbor:
3.23.4 networkx.algorithms.distance_regular.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’s intersection 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
Return type tuple of lists
Examples
>>> G=nx.icosahedral_graph()
>>> nx.intersection_array(G)
([5, 2, 1], [1, 2, 5])
References
See also:
global_parameters()
3.23.5 networkx.algorithms.distance_regular.global_parameters
global_parameters(b, c)
Returns 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 (list)
• c (list)
Returns An iterable over three tuples.
Return type iterable
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)]
References
See also:
intersection_array()
3.24 Dominance
Dominance algorithms.
3.24.1 networkx.algorithms.dominance.immediate_dominators
immediate_dominators(G, start)
Returns the immediate dominators of all nodes of a directed graph.
Parameters
• G (a DiGraph or MultiDiGraph) – The graph where dominance is to be computed.
• start (node) – The start node of dominance computation.
Returns idom – A dict containing the immediate dominators of each node reachable from start.
Return type dict keyed by nodes
Raises
• NetworkXNotImplemented – If G is undirected.
• NetworkXError – If start is not in G.
Notes
Except for start, the immediate dominators are the parents of their corresponding nodes in the dominator tree.
Examples
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
>>> sorted(nx.immediate_dominators(G, 1).items())
[(1, 1), (2, 1), (3, 1), (4, 3), (5, 1)]
References
3.24.2 networkx.algorithms.dominance.dominance_frontiers
dominance_frontiers(G, start)
Returns the dominance frontiers of all nodes of a directed graph.
Parameters
• G (a DiGraph or MultiDiGraph) – The graph where dominance is to be computed.
• start (node) – The start node of dominance computation.
Returns df – A dict containing the dominance frontiers of each node reachable from start as lists.
Return type dict keyed by nodes
Raises
• NetworkXNotImplemented – If G is undirected.
• NetworkXError – If start is not in G.
Examples
>>> G = nx.DiGraph([(1, 2), (1, 3), (2, 5), (3, 4), (4, 5)])
>>> sorted((u, sorted(df)) for u, df in nx.dominance_frontiers(G, 1).items())
[(1, []), (2, [5]), (3, [5]), (4, [5]), (5, [])]
References
3.25.1 networkx.algorithms.dominating.dominating_set
dominating_set(G, start_with=None)
Finds a dominating set for the graph G.
A dominating set for a graph with node set V is a subset D of V such that every node not in D is adjacent to at
least one member of D1 .
Parameters
• G (NetworkX graph)
• start_with (node (default=None)) – Node to use as a starting point for the algorithm.
Returns D – A dominating set for G.
Return type set
Notes
This function is an implementation of algorithm 7 in2 which finds some dominating set, not necessarily the
smallest one.
See also:
is_dominating_set()
References
3.25.2 networkx.algorithms.dominating.is_dominating_set
is_dominating_set(G, nbunch)
Checks if nbunch is a dominating set for G.
A dominating set for a graph with node set V is a subset D of V such that every node not in D is adjacent to at
least one member of D1 .
Parameters
• G (NetworkX graph)
• nbunch (iterable) – An iterable of nodes in the graph G.
See also:
dominating_set()
1 https://en.wikipedia.org/wiki/Dominating_set
2 Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf
1 https://en.wikipedia.org/wiki/Dominating_set
References
3.26 Efficiency
3.26.1 networkx.algorithms.efficiency.efficiency
efficiency(G, u, v)
Returns the efficiency of a pair of nodes in a graph.
The efficiency of a pair of nodes is the multiplicative inverse of the shortest path distance between the nodes1 .
Returns 0 if no path between nodes.
Parameters
• G (networkx.Graph) – An undirected graph for which to compute the average local
efficiency.
• u, v (node) – Nodes in the graph G.
Returns Multiplicative inverse of the shortest path distance between the nodes.
Return type float
Notes
Edge weights are ignored when computing the shortest path distances.
See also:
local_efficiency(), global_efficiency()
References
3.26.2 networkx.algorithms.efficiency.local_efficiency
local_efficiency(G)
Returns the average local efficiency of the graph.
The efficiency of a pair of nodes in a graph is the multiplicative inverse of the shortest path distance between the
nodes. The local efficiency of a node in the graph is the average global efficiency of the subgraph induced by
the neighbors of the node. The average local efficiency is the average of the local efficiencies of each node1 .
Parameters G (networkx.Graph) – An undirected graph for which to compute the average local
efficiency.
1 Latora, Vito, and Massimo Marchiori. “Efficient behavior of small-world networks.” Physical Review Letters 87.19 (2001): 198701. <https:
//doi.org/10.1103/PhysRevLett.87.198701>
1 Latora, Vito, and Massimo Marchiori. “Efficient behavior of small-world networks.” Physical Review Letters 87.19 (2001): 198701. <https:
//doi.org/10.1103/PhysRevLett.87.198701>
Notes
Edge weights are ignored when computing the shortest path distances.
See also:
global_efficiency()
References
3.26.3 networkx.algorithms.efficiency.global_efficiency
global_efficiency(G)
Returns the average global efficiency of the graph.
The efficiency of a pair of nodes in a graph is the multiplicative inverse of the shortest path distance between the
nodes. The average global efficiency of a graph is the average efficiency of all pairs of nodes1 .
Parameters G (networkx.Graph) – An undirected graph for which to compute the average
global efficiency.
Returns The average global efficiency of the graph.
Return type float
Notes
Edge weights are ignored when computing the shortest path distances.
See also:
local_efficiency()
References
3.27 Eulerian
//doi.org/10.1103/PhysRevLett.87.198701>
3.27.1 networkx.algorithms.euler.is_eulerian
is_eulerian(G)
Returns True if and only if G is Eulerian.
A graph is Eulerian if it has an Eulerian circuit. An Eulerian circuit is a closed walk that includes each edge of
a graph exactly once.
Parameters G (NetworkX graph) – A graph, either directed or undirected.
Examples
Notes
If the graph is not connected (or not strongly connected, for directed graphs), this function returns False.
3.27.2 networkx.algorithms.euler.eulerian_circuit
Notes
References
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)]
3.27.3 networkx.algorithms.euler.eulerize
eulerize(G)
Transforms a graph into an Eulerian graph
Parameters G (NetworkX graph) – An undirected graph
Returns G
Return type NetworkX multigraph
Raises NetworkXError – If the graph is not connected.
See also:
is_eulerian(), eulerian_circuit()
References
Examples
>>> G = nx.complete_graph(10)
>>> H = nx.eulerize(G)
>>> nx.is_eulerian(H)
True
3.28 Flows
networkx.algorithms.flow.maximum_flow
Notes
The function used in the flow_func parameter has to return a residual network that follows NetworkX conven-
tions:
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
maximum_flow returns both the value of the maximum flow and a dictionary with all flows.
You can also use alternative algorithms for computing the maximum flow by using the flow_func parameter.
networkx.algorithms.flow.maximum_flow_value
Digraph, a source node, and a target node. And return a residual network that follows Net-
workX 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 maxi-
mum flow.
Returns flow_value – Value of the maximum flow, i.e., net outflow from the source.
Return type integer, float
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(),
preflow_push(), shortest_augmenting_path()
Notes
The function used in the flow_func parameter has to return a residual network that follows NetworkX conven-
tions:
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 maximum flow by using the flow_func parameter.
networkx.algorithms.flow.minimum_cut
See also:
maximum_flow(), maximum_flow_value(), minimum_cut_value(), edmonds_karp(),
preflow_push(), shortest_augmenting_path()
Notes
The function used in the flow_func parameter has to return a residual network that follows NetworkX conven-
tions:
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:
‘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.
networkx.algorithms.flow.minimum_cut_value
Notes
The function used in the flow_func parameter has to return a residual network that follows NetworkX conven-
tions:
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.
3.28.2 Edmonds-Karp
edmonds_karp(G, s, t[, capacity, residual, . . . ]) Find a maximum single-commodity flow using the
Edmonds-Karp algorithm.
networkx.algorithms.flow.edmonds_karp
Parameters
• G (NetworkX graph) – Edges of the graph are expected to have an attribute called ‘capacity’.
If this attribute is not present, the edge is considered to have infinite capacity.
• s (node) – Source node for the flow.
• t (node) – Sink node for the flow.
• capacity (string) – 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.
• 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 – Residual network after computing the maximum flow.
Return type NetworkX DiGraph
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(), 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
networkx.algorithms.flow.shortest_augmenting_path
• 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 – Residual network after computing the maximum flow.
Return type NetworkX DiGraph
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(), 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
(continues on next page)
3.28.4 Preflow-Push
preflow_push(G, s, t[, capacity, residual, . . . ]) Find a maximum single-commodity flow using the
highest-label preflow-push algorithm.
networkx.algorithms.flow.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.nodes[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.nodes['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.nodes['y']['excess']
True
3.28.5 Dinitz
dinitz(G, s, t[, capacity, residual, . . . ]) Find a maximum single-commodity flow using Dinitz’
algorithm.
networkx.algorithms.flow.dinitz
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.
1 Dinitz’ Algorithm: The Original Version and Even’s Version. 2006. Yefim Dinitz. In Theoretical Computer Science. Lecture Notes in
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 = dinitz(G, 'x', 'y')
>>> flow_value = nx.maximum_flow_value(G, 'x', 'y')
>>> flow_value
3.0
>>> flow_value == R.graph['flow_value']
True
References
3.28.6 Boykov-Kolmogorov
networkx.algorithms.flow.boykov_kolmogorov
Pattern Analysis and Machine Intelligence, IEEE Transactions on, 26(9), 1124-1137. http://www.csd.uwo.ca/~yuri/Papers/pami04.pdf
2 Vladimir Kolmogorov. Graph-based Algorithms for Multi-camera Reconstruction Problem. PhD thesis, Cornell University, CS Department,
practical problems.
Parameters
• G (NetworkX graph) – Edges of the graph are expected to have an attribute called ‘capacity’.
If this attribute is not present, the edge is considered to have infinite capacity.
• s (node) – Source node for the flow.
• t (node) – Sink node for the flow.
• capacity (string) – 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.
• 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 – Residual network after computing the maximum flow.
Return type NetworkX DiGraph
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(), 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.
2003. pp. 109-114. https://pub.ist.ac.at/~vnk/papers/thesis.pdf
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 = boykov_kolmogorov(G, 'x', 'y')
>>> flow_value = nx.maximum_flow_value(G, 'x', 'y')
>>> flow_value
3.0
>>> flow_value == R.graph['flow_value']
True
A nice feature of the Boykov-Kolmogorov algorithm is that a partition of the nodes that defines a minimum cut
can be easily computed based on the search trees used during the algorithm. These trees are stored in the graph
attribute trees of the residual network.
Or equivalently:
References
networkx.algorithms.flow.gomory_hu_tree
Examples
>>> G = nx.karate_club_graph()
>>> nx.set_edge_attributes(G, 1, 'capacity')
>>> T = nx.gomory_hu_tree(G)
>>> # The value of the minimum cut between any pair
... # of nodes in G is the minimum edge weight in the
... # shortest path between the two nodes in the
... # Gomory-Hu tree.
... def minimum_edge_weight_in_shortest_path(T, u, v):
... path = nx.shortest_path(T, u, v, weight='weight')
... return min((T[u][v]['weight'], (u,v)) for (u, v) in zip(path, path[1:]))
>>> u, v = 0, 33
>>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
>>> cut_value
10
>>> nx.minimum_cut_value(G, u, v)
10
>>> # The Comory-Hu tree also has the property that removing the
... # edge with the minimum weight in the shortest path between
... # any two nodes leaves two connected components that form
... # a partition of the nodes in G that defines the minimum s-t
... # cut.
... cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
>>> T.remove_edge(*edge)
>>> U, V = list(nx.connected_components(T))
>>> # Thus U and V form a partition that defines a minimum cut
... # between u and v in G. You can compute the edge cut set,
... # that is, the set of edges that if removed from G will
... # disconnect u from v in G, with this information:
... cutset = set()
>>> for x, nbrs in ((n, G[n]) for n in U):
... cutset.update((x, y) for y in nbrs if y in V)
>>> # Because we have set the capacities of all edges to 1
(continues on next page)
Notes
This implementation is based on Gusfield approach1 to compute Comory-Hu trees, which does not require node
contractions and has the same computational complexity than the original method.
See also:
minimum_cut(), maximum_flow()
References
3.28.8 Utils
networkx.algorithms.flow.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.
1 Gusfield D: Very simple methods for all pairs network flow analysis. SIAM J Comput 19(1):143-155, 1990.
network_simplex(G[, demand, capacity, weight]) Find a minimum cost flow satisfying all demands in di-
graph G.
min_cost_flow_cost(G[, demand, capacity, Find the cost of a minimum cost flow satisfying all de-
weight]) mands in digraph G.
min_cost_flow(G[, demand, capacity, weight]) Returns a minimum cost flow satisfying all demands in
digraph G.
cost_of_flow(G, flowDict[, weight]) Compute the cost of the flow given by flowDict on graph
G.
max_flow_min_cost(G, s, t[, capacity, weight]) Returns a maximum (s, t)-flow of minimum cost.
networkx.algorithms.flow.network_simplex
Notes
This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and
roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant
edge attributes by a convenient constant factor (eg 100).
See also:
cost_of_flow(), max_flow_min_cost(), min_cost_flow(), min_cost_flow_cost()
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)
(continues on next page)
References
networkx.algorithms.flow.min_cost_flow_cost
Notes
This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and
roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant
edge attributes by a convenient constant factor (eg 100).
Examples
networkx.algorithms.flow.min_cost_flow
• weight (string) – Edges of the graph G are expected to have an attribute weight that indicates
the cost incurred 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 of dictionaries keyed by nodes such that flowDict[u][v] is the flow
edge (u, v).
Return type dictionary
Raises
• NetworkXError – This exception is raised if the input graph is not directed or not con-
nected.
• 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()
Notes
This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and
roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant
edge attributes by a convenient constant factor (eg 100).
Examples
networkx.algorithms.flow.cost_of_flow
• G (NetworkX graph) – DiGraph on which a minimum cost flow satisfying all demands is to
be found.
• weight (string) – Edges of the graph G are expected to have an attribute weight that indicates
the cost incurred 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 – 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.
Return type Integer, float
See also:
max_flow_min_cost(), min_cost_flow(), min_cost_flow_cost(), network_simplex()
Notes
This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and
roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant
edge attributes by a convenient constant factor (eg 100).
networkx.algorithms.flow.max_flow_min_cost
Notes
This algorithm is not guaranteed to work if edge weights or demands are floating point numbers (overflows and
roundoff errors can cause problems). As a workaround you can use integer numbers by multiplying the relevant
edge attributes by a convenient constant factor (eg 100).
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)
>>> mincost = nx.cost_of_flow(G, mincostFlow)
>>> mincost
373
>>> from networkx.algorithms.flow import maximum_flow
>>> maxFlow = maximum_flow(G, 1, 7)[1]
>>> nx.cost_of_flow(G, maxFlow) >= mincost
True
>>> 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 di-
graph G.
networkx.algorithms.flow.capacity_scaling
Notes
This algorithm does not work if edge weights are floating-point numbers.
See also:
network_simplex()
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 # doctest: +SKIP
{'a': {'t': 4}, 'd': {'w': 2}, 'q': {'d': 1}, 'p': {'q': 2, 'a': 2}, 't': {'q': 1,
˓→ 'w': 1}, 'w': {}}
3.29.1 networkx.algorithms.graphical.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 – True if the sequence is a valid degree sequence and False if not.
Return type bool
Examples
>>> G = nx.path_graph(4)
>>> sequence = (d for n, d in G.degree())
>>> nx.is_graphical(sequence)
True
References
3.29.2 networkx.algorithms.graphical.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 – True if in and out-sequences are digraphic False if not.
Return type bool
Notes
This algorithm is from Kleitman and Wang1 . The worst case runtime is 𝑂(𝑠 × log 𝑛) where 𝑠 and 𝑛 are the sum
and length of the sequences respectively.
References
3.29.3 networkx.algorithms.graphical.is_multigraphical
is_multigraphical(sequence)
Returns True if some multigraph can realize the sequence.
Parameters sequence (list) – A list of integers
Returns valid – True if deg_sequence is a multigraphic degree sequence and False if not.
Return type bool
Notes
The worst-case run time is 𝑂(𝑛) where 𝑛 is the length of the sequence.
References
3.29.4 networkx.algorithms.graphical.is_pseudographical
is_pseudographical(sequence)
Returns True if some pseudograph can realize the sequence.
Every nonnegative integer sequence with an even sum is pseudographical (see1 ).
Parameters sequence (list or iterable container) – A sequence of integer node degrees
Returns valid – True if the sequence is a pseudographic degree sequence and False if not.
Return type bool
Notes
The worst-case run time is 𝑂(𝑛) where n is the length of the sequence.
References
3.29.5 networkx.algorithms.graphical.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 𝑂(𝑠) where 𝑠 is the sum of
the sequence.
1 D.J. Kleitman and D.L. Wang Algorithms for Constructing Graphs and Digraphs with Given Valences and Factors, Discrete Mathematics,
778-782 (1976).
Parameters deg_sequence (list) – A list of integers where each element specifies the degree of a
node in a graph.
Returns valid – True if deg_sequence is graphical and False if not.
Return type bool
Notes
References
3.29.6 networkx.algorithms.graphical.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 [?].
Parameters deg_sequence (list) – A list of integers
Returns valid – True if deg_sequence is graphical and False if not.
Return type bool
Notes
This implementation uses an equivalent form of the Erdős-Gallai criterion. Worst-case run time is 𝑂(𝑛) where
𝑛 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 d_k >= k and the value n_j 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 in2 .
The ZZ condition says that for the sequence d if
(max(𝑑) + min(𝑑) + 1)2
|𝑑| >=
4 * min(𝑑)
1 I.E. Zverovich and V.E. Zverovich. “Contributions to the theory of graphic sequences”, Discrete Mathematics, 105, pp. 292-303 (1992).
2 I.E. Zverovich and V.E. Zverovich. “Contributions to the theory of graphic sequences”, Discrete Mathematics, 105, pp. 292-303 (1992).
References
[?], [?]
3.30 Hierarchy
Flow Hierarchy.
3.30.1 networkx.algorithms.hierarchy.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 graph1 .
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 – Flow hierarchy value
Return type float
Notes
The algorithm described in1 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
3.31 Hybrid
Provides functions for finding and testing for locally (k, l)-connected graphs.
kl_connected_subgraph(G, k, l[, low_memory, Returns the maximum locally (k, l)-connected sub-
. . . ]) graph of G.
is_kl_connected(G, k, l[, low_memory]) Returns True if and only if G is locally (k, l)-
connected.
1 Luo, J.; Magee, C.L. (2011), Detecting evolving patterns of self-organizing networks by flow hierarchy measurement, Complexity, Volume 16
3.31.1 networkx.algorithms.hybrid.kl_connected_subgraph
References
3.31.2 networkx.algorithms.hybrid.is_kl_connected
is_kl_connected(G, k, l, low_memory=False)
Returns True if and only if G is locally (k, l)-connected.
A graph is locally (k, l)-connected if for each edge (u, v) in the graph there are at least l edge-disjoint
paths of length at most k joining u to v.
Parameters
• G (NetworkX graph) – The graph to test for local (k, l)-connectedness.
• k (integer) – The maximum length of paths to consider. A higher number means a looser
connectivity requirement.
• l (integer) – The number of edge-disjoint paths. A higher number means a stricter connec-
tivity requirement.
• low_memory (bool) – If this is True, this function uses an algorithm that uses slightly more
time but less memory.
Returns Whether the graph is locally (k, l)-connected subgraph.
Return type bool
See also:
kl_connected_subgraph()
References
3.32 Isolates
3.32.1 networkx.algorithms.isolate.is_isolate
is_isolate(G, n)
Determines whether a node is an isolate.
An isolate is a node with no neighbors (that is, with degree zero). For directed graphs, this means no in-neighbors
and no out-neighbors.
Parameters
• G (NetworkX graph)
• n (node) – A node in G.
Returns is_isolate – True if and only if n has no neighbors.
Return type bool
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
3.32.2 networkx.algorithms.isolate.isolates
isolates(G)
Iterator over isolates in the graph.
An isolate is a node with no neighbors (that is, with degree zero). For directed graphs, this means no in-neighbors
and no out-neighbors.
Parameters G (NetworkX graph)
Returns An iterator over the isolates of G.
Return type iterator
Examples
>>> G = nx.Graph()
>>> G.add_edge(1, 2)
>>> G.add_node(3)
>>> list(nx.isolates(G))
[3]
To remove all isolates in the graph, first create a list of the isolates, then use Graph.
remove_nodes_from():
>>> G.remove_nodes_from(list(nx.isolates(G)))
>>> list(G)
[1, 2]
3.32.3 networkx.algorithms.isolate.number_of_isolates
number_of_isolates(G)
Returns the number of isolates in the graph.
An isolate is a node with no neighbors (that is, with degree zero). For directed graphs, this means no in-neighbors
and no out-neighbors.
Parameters G (NetworkX graph)
Returns The number of degree zero nodes in the graph G.
Return type int
3.33 Isomorphism
is_isomorphic(G1, G2[, node_match, Returns True if the graphs G1 and G2 are isomorphic
edge_match]) 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.
3.33.1 networkx.algorithms.isomorphism.is_isomorphic
Notes
Examples
>>> G1 = nx.DiGraph()
>>> G2 = nx.DiGraph()
>>> nx.add_path(G1, [1,2,3,4], weight=1)
>>> nx.add_path(G2, [10,20,30,40], weight=2)
>>> em = iso.numerical_edge_match('weight', 1)
>>> nx.is_isomorphic(G1, G2) # no weights considered
True
>>> nx.is_isomorphic(G1, G2, edge_match=em) # match weights
False
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')
>>> nx.add_path(G1, [1,2,3,4], weight=3, linewidth=2.5)
>>> nx.add_path(G2, [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’.
See also:
numerical_node_match(), numerical_edge_match(), numerical_multiedge_match(),
categorical_node_match(), categorical_edge_match(), categorical_multiedge_match()
References
3.33.2 networkx.algorithms.isomorphism.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
3.33.3 networkx.algorithms.isomorphism.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
3.33.4 networkx.algorithms.isomorphism.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
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
>>> GM.mapping
{0: 0, 1: 1, 2: 2, 3: 3}
>>> DiGM.mapping
{0: 0, 1: 1, 2: 2, 3: 3}
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 subgraph, 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
The implementation handles both directed and undirected graphs as well as multigraphs.
In general, the subgraph isomorphism problem is NP-complete whereas the graph isomorphism problem is most likely
not NP-complete (although no polynomial-time algorithm is known to exist).
Graph Matcher
networkx.algorithms.isomorphism.GraphMatcher.__init__
node_match(G1.nodes[n1], G2.nodes[n2])
That is, the function will receive the node attribute dictionaries of the nodes under consider-
ation. 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 consider-
ation. If None, then no attributes are considered when testing for an isomorphism.
networkx.algorithms.isomorphism.GraphMatcher.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.
networkx.algorithms.isomorphism.GraphMatcher.is_isomorphic
GraphMatcher.is_isomorphic()
Returns True if G1 and G2 are isomorphic graphs.
networkx.algorithms.isomorphism.GraphMatcher.subgraph_is_isomorphic
GraphMatcher.subgraph_is_isomorphic()
Returns True if a subgraph of G1 is isomorphic to G2.
networkx.algorithms.isomorphism.GraphMatcher.isomorphisms_iter
GraphMatcher.isomorphisms_iter()
Generator over isomorphisms between G1 and G2.
networkx.algorithms.isomorphism.GraphMatcher.subgraph_isomorphisms_iter
GraphMatcher.subgraph_isomorphisms_iter()
Generator over isomorphisms between a subgraph of G1 and G2.
networkx.algorithms.isomorphism.GraphMatcher.candidate_pairs_iter
GraphMatcher.candidate_pairs_iter()
Iterator over candidate pairs of nodes in G1 and G2.
networkx.algorithms.isomorphism.GraphMatcher.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.
networkx.algorithms.isomorphism.GraphMatcher.semantic_feasibility
GraphMatcher.semantic_feasibility(G1_node, G2_node)
Returns True if mapping G1_node to G2_node is semantically feasible.
networkx.algorithms.isomorphism.GraphMatcher.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
networkx.algorithms.isomorphism.DiGraphMatcher.__init__
node_match(G1.nodes[n1], G2.nodes[n2])
That is, the function will receive the node attribute dictionaries of the nodes under consider-
ation. 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 consider-
ation. If None, then no attributes are considered when testing for an isomorphism.
networkx.algorithms.isomorphism.DiGraphMatcher.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.
networkx.algorithms.isomorphism.DiGraphMatcher.is_isomorphic
DiGraphMatcher.is_isomorphic()
Returns True if G1 and G2 are isomorphic graphs.
networkx.algorithms.isomorphism.DiGraphMatcher.subgraph_is_isomorphic
DiGraphMatcher.subgraph_is_isomorphic()
Returns True if a subgraph of G1 is isomorphic to G2.
networkx.algorithms.isomorphism.DiGraphMatcher.isomorphisms_iter
DiGraphMatcher.isomorphisms_iter()
Generator over isomorphisms between G1 and G2.
networkx.algorithms.isomorphism.DiGraphMatcher.subgraph_isomorphisms_iter
DiGraphMatcher.subgraph_isomorphisms_iter()
Generator over isomorphisms between a subgraph of G1 and G2.
networkx.algorithms.isomorphism.DiGraphMatcher.candidate_pairs_iter
DiGraphMatcher.candidate_pairs_iter()
Iterator over candidate pairs of nodes in G1 and G2.
networkx.algorithms.isomorphism.DiGraphMatcher.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.
networkx.algorithms.isomorphism.DiGraphMatcher.semantic_feasibility
DiGraphMatcher.semantic_feasibility(G1_node, G2_node)
Returns True if mapping G1_node to G2_node is semantically feasible.
networkx.algorithms.isomorphism.DiGraphMatcher.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
networkx.algorithms.isomorphism.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 – The customized, categorical node_match function.
Return type function
Examples
networkx.algorithms.isomorphism.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 – The customized, categorical edge_match function.
Return type function
Examples
networkx.algorithms.isomorphism.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 – The customized, categorical edge_match function.
Return type function
Examples
networkx.algorithms.isomorphism.numerical_node_match
Examples
networkx.algorithms.isomorphism.numerical_edge_match
Examples
networkx.algorithms.isomorphism.numerical_multiedge_match
Examples
networkx.algorithms.isomorphism.generic_node_match
Examples
networkx.algorithms.isomorphism.generic_edge_match
• default (value | list) – The default value for the edge attribute, or a list of default values for
the edge attributes.
• op (callable | list) – The operator to use when comparing attribute values, or a list of opera-
tors to use when comparing values for each attribute.
Returns match – The customized, generic edge_match function.
Return type function
Examples
networkx.algorithms.isomorphism.generic_multiedge_match
Examples
3.34.1 PageRank
pagerank(G[, alpha, personalization, . . . ]) Returns the PageRank of the nodes in the graph.
pagerank_numpy(G[, alpha, personalization, . . . ]) Returns the PageRank of the nodes in the graph.
pagerank_scipy(G[, alpha, personalization, . . . ]) Returns the PageRank of the nodes in the graph.
google_matrix(G[, alpha, personalization, . . . ]) Returns the Google matrix of the graph.
networkx.algorithms.link_analysis.pagerank_alg.pagerank
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank(G, alpha=0.9)
Notes
The eigenvector calculation is done by the power iteration method and has no guarantee of convergence. The
iteration will stop after an error tolerance of len(G) * tol has been reached. If the number of iterations
exceed max_iter, a networkx.exception.PowerIterationFailedConvergence exception is
raised.
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.
See also:
pagerank_numpy(), pagerank_scipy(), google_matrix()
References
networkx.algorithms.link_analysis.pagerank_alg.pagerank_numpy
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank_numpy(G, alpha=0.9)
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.
See also:
pagerank(), pagerank_scipy(), google_matrix()
References
networkx.algorithms.link_analysis.pagerank_alg.pagerank_scipy
Examples
>>> G = nx.DiGraph(nx.path_graph(4))
>>> pr = nx.pagerank_scipy(G, alpha=0.9)
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.
See also:
pagerank(), pagerank_numpy(), google_matrix()
References
networkx.algorithms.link_analysis.pagerank_alg.google_matrix
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.
See also:
pagerank(), pagerank_numpy(), pagerank_scipy()
3.34.2 Hits
hits(G[, max_iter, tol, nstart, normalized]) Returns HITS hubs and authorities values for nodes.
hits_numpy(G[, normalized]) Returns HITS hubs and authorities values for nodes.
hits_scipy(G[, max_iter, tol, normalized]) Returns HITS hubs and authorities values for nodes.
hub_matrix(G[, nodelist]) Returns the HITS hub matrix.
authority_matrix(G[, nodelist]) Returns the HITS authority matrix.
networkx.algorithms.link_analysis.hits_alg.hits
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
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
networkx.algorithms.link_analysis.hits_alg.hits_numpy
hits_numpy(G, normalized=True)
Returns 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 dictionaries keyed by node containing the hub and authority
values.
Return type two-tuple of dictionaries
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
Notes
References
networkx.algorithms.link_analysis.hits_alg.hits_scipy
Examples
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
Notes
References
networkx.algorithms.link_analysis.hits_alg.hub_matrix
hub_matrix(G, nodelist=None)
Returns the HITS hub matrix.
networkx.algorithms.link_analysis.hits_alg.authority_matrix
authority_matrix(G, nodelist=None)
Returns 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, com- Count the number of common neighbors of all node
munity]) pairs in ebunch
ra_index_soundarajan_hopcroft(G[, Compute the resource allocation index of all node pairs
ebunch, . . . ]) in ebunch using community information.
within_inter_cluster(G[, ebunch, delta, . . . ]) Compute the ratio of within- and inter-cluster common
neighbors of all node pairs in ebunch.
3.35.1 networkx.algorithms.link_prediction.resource_allocation_index
resource_allocation_index(G, ebunch=None)
Compute the resource allocation index of all node pairs in ebunch.
Resource allocation index of u and v is defined as
∑︁ 1
|Γ(𝑤)|
𝑤∈Γ(𝑢)∩Γ(𝑣)
Examples
References
3.35.2 networkx.algorithms.link_prediction.jaccard_coefficient
jaccard_coefficient(G, ebunch=None)
Compute the Jaccard coefficient of all node pairs in ebunch.
Jaccard coefficient of nodes u and v is defined as
|Γ(𝑢) ∩ Γ(𝑣)|
|Γ(𝑢) ∪ Γ(𝑣)|
where Γ(𝑢) denotes the set of neighbors of 𝑢.
Parameters
• G (graph) – A NetworkX undirected graph.
• ebunch (iterable of node pairs, optional (default = None)) – Jaccard coefficient 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.
Returns piter – An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is
their Jaccard coefficient.
Return type iterator
Examples
References
3.35.3 networkx.algorithms.link_prediction.adamic_adar_index
adamic_adar_index(G, ebunch=None)
Compute the Adamic-Adar index of all node pairs in ebunch.
Adamic-Adar index of u and v is defined as
∑︁ 1
log |Γ(𝑤)|
𝑤∈Γ(𝑢)∩Γ(𝑣)
Examples
References
3.35.4 networkx.algorithms.link_prediction.preferential_attachment
preferential_attachment(G, ebunch=None)
Compute the preferential attachment score of all node pairs in ebunch.
Preferential attachment score of u and v is defined as
|Γ(𝑢)||Γ(𝑣)|
Examples
References
3.35.5 networkx.algorithms.link_prediction.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] identifies which community u belongs to.
Each node belongs to at most one community. Default value: ‘community’.
Returns piter – An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is
their score.
Return type iterator
Examples
References
3.35.6 networkx.algorithms.link_prediction.ra_index_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] identifies which community u belongs to.
Each node belongs to at most one community. Default value: ‘community’.
Returns piter – An iterator of 3-tuples in the form (u, v, p) where (u, v) is a pair of nodes and p is
their score.
Examples
References
3.35.7 networkx.algorithms.link_prediction.within_inter_cluster
Examples
References
Algorithms for finding the lowest common ancestor of trees and DAGs.
3.36.1 networkx.algorithms.lowest_common_ancestors.all_pairs_lowest_common_ancestor
all_pairs_lowest_common_ancestor(G, pairs=None)
Compute the lowest common ancestor for pairs of nodes.
Parameters
• G (NetworkX directed graph)
• pairs (iterable of pairs of nodes, optional (default: all pairs)) – The pairs of nodes of
interest. If None, will find the LCA of all pairs of nodes.
Returns
• An iterator over ((node1, node2), lca) where (node1, node2) are
• the pairs specified and lca is a lowest common ancestor of the pair.
• Note that for the default of all pairs in G, we consider
• unordered pairs, e.g. you will not get both (b, a) and (a, b).
Notes
3.36.2 networkx.algorithms.lowest_common_ancestors.tree_all_pairs_lowest_common_ancest
Notes
Only defined on non-null trees represented with directed edges from parents to children. Uses Tarjan’s off-line
lowest-common-ancestors algorithm. Runs in time 𝑂(4 × (𝑉 + 𝐸 + 𝑃 )) time, where 4 is the largest value of
the inverse Ackermann function likely to ever come up in actual use, and 𝑃 is the number of pairs requested (or
𝑉 2 if all are needed).
Tarjan, R. E. (1979), “Applications of path compression on balanced trees”, Journal of the ACM 26 (4): 690-715,
doi:10.1145/322154.322161.
See also:
all_pairs_lowest_common_ancestor(), lowest_common_ancestor()
3.36.3 networkx.algorithms.lowest_common_ancestors.lowest_common_ancestor
Notes
Only defined on non-null directed acyclic graphs. Takes n log(n) time in the size of the graph. See
all_pairs_lowest_common_ancestor when you have more than one pair of nodes of interest.
See also:
tree_all_pairs_lowest_common_ancestor(), all_pairs_lowest_common_ancestor()
3.37 Matching
3.37.1 networkx.algorithms.matching.is_matching
is_matching(G, matching)
Decides whether the given set or dictionary represents a valid matching in G.
A matching in a graph is a set of edges in which no two distinct edges share a common endpoint.
Parameters
• G (NetworkX graph)
• matching (dict or set) – A dictionary or set representing a matching. If a dictionary, it
must have matching[u] == v and matching[v] == u for each edge (u, v) in
the matching. If a set, it must have elements of the form (u, v), where (u, v) is an
edge in the matching.
Returns Whether the given set or dictionary represents a valid matching in the graph.
Return type bool
3.37.2 networkx.algorithms.matching.is_maximal_matching
is_maximal_matching(G, matching)
Decides whether the given set or dictionary represents a valid maximal matching in G.
A maximal matching in a graph is a matching in which adding any edge would cause the set to no longer be a
valid matching.
Parameters
• G (NetworkX graph)
• matching (dict or set) – A dictionary or set representing a matching. If a dictionary, it
must have matching[u] == v and matching[v] == u for each edge (u, v) in
the matching. If a set, it must have elements of the form (u, v), where (u, v) is an
edge in the matching.
Returns Whether the given set or dictionary represents a valid maximal matching in the graph.
Return type bool
3.37.3 networkx.algorithms.matching.is_perfect_matching
is_perfect_matching(G, matching)
Decides whether the given set represents a valid perfect matching in G.
A perfect matching in a graph is a matching in which exactly one edge is incident upon each vertex.
Parameters
• G (NetworkX graph)
• matching (dict or set) – A dictionary or set representing a matching. If a dictionary, it
must have matching[u] == v and matching[v] == u for each edge (u, v) in
the matching. If a set, it must have elements of the form (u, v), where (u, v) is an
edge in the matching.
Returns Whether the given set or dictionary represents a valid perfect matching in the graph.
Return type bool
3.37.4 networkx.algorithms.matching.maximal_matching
maximal_matching(G)
Find a maximal matching in the graph.
A matching is a subset of edges in which no node occurs more than once. A maximal matching cannot add more
edges and still be a matching.
Parameters G (NetworkX graph) – Undirected graph
Returns matching – A maximal matching of the graph.
Return type set
Notes
The algorithm greedily selects a maximal matching M of the graph G (i.e. no superset of M exists). It runs in
𝑂(|𝐸|) time.
3.37.5 networkx.algorithms.matching.max_weight_matching
A matching is a subset of edges in which no node occurs more than once. The weight of a matching is the sum
of the weights of its edges. A maximal matching cannot add more edges and still be a matching. The cardinality
of a matching is the number of matched edges.
Parameters
• G (NetworkX graph) – Undirected graph
• maxcardinality (bool, optional (default=False)) – If maxcardinality is True, compute the
maximum-cardinality matching with maximum weight among all maximum-cardinality
matchings.
• weight (string, optional (default=’weight’)) – Edge data key corresponding to the edge
weight. If key not found, uses 1 as weight.
Returns matching – A maximal matching of the graph.
Return type set
Notes
If G has edges with weight attributes 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 Edmonds1 .
Bipartite graphs can also be matched using the functions present in networkx.algorithms.bipartite.
matching.
References
3.38 Minors
contracted_edge(G, edge[, self_loops]) Returns the graph that results from contracting the spec-
ified edge.
contracted_nodes(G, u, v[, self_loops]) Returns the graph that results from contracting u and v.
identified_nodes(G, u, v[, self_loops]) Returns the graph that results from contracting u and v.
quotient_graph(G, partition[, . . . ]) Returns the quotient graph of G under the specified
equivalence relation on nodes.
3.38.1 networkx.algorithms.minors.contracted_edge
to the original two nodes. A graph that results from edge contraction is called a minor of the original graph.
Parameters
• G (NetworkX graph) – The graph whose edge will be contracted.
• edge (tuple) – Must be a pair of nodes in G.
• self_loops (Boolean) – If this is True, any edges (including edge) joining the endpoints of
edge in G become self-loops on the new node in the returned graph.
Returns A new graph object of the same type as G (leaving G unmodified) with endpoints of edge
identified in a single node. The right node of edge will be merged into the left one, so only the
left one will appear in the returned graph.
Return type Networkx graph
Raises ValueError – If edge is not an edge in G.
Examples
Contracting two adjacent nodes in the cycle graph on n nodes yields the cycle graph on n - 1 nodes:
See also:
contracted_nodes(), quotient_graph()
3.38.2 networkx.algorithms.minors.contracted_nodes
contracted_nodes(G, u, v, self_loops=True)
Returns the graph that results from contracting u and v.
Node contraction identifies the two nodes as a single node incident to any edge that was incident to the original
two nodes.
Parameters
• G (NetworkX graph) – The graph whose nodes will be contracted.
• u, v (nodes) – Must be nodes in G.
• self_loops (Boolean) – If this is True, any edges joining u and v in G become self-loops on
the new node in the returned graph.
Returns A new graph object of the same type as G (leaving G unmodified) with u and v identified
in a single node. The right node v will be merged into the node u, so only u will appear in the
returned graph.
Return type Networkx graph
Notes
For multigraphs, the edge keys for the realigned edges may not be the same as the edge keys for the old edges.
This is natural because edge keys are unique only within each pair of nodes.
Examples
Contracting two nonadjacent nodes of the cycle graph on four nodes C_4 yields the path graph (ignoring parallel
edges):
>>> G = nx.cycle_graph(4)
>>> M = nx.contracted_nodes(G, 1, 3)
>>> P3 = nx.path_graph(3)
>>> nx.is_isomorphic(M, P3)
True
>>> G = nx.MultiGraph(P3)
>>> M = nx.contracted_nodes(G, 0, 2)
>>> M.edges
MultiEdgeView([(0, 1, 0), (0, 1, 1)])
See also:
contracted_edge(), quotient_graph()
Notes
3.38.3 networkx.algorithms.minors.identified_nodes
identified_nodes(G, u, v, self_loops=True)
Returns the graph that results from contracting u and v.
Node contraction identifies the two nodes as a single node incident to any edge that was incident to the original
two nodes.
Parameters
• G (NetworkX graph) – The graph whose nodes will be contracted.
• u, v (nodes) – Must be nodes in G.
• self_loops (Boolean) – If this is True, any edges joining u and v in G become self-loops on
the new node in the returned graph.
Returns A new graph object of the same type as G (leaving G unmodified) with u and v identified
in a single node. The right node v will be merged into the node u, so only u will appear in the
returned graph.
Return type Networkx graph
Notes
For multigraphs, the edge keys for the realigned edges may not be the same as the edge keys for the old edges.
This is natural because edge keys are unique only within each pair of nodes.
Examples
Contracting two nonadjacent nodes of the cycle graph on four nodes C_4 yields the path graph (ignoring parallel
edges):
>>> G = nx.cycle_graph(4)
>>> M = nx.contracted_nodes(G, 1, 3)
>>> P3 = nx.path_graph(3)
>>> nx.is_isomorphic(M, P3)
True
>>> G = nx.MultiGraph(P3)
>>> M = nx.contracted_nodes(G, 0, 2)
>>> M.edges
MultiEdgeView([(0, 1, 0), (0, 1, 1)])
See also:
contracted_edge(), quotient_graph()
Notes
3.38.4 networkx.algorithms.minors.quotient_graph
• partition (function or list of sets) – If a function, this function must represent an equivalence
relation on the nodes of G. It must take two arguments u and v and return True exactly when
u and v are in the same equivalence class. The equivalence classes form the nodes in the
returned graph.
If a list of sets, the list must form a valid partition of the nodes of the graph. That is, each
node must be in exactly one block of the partition.
• edge_relation (Boolean function with two arguments) – This function must represent an
edge relation on the blocks of G in the partition induced by node_relation. It must take
two arguments, B and C, each one a set of nodes, and return True exactly when there should
be an edge joining block B to block C in the returned graph.
If edge_relation is not specified, it is assumed to be the following relation. Block B is
related to block C if and only if some node in B is adjacent to some node in C, according to
the edge set of G.
• edge_data (function) – This function takes two arguments, B and C, each one a set of nodes,
and must return a dictionary representing the edge data attributes to set on the edge joining
B and C, should there be an edge joining B and C in the quotient graph (if no such edge
occurs in the quotient graph as determined by edge_relation, then the output of this
function is ignored).
If the quotient graph would be a multigraph, this function is not applied, since the edge data
from each edge in the graph G appears in the edges of the quotient graph.
• node_data (function) – This function takes one argument, B, a set of nodes in G, and must
return a dictionary representing the node data attributes to set on the node representing B in
the quotient graph. If None, the following node attributes will be set:
– ‘graph’, the subgraph of the graph G that this block represents,
– ‘nnodes’, the number of nodes in this block,
– ‘nedges’, the number of edges within this block,
– ‘density’, the density of the subgraph of G that this block represents.
• relabel (bool) – If True, relabel the nodes of the quotient graph to be nonnegative integers.
Otherwise, the nodes are identified with frozenset instances representing the blocks
given in partition.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns The quotient graph of G under the equivalence relation specified by partition. If the
partition were given as a list of set instances and relabel is False, each node will be a
frozenset corresponding to the same set.
Return type NetworkX graph
Raises NetworkXException – If the given partition is not a valid partition of the nodes of G.
Examples
The quotient graph of the complete bipartite graph under the “same neighbors” equivalence relation is K_2.
Under this relation, two nodes are equivalent if they are not adjacent but have the same neighbor set:
The quotient graph of a directed graph under the “same strongly connected component” equivalence relation
is the condensation of the graph (see condensation()). This example comes from the Wikipedia article
‘Strongly connected component‘_:
Node identification can be represented as the quotient of a graph under the equivalence relation that places the
two nodes in one block and each other node in its own singleton block:
>>> G = nx.path_graph(6)
>>> partition = [{0, 1}, {2, 3}, {4, 5}]
>>> M = nx.quotient_graph(G, partition, relabel=True)
>>> list(M.edges())
[(0, 1), (1, 2)]
1 Patrick Doreian, Vladimir Batagelj, and Anuska Ferligoj. Generalized Blockmodeling. Cambridge University Press, 2004.
References
3.39.1 networkx.algorithms.mis.maximal_independent_set
Examples
>>> G = nx.path_graph(5)
>>> nx.maximal_independent_set(G) # doctest: +SKIP
[4, 0, 2]
>>> nx.maximal_independent_set(G, [1]) # doctest: +SKIP
[1, 3]
Notes
This algorithm does not solve the maximum independent set problem.
References
Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August). Semi-supervised learning using gaussian fields and harmonic
functions. In ICML (Vol. 3, pp. 912-919).
networkx.algorithms.node_classification.hmn.harmonic_function
Examples
References
Zhu, X., Ghahramani, Z., & Lafferty, J. (2003, August). Semi-supervised learning using gaussian fields and
harmonic functions. In ICML (Vol. 3, pp. 912-919).
Function for computing Local and global consistency algorithm by Zhou et al.
References
Zhou, D., Bousquet, O., Lal, T. N., Weston, J., & Schölkopf, B. (2004). Learning with local and global consistency.
Advances in neural information processing systems, 16(16), 321-328.
networkx.algorithms.node_classification.lgc.local_and_global_consistency
Examples
References
Zhou, D., Bousquet, O., Lal, T. N., Weston, J., & Schölkopf, B. (2004). Learning with local and global consis-
tency. Advances in neural information processing systems, 16(16), 321-328.
3.41 Operators
3.41.1 networkx.algorithms.operators.unary.complement
complement(G)
Returns the graph complement of G.
Parameters G (graph) – A NetworkX graph
Returns GC
Return type 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.
3.41.2 networkx.algorithms.operators.unary.reverse
reverse(G, copy=True)
Returns 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 – The reversed G.
3.41.3 networkx.algorithms.operators.binary.compose
compose(G, H)
Returns 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 do not need to be
disjoint.
Parameters G, H (graph) – A NetworkX graph
Returns C
Return type 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.
For MultiGraphs, the edges are identified by incident nodes AND edge-key. This can cause surprises (i.e., edge
(1, 2) may or may not be the same in two graphs) if you use MultiGraph without keeping track of edge keys.
3.41.4 networkx.algorithms.operators.binary.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.
See also:
disjoint_union()
3.41.5 networkx.algorithms.operators.binary.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
Return type 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.
3.41.6 networkx.algorithms.operators.binary.intersection
intersection(G, H)
Returns 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.
Returns GH
Return type 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
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)
3.41.7 networkx.algorithms.operators.binary.difference
difference(G, H)
Returns 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
Return type 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)
3.41.8 networkx.algorithms.operators.binary.symmetric_difference
symmetric_difference(G, H)
Returns 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
Return type 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.
3.41.9 networkx.algorithms.operators.all.compose_all
compose_all(graphs)
Returns 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
Returns C
Return type A graph with the same type as the first graph in list
Raises ValueError – If graphs is an empty 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.
3.41.10 networkx.algorithms.operators.all.union_all
union_all(graphs, rename=(None, ))
Returns the union of all graphs.
The graphs must be disjoint, otherwise an exception is raised.
Parameters
• graphs (list of graphs) – List of NetworkX graphs
• rename (bool , default=(None, None)) – Node names of G and H can be changed by spec-
ifying the tuple rename=(‘G-‘,’H-‘) (for example). Node “u” in G is then renamed “G-u”
and “v” in H is renamed “H-v”.
Returns U
Return type a graph with the same type as the first graph in list
Raises ValueError – If graphs is an empty list.
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.
See also:
union(), disjoint_union_all()
3.41.11 networkx.algorithms.operators.all.disjoint_union_all
disjoint_union_all(graphs)
Returns 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
Return type A graph with the same type as the first graph in list
Raises ValueError – If graphs is an empty list.
Notes
3.41.12 networkx.algorithms.operators.all.intersection_all
intersection_all(graphs)
Returns 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 of NetworkX graphs
Returns R
Return type A new graph with the same type as the first graph in list
Raises ValueError – If graphs is an empty list.
Notes
Attributes from the graph, nodes, and edges are not copied to the new graph.
Graph products.
3.41.13 networkx.algorithms.operators.product.cartesian_product
cartesian_product(G, H)
Returns the Cartesian product of G and H.
The Cartesian product 𝑃 of the graphs 𝐺 and 𝐻 has a node set that is the Cartesian product of the node sets,
𝑉 (𝑃 ) = 𝑉 (𝐺) × 𝑉 (𝐻). 𝑃 has an edge ((𝑢, 𝑣), (𝑥, 𝑦)) if and only if either 𝑢 is equal to 𝑥 and both 𝑣 and 𝑦 are
adjacent in 𝐻 or if 𝑣 is equal to 𝑦 and both 𝑢 and 𝑥 are adjacent in 𝐺.
Parameters G, H (graphs) – Networkx graphs.
Returns P – 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 undirected.
Return type NetworkX graph
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.
Examples
>>> G = nx.Graph()
>>> H = nx.Graph()
>>> G.add_node(0, a1=True)
>>> H.add_node('a', a2='Spam')
>>> P = nx.cartesian_product(G, H)
>>> list(P)
[(0, 'a')]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
3.41.14 networkx.algorithms.operators.product.lexicographic_product
lexicographic_product(G, H)
Returns the lexicographic product of G and H.
The lexicographical product 𝑃 of the graphs 𝐺 and 𝐻 has a node set that is the Cartesian product of the node
sets, 𝑉 (𝑃 ) = 𝑉 (𝐺) × 𝑉 (𝐻). 𝑃 has an edge ((𝑢, 𝑣), (𝑥, 𝑦)) if and only if (𝑢, 𝑣) is an edge in 𝐺 or 𝑢 == 𝑣 and
(𝑥, 𝑦) is an edge in 𝐻.
Parameters G, H (graphs) – Networkx graphs.
Returns P – 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 undirected.
Return type NetworkX graph
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.
Examples
>>> G = nx.Graph()
>>> H = nx.Graph()
>>> G.add_node(0, a1=True)
>>> H.add_node('a', a2='Spam')
>>> P = nx.lexicographic_product(G, H)
>>> list(P)
[(0, 'a')]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
3.41.15 networkx.algorithms.operators.product.rooted_product
rooted_product(G, H, root)
Return the rooted product of graphs G and H rooted at root in H.
A new graph is constructed representing the rooted product of the inputted graphs, G and H, with a root in H. A
rooted product duplicates H for each nodes in G with the root of H corresponding to the node in G. Nodes are
renamed as the direct product of G and H. The result is a subgraph of the cartesian product.
Parameters
• G,H (graph) – A NetworkX graph
• root (node) – A node in H
Returns R
Return type The rooted product of G and H with a specified root in H
Notes
The nodes of R are the Cartesian Product of the nodes of G and H. The nodes of G and H are not relabeled.
3.41.16 networkx.algorithms.operators.product.strong_product
strong_product(G, H)
Returns the strong product of G and H.
The strong product 𝑃 of the graphs 𝐺 and 𝐻 has a node set that is the Cartesian product of the node sets,
𝑉 (𝑃 ) = 𝑉 (𝐺) × 𝑉 (𝐻). 𝑃 has an edge ((𝑢, 𝑣), (𝑥, 𝑦)) if and only if 𝑢 == 𝑣 and (𝑥, 𝑦) is an edge in 𝐻, or
𝑥 == 𝑦 and (𝑢, 𝑣) is an edge in 𝐺, or (𝑢, 𝑣) is an edge in 𝐺 and (𝑥, 𝑦) is an edge in 𝐻.
Parameters G, H (graphs) – Networkx graphs.
Returns P – 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 undirected.
Return type NetworkX graph
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.
Examples
>>> G = nx.Graph()
>>> H = nx.Graph()
>>> G.add_node(0, a1=True)
>>> H.add_node('a', a2='Spam')
>>> P = nx.strong_product(G, H)
>>> list(P)
[(0, 'a')]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
3.41.17 networkx.algorithms.operators.product.tensor_product
tensor_product(G, H)
Returns the tensor product of G and H.
The tensor product 𝑃 of the graphs 𝐺 and 𝐻 has a node set that is the tensor product of the node sets, 𝑉 (𝑃 ) =
𝑉 (𝐺) × 𝑉 (𝐻). 𝑃 has an edge ((𝑢, 𝑣), (𝑥, 𝑦)) if and only if (𝑢, 𝑥) is an edge in 𝐺 and (𝑣, 𝑦) is an edge in 𝐻.
Tensor product is sometimes also referred to as the categorical product, direct product, cardinal product or
conjunction.
Parameters G, H (graphs) – Networkx graphs.
Returns P – 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.
Return type NetworkX graph
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.
Examples
>>> G = nx.Graph()
>>> H = nx.Graph()
>>> G.add_node(0, a1=True)
>>> H.add_node('a', a2='Spam')
>>> P = nx.tensor_product(G, H)
>>> list(P)
[(0, 'a')]
Edge attributes and edge keys (for multigraphs) are also copied to the new product graph
3.41.18 networkx.algorithms.operators.product.power
power(G, k)
Returns the specified power of a graph.
The 𝑘, denoted 𝐺𝑘 , is a graph on the same set of nodes in which two distinct nodes 𝑢 and 𝑣 are adjacent in 𝐺𝑘
if and only if the shortest path distance between 𝑢 and 𝑣 in 𝐺 is at most 𝑘.
Parameters
• G (graph) – A NetworkX simple graph object.
• k (positive integer) – The power to which to raise the graph G.
Returns G to the power k.
Return type NetworkX simple graph
Raises
• ValueError – If the exponent k is not positive.
• NetworkXNotImplemented – If G is not a simple graph.
Examples
The number of edges will never decrease when taking successive powers:
>>> G = nx.path_graph(4)
>>> list(nx.power(G, 2).edges)
[(0, 1), (0, 2), (1, 2), (1, 3), (2, 3)]
>>> list(nx.power(G, 3).edges)
[(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
The k`th power of a cycle graph on *n* nodes is the complete graph on *n*
nodes, if `k is at least n // 2:
>>> G = nx.cycle_graph(5)
>>> H = nx.complete_graph(5)
>>> nx.is_isomorphic(nx.power(G, 2), H)
True
>>> G = nx.cycle_graph(8)
>>> H = nx.complete_graph(8)
>>> nx.is_isomorphic(nx.power(G, 4), H)
True
References
Notes
This definition of “power graph” comes from Exercise 3.1.6 of Graph Theory by Bondy and Murty1 .
3.42 Planarity
3.42.1 networkx.algorithms.planarity.check_planarity
check_planarity(G, counterexample=False)
Check if a graph is planar and return a counterexample or an embedding.
A graph is planar iff it can be drawn in a plane without any edge intersections.
Parameters
• G (NetworkX graph)
• counterexample (bool) – A Kuratowski subgraph (to proof non planarity) is only returned
if set to true.
Returns (is_planar, certificate) – is_planar is true if the graph is planar. If the graph is planar
certificate is a PlanarEmbedding otherwise it is a Kuratowski subgraph.
Return type (bool, NetworkX graph) tuple
1
Notes
A (combinatorial) embedding consists of cyclic orderings of the incident edges at each vertex. Given such
an embedding there are multiple approaches discussed in literature to drawing the graph (subject to various
constraints, e.g. integer coordinates), see e.g. [2].
The planarity check algorithm and extraction of the combinatorial embedding is based on the Left-Right Pla-
narity Test [1].
A counterexample is only generated if the corresponding parameter is set, because the complexity of the coun-
terexample generation is higher.
References
Examples
>>> G = nx.PlanarEmbedding()
>>> G.add_half_edge_cw(0, 1, None)
>>> G.add_half_edge_cw(0, 2, 1)
>>> G.add_half_edge_cw(0, 3, 2)
>>> G.add_half_edge_cw(1, 0, None)
>>> G.add_half_edge_cw(2, 0, None)
>>> G.add_half_edge_cw(3, 0, None)
Alternatively the same embedding can also be defined in counterclockwise orientation. The following results in
exactly the same PlanarEmbedding:
>>> G = nx.PlanarEmbedding()
>>> G.add_half_edge_ccw(0, 1, None)
>>> G.add_half_edge_ccw(0, 3, 1)
>>> G.add_half_edge_ccw(0, 2, 3)
>>> G.add_half_edge_ccw(1, 0, None)
>>> G.add_half_edge_ccw(2, 0, None)
>>> G.add_half_edge_ccw(3, 0, None)
After creating a graph, it is possible to validate that the PlanarEmbedding object is correct:
>>> G.check_structure()
Parameters
• start_node (node)
• end_node (node)
See also:
add_half_edge_ccw(), add_half_edge_cw(), connect_components()
check_structure()
Runs without exceptions if this object is valid.
Checks that the following properties are fulfilled:
• Edges go in both directions (because the edge attributes differ).
• Every edge has a ‘cw’ and ‘ccw’ attribute which corresponds to a correct planar embedding.
• A node with a degree larger than 0 has a node attribute ‘first_nbr’.
Running this method verifies that the underlying Graph must be planar.
Raises nx.NetworkXException – This exception is raised with a short explanation if the
PlanarEmbedding is invalid.
connect_components(v, w)
Adds half-edges for (v, w) and (w, v) at some position.
This method should only be called if v and w are in different components, or it might break the embed-
ding. This especially means that if connect_components(v, w) is called it is not allowed to call
connect_components(w, v) afterwards. The neighbor orientations in both directions are all set
correctly after the first call.
Parameters
• v (node)
• w (node)
See also:
add_half_edge_ccw(), add_half_edge_cw(), add_half_edge_first()
get_data()
Converts the adjacency structure into a better readable structure.
Returns embedding – A dict mapping all nodes to a list of neighbors sorted in clockwise order.
Return type dict
is_directed()
A valid PlanarEmbedding is undirected.
All reverse edges are contained, i.e. for every existing half-edge (v, w) the half-edge in the opposite
direction (w, v) is also contained.
neighbors_cw_order(v)
Generator for the neighbors of v in clockwise order.
Parameters v (node)
Yields node
next_face_half_edge(v, w)
Returns the following half-edge left of a face.
Parameters
• v (node)
• w (node)
Returns half-edge
Return type tuple
traverse_face(v, w, mark_half_edges=None)
Returns nodes on the face that belong to the half-edge (v, w).
The face that is traversed lies to the right of the half-edge (in an orientation where v is below w).
Optionally it is possible to pass a set to which all encountered half edges are added. Before calling this
method, this set must not include any half-edges that belong to the face.
Parameters
• v (node) – Start node of half-edge.
• w (node) – End node of half-edge.
• mark_half_edges (set, optional) – Set to which all encountered half-edges are added.
Returns face – A list of nodes that lie on this face.
Return type list
3.43 Reciprocity
3.43.1 networkx.algorithms.reciprocity.reciprocity
reciprocity(G, nodes=None)
Compute the reciprocity in a directed graph.
The reciprocity of a directed graph is defined as the ratio of the number of edges pointing in both directions to
the total number of edges in the graph. Formally, 𝑟 = |(𝑢, 𝑣) ∈ 𝐺|(𝑣, 𝑢) ∈ 𝐺|/|(𝑢, 𝑣) ∈ 𝐺|.
The reciprocity of a single node u is defined similarly, it is the ratio of the number of edges in both directions to
the total number of edges attached to node u.
Parameters
• G (graph) – A networkx directed graph
• nodes (container of nodes, optional (default=whole graph)) – Compute reciprocity for
nodes in this container.
Returns out – Reciprocity keyed by node label.
Return type dictionary
Notes
The reciprocity is not defined for isolated nodes. In such cases this function will return None.
3.43.2 networkx.algorithms.reciprocity.overall_reciprocity
overall_reciprocity(G)
Compute the reciprocity for the whole graph.
See the doc of reciprocity for the definition.
Parameters G (graph) – A networkx graph
3.44.1 networkx.algorithms.richclub.rich_club_coefficient
where N_k is the number of nodes with degree larger than k, and E_k is the number of edges among those
nodes.
Parameters
• G (NetworkX graph) – Undirected graph with neither parallel edges nor self-loops.
• normalized (bool (optional)) – Normalize using randomized network as in1
• Q (float (optional, default=100)) – If normalized is True, perform Q * m double-edge
swaps, where m is the number of edges in G, to use as a null-model for normalization.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns rc – A dictionary, keyed by degree, with rich-club coefficient values.
Return type dictionary
1 Julian J. McAuley, Luciano da Fontoura Costa, and Tibério S. Caetano, “The rich-club phenomenon across complex network hierarchies”,
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] # doctest: +SKIP
0.4
Notes
The rich club definition and algorithm are found in1 . 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 in2 .
References
Compute the shortest paths and path lengths between nodes in the graph.
These algorithms work with undirected and directed graphs.
3.45.1 networkx.algorithms.shortest_paths.generic.shortest_path
Returns
path – All returned paths include both the source and target in the path.
If the source and target are both specified, return a single list of nodes in a shortest path from the
source to the target.
If only the source is specified, return a dictionary keyed by targets with a list of nodes in a
shortest path from the source to one of the targets.
If only the target is specified, return a dictionary keyed by sources with a list of nodes in a
shortest path from one of the sources to the target.
If neither the source nor target are specified return a dictionary of dictionaries with
path[source][target]=[list of nodes in path].
Return type list or dictionary
Raises
• NodeNotFound – If source is not in G.
• ValueError – If method is not among the supported options.
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]
Notes
There may be more than one shortest path between a source and target. This returns only one of them.
See also:
all_pairs_shortest_path(), all_pairs_dijkstra_path(),
all_pairs_bellman_ford_path(), single_source_shortest_path(),
single_source_dijkstra_path(), single_source_bellman_ford_path()
3.45.2 networkx.algorithms.shortest_paths.generic.all_shortest_paths
Examples
>>> G = nx.Graph()
>>> nx.add_path(G, [0, 1, 2])
>>> nx.add_path(G, [0, 10, 2])
>>> print([p for p in nx.all_shortest_paths(G, source=0, target=2)])
[[0, 1, 2], [0, 10, 2]]
Notes
There may be many shortest paths between the source and target.
See also:
shortest_path(), single_source_shortest_path(), all_pairs_shortest_path()
3.45.3 networkx.algorithms.shortest_paths.generic.shortest_path_length
Returns
length – If the source and target are both specified, return the length of the shortest path from
the source to the target.
If only the source is specified, return a dict keyed by target to the shortest path length from the
source to that target.
If only the target is specified, return a dict keyed by source to the shortest path length from that
source to the target.
If neither the source nor target are specified, return an iterator over (source, dictionary) where
dictionary is keyed by target to shortest path length from source to that target.
Return type int or iterator
Raises
• NodeNotFound – If source is not in G.
• NetworkXNoPath – If no path exists between source and target.
• ValueError – If method is not among the supported options.
Examples
>>> G = nx.path_graph(5)
>>> 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 = dict(nx.shortest_path_length(G)) # source,target not specified
>>> p[0][4]
4
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.
See also:
all_pairs_shortest_path_length(), all_pairs_dijkstra_path_length(),
all_pairs_bellman_ford_path_length(), single_source_shortest_path_length(),
single_source_dijkstra_path_length(), single_source_bellman_ford_path_length()
3.45.4 networkx.algorithms.shortest_paths.generic.average_shortest_path_length
where V is the set of nodes in G, d(s, t) is the shortest path from s to t, and n is the number of nodes in G.
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.
• method (string, optional (default = ‘dijkstra’)) – The algorithm to use to compute the path
lengths. Supported options: ‘dijkstra’, ‘bellman-ford’. Other inputs produce a ValueError.
If weight is None, unweighted graph methods are used, and this suggestion is ignored.
Raises
• NetworkXPointlessConcept – If G is the null graph (that is, the graph on zero nodes).
• NetworkXError – If G is not connected (or not weakly connected, in the case of a directed
graph).
• ValueError – If method is not among the supported options.
Examples
>>> G = nx.path_graph(5)
>>> nx.average_shortest_path_length(G)
2.0
For disconnected graphs, you can compute the average shortest path length for each component
3.45.5 networkx.algorithms.shortest_paths.generic.has_path
single_source_shortest_path(G, source[, Compute shortest path between source and all other
cutoff]) nodes reachable from source.
single_source_shortest_path_length(G, Compute the shortest path lengths from source to all
source) reachable nodes.
single_target_shortest_path(G, target[, Compute shortest path to target from all nodes that reach
cutoff]) target.
single_target_shortest_path_length(G, Compute the shortest path lengths to target from all
target) reachable nodes.
bidirectional_shortest_path(G, source, tar- Returns a list of nodes in a shortest path between source
get) and target.
all_pairs_shortest_path(G[, cutoff]) Compute shortest paths between all nodes.
all_pairs_shortest_path_length(G[, cut- Computes the shortest path lengths between all nodes in
off]) G.
predecessor(G, source[, target, cutoff, . . . ]) Returns dict of predecessors for the path from source to
all nodes in G
networkx.algorithms.shortest_paths.unweighted.single_source_shortest_path
Examples
>>> G = nx.path_graph(5)
>>> path = nx.single_source_shortest_path(G, 0)
>>> path[4]
[0, 1, 2, 3, 4]
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.
See also:
shortest_path()
networkx.algorithms.shortest_paths.unweighted.single_source_shortest_path_length
Examples
>>> G = nx.path_graph(5)
>>> length = nx.single_source_shortest_path_length(G, 0)
>>> length[4]
4
>>> for node in length:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 3
4: 4
See also:
shortest_path_length()
networkx.algorithms.shortest_paths.unweighted.single_target_shortest_path
Examples
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.
See also:
shortest_path(), single_source_shortest_path()
networkx.algorithms.shortest_paths.unweighted.single_target_shortest_path_length
Examples
See also:
single_source_shortest_path_length(), shortest_path_length()
networkx.algorithms.shortest_paths.unweighted.bidirectional_shortest_path
Parameters
• G (NetworkX graph)
• source (node label) – starting node for path
• target (node label) – ending node for path
Returns path – List of nodes in a path from source to target.
Return type list
Raises NetworkXNoPath – If no path exists between source and target.
See also:
shortest_path()
Notes
networkx.algorithms.shortest_paths.unweighted.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 at which to stop the search. Only paths of length at most
cutoff are returned.
Returns lengths – Dictionary, keyed by source and target, of shortest paths.
Return type dictionary
Examples
>>> G = nx.path_graph(5)
>>> path = dict(nx.all_pairs_shortest_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
See also:
floyd_warshall()
networkx.algorithms.shortest_paths.unweighted.all_pairs_shortest_path_length
all_pairs_shortest_path_length(G, cutoff=None)
Computes the shortest path lengths between all nodes in G.
Parameters
• G (NetworkX graph)
• cutoff (integer, optional) – Depth at which to stop the search. Only paths of length at most
cutoff are returned.
Returns lengths – (source, dictionary) iterator with dictionary keyed by target and shortest path
length as the key value.
Return type iterator
Notes
Examples
>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_shortest_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print('1 - {}: {}'.format(node, length[1][node]))
1 - 0: 1
1 - 1: 0
1 - 2: 1
1 - 3: 2
1 - 4: 3
>>> length[3][2]
1
>>> length[2][2]
0
networkx.algorithms.shortest_paths.unweighted.predecessor
Examples
>>> G = nx.path_graph(4)
>>> list(G)
[0, 1, 2, 3]
>>> nx.predecessor(G, 0)
{0: [], 1: [0], 2: [1], 3: [2]}
networkx.algorithms.shortest_paths.weighted.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.
Examples
networkx.algorithms.shortest_paths.weighted.dijkstra_path
Examples
>>> G=nx.path_graph(5)
>>> print(nx.dijkstra_path(G,0,4))
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
The weight function can be used to include node weights.
>>> def func(u, v, d):
... node_u_wt = G.nodes[u].get('node_weight', 1)
... node_v_wt = G.nodes[v].get('node_weight', 1)
... edge_wt = d.get('weight', 1)
... return node_u_wt/2 + node_v_wt/2 + edge_wt
In this example we take the average of start and end node weights of an edge and add it to the weight of the
edge.
See also:
bidirectional_dijkstra(), bellman_ford_path()
networkx.algorithms.shortest_paths.weighted.dijkstra_path_length
Examples
>>> G=nx.path_graph(5)
>>> print(nx.dijkstra_path_length(G,0,4))
4
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
See also:
bidirectional_dijkstra(), bellman_ford_path_length()
networkx.algorithms.shortest_paths.weighted.single_source_dijkstra
Parameters
• G (NetworkX graph)
• source (node label) – Starting node for path
• target (node label, optional) – Ending node for path
• cutoff (integer or float, optional) – Depth to stop the search. Only return paths with length
<= cutoff.
• weight (string or function) – If this is a string, then edge weights will be accessed via
the edge attribute with this key (that is, the weight of the edge joining u to v will be G.
edges[u, v][weight]). If no such edge attribute exists, the weight of the edge is
assumed to be one.
If this is a function, the weight of an edge is the value returned by the function. The func-
tion must accept exactly three positional arguments: the two endpoints of an edge and the
dictionary of edge attributes for that edge. The function must return a number.
Returns distance, path – If target is None, paths and lengths to all nodes are computed. The return
value is a tuple of two dictionaries keyed by target nodes. The first dictionary stores distance to
each target node. The second stores the path to each target node. If target is not None, returns
a tuple (distance, path), where distance is the distance from source to target and path is a list
representing the path from source to target.
Return type pair of dictionaries, or numeric and list.
Raises NodeNotFound – If source is not in G.
Examples
>>> G = nx.path_graph(5)
>>> length, path = nx.single_source_dijkstra(G, 0)
>>> print(length[4])
4
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 3
4: 4
>>> path[4]
[0, 1, 2, 3, 4]
>>> length, path = nx.single_source_dijkstra(G, 0, 1)
>>> length
1
>>> path
[0, 1]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
networkx.algorithms.shortest_paths.weighted.single_source_dijkstra_path
Examples
>>> G=nx.path_graph(5)
>>> path=nx.single_source_dijkstra_path(G,0)
>>> path[4]
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
See also:
single_source_dijkstra(), single_source_bellman_ford()
networkx.algorithms.shortest_paths.weighted.single_source_dijkstra_path_length
Examples
>>> G = nx.path_graph(5)
>>> length = nx.single_source_dijkstra_path_length(G, 0)
>>> length[4]
4
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 3
4: 4
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
See also:
single_source_dijkstra(), single_source_bellman_ford_path_length()
networkx.algorithms.shortest_paths.weighted.multi_source_dijkstra
Examples
>>> G = nx.path_graph(5)
>>> length, path = nx.multi_source_dijkstra(G, {0, 4})
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 1
4: 0
>>> path[1]
[0, 1]
>>> path[3]
[4, 3]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
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).
Raises
• ValueError – If sources is empty.
• NodeNotFound – If any of sources is not in G.
See also:
multi_source_dijkstra_path(), multi_source_dijkstra_path_length()
networkx.algorithms.shortest_paths.weighted.multi_source_dijkstra_path
Examples
>>> G = nx.path_graph(5)
>>> path = nx.multi_source_dijkstra_path(G, {0, 4})
>>> path[1]
[0, 1]
(continues on next page)
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
Raises
• ValueError – If sources is empty.
• NodeNotFound – If any of sources is not in G.
See also:
multi_source_dijkstra(), multi_source_bellman_ford()
networkx.algorithms.shortest_paths.weighted.multi_source_dijkstra_path_length
Examples
>>> G = nx.path_graph(5)
>>> length = nx.multi_source_dijkstra_path_length(G, {0, 4})
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 1
4: 0
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The weight function can be used to hide edges by returning None. So weight = lambda u, v, d: 1
if d['color']=="red" else None will find the shortest red path.
Raises
• ValueError – If sources is empty.
• NodeNotFound – If any of sources is not in G.
See also:
multi_source_dijkstra()
networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra
Examples
>>> G = nx.path_graph(5)
>>> len_path = dict(nx.all_pairs_dijkstra(G))
>>> print(len_path[3][0][1])
2
>>> for node in [0, 1, 2, 3, 4]:
... print('3 - {}: {}'.format(node, len_path[3][0][node]))
3 - 0: 3
3 - 1: 2
3 - 2: 1
3 - 3: 0
3 - 4: 1
>>> len_path[3][1][1]
[3, 2, 1]
>>> for n, (dist, path) in nx.all_pairs_dijkstra(G):
... print(path[1])
[0, 1]
[1]
[2, 1]
[3, 2, 1]
[4, 3, 2, 1]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
The yielded dicts only have keys for reachable nodes.
networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path
Examples
>>> G = nx.path_graph(5)
>>> path = dict(nx.all_pairs_dijkstra_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
floyd_warshall(), all_pairs_bellman_ford_path()
networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path_length
Examples
>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_dijkstra_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print('1 - {}: {}'.format(node, length[1][node]))
1 - 0: 1
1 - 1: 0
1 - 2: 1
1 - 3: 2
1 - 4: 3
>>> length[3][2]
1
>>> length[2][2]
0
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.
networkx.algorithms.shortest_paths.weighted.bidirectional_dijkstra
Examples
>>> G = nx.path_graph(5)
>>> length, path = nx.bidirectional_dijkstra(G, 0, 4)
>>> print(length)
4
>>> print(path)
[0, 1, 2, 3, 4]
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).
See also:
shortest_path(), shortest_path_length()
networkx.algorithms.shortest_paths.weighted.bellman_ford_path
Examples
>>> G=nx.path_graph(5)
>>> print(nx.bellman_ford_path(G, 0, 4))
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
dijkstra_path(), bellman_ford_path_length()
networkx.algorithms.shortest_paths.weighted.bellman_ford_path_length
• weight (string, optional (default=’weight’)) – Edge data key corresponding to the edge
weight
Returns length – Shortest path length.
Return type number
Raises
• NodeNotFound – If source is not in G.
• NetworkXNoPath – If no path exists between source and target.
Examples
>>> G=nx.path_graph(5)
>>> print(nx.bellman_ford_path_length(G,0,4))
4
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
dijkstra_path_length(), bellman_ford_path()
networkx.algorithms.shortest_paths.weighted.single_source_bellman_ford
Examples
>>> G = nx.path_graph(5)
>>> length, path = nx.single_source_bellman_ford(G, 0)
>>> print(length[4])
4
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 3
4: 4
>>> path[4]
[0, 1, 2, 3, 4]
>>> length, path = nx.single_source_bellman_ford(G, 0, 1)
>>> length
1
>>> path
[0, 1]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
single_source_dijkstra(), single_source_bellman_ford_path(),
single_source_bellman_ford_path_length()
networkx.algorithms.shortest_paths.weighted.single_source_bellman_ford_path
Examples
>>> G=nx.path_graph(5)
>>> path=nx.single_source_bellman_ford_path(G,0)
>>> path[4]
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
single_source_dijkstra(), single_source_bellman_ford()
networkx.algorithms.shortest_paths.weighted.single_source_bellman_ford_path_length
Examples
>>> G = nx.path_graph(5)
>>> length = dict(nx.single_source_bellman_ford_path_length(G, 0))
>>> length[4]
4
>>> for node in [0, 1, 2, 3, 4]:
... print('{}: {}'.format(node, length[node]))
0: 0
1: 1
2: 2
3: 3
4: 4
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
single_source_dijkstra(), single_source_bellman_ford()
networkx.algorithms.shortest_paths.weighted.all_pairs_bellman_ford_path
all_pairs_bellman_ford_path(G, weight=’weight’)
Compute shortest paths between all nodes in a weighted graph.
Parameters
• G (NetworkX graph)
• weight (string, optional (default=’weight’)) – Edge data key corresponding to the edge
weight
Returns distance – Dictionary, keyed by source and target, of shortest paths.
Return type dictionary
Examples
>>> G = nx.path_graph(5)
>>> path = dict(nx.all_pairs_bellman_ford_path(G))
>>> print(path[0][4])
[0, 1, 2, 3, 4]
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
See also:
floyd_warshall(), all_pairs_dijkstra_path()
networkx.algorithms.shortest_paths.weighted.all_pairs_bellman_ford_path_length
all_pairs_bellman_ford_path_length(G, weight=’weight’)
Compute shortest path lengths between all nodes in a weighted graph.
Parameters
• G (NetworkX graph)
• weight (string, optional (default=’weight’)) – Edge data key corresponding to the edge
weight
Returns distance – (source, dictionary) iterator with dictionary keyed by target and shortest path
length as the key value.
Return type iterator
Examples
>>> G = nx.path_graph(5)
>>> length = dict(nx.all_pairs_bellman_ford_path_length(G))
>>> for node in [0, 1, 2, 3, 4]:
... print('1 - {}: {}'.format(node, length[1][node]))
1 - 0: 1
1 - 1: 0
1 - 2: 1
1 - 3: 2
1 - 4: 3
>>> length[3][2]
1
>>> length[2][2]
0
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.
networkx.algorithms.shortest_paths.weighted.bellman_ford_predecessor_and_distance
Examples
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.
In NetworkX v2.1 and prior, the source node had predecessor [None]. In NetworkX v2.2 this changed to the
source node having predecessor []
networkx.algorithms.shortest_paths.weighted.negative_edge_cycle
negative_edge_cycle(G, weight=’weight’)
Returns True if there exists a negative edge cycle anywhere in G.
Parameters
• G (NetworkX graph)
• weight (string or function) – If this is a string, then edge weights will be accessed via
the edge attribute with this key (that is, the weight of the edge joining u to v will be G.
edges[u, v][weight]). If no such edge attribute exists, the weight of the edge is
assumed to be one.
If this is a function, the weight of an edge is the value returned by the function. The func-
tion must accept exactly three positional arguments: the two endpoints of an edge and the
dictionary of edge attributes for that edge. The function must return a number.
Returns negative_cycle – True if a negative edge cycle exists, otherwise False.
Return type bool
Examples
Notes
Edge weight attributes must be numerical. Distances are calculated as sums of weighted edges traversed.
This algorithm uses bellman_ford_predecessor_and_distance() but finds negative cycles on any component by
first adding a new node connected to every node, and starting bellman_ford_predecessor_and_distance on that
node. It then removes that extra node.
networkx.algorithms.shortest_paths.weighted.goldberg_radzik
Examples
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.
networkx.algorithms.shortest_paths.weighted.johnson
johnson(G, weight=’weight’)
Uses Johnson’s Algorithm to compute shortest paths.
Johnson’s Algorithm finds a shortest path between each pair of nodes in a weighted graph even if negative
weights are present.
Parameters
• G (NetworkX graph)
• weight (string or function) – If this is a string, then edge weights will be accessed via
the edge attribute with this key (that is, the weight of the edge joining u to v will be G.
edges[u, v][weight]). If no such edge attribute exists, the weight of the edge is
assumed to be one.
If this is a function, the weight of an edge is the value returned by the function. The func-
tion must accept exactly three positional arguments: the two endpoints of an edge and the
dictionary of edge attributes for that edge. The function must return a number.
Returns distance – Dictionary, keyed by source and target, of shortest paths.
Return type dictionary
Raises NetworkXError – If given graph is not weighted.
Examples
Notes
Johnson’s algorithm is suitable even for graphs with negative weights. It works by using the Bellman–Ford
algorithm to compute a transformation of the input graph that removes all negative weights, allowing Dijkstra’s
algorithm to be used on the transformed graph.
The time complexity of this algorithm is 𝑂(𝑛2 log 𝑛 + 𝑛𝑚), where 𝑛 is the number of nodes and 𝑚 the number
of edges in the graph. For dense graphs, this may be faster than the Floyd–Warshall algorithm.
See also:
floyd_warshall_predecessor_and_distance(), floyd_warshall_numpy(),
all_pairs_shortest_path(), all_pairs_shortest_path_length(),
all_pairs_dijkstra_path(), bellman_ford_predecessor_and_distance(),
all_pairs_bellman_ford_path(), all_pairs_bellman_ford_path_length()
floyd_warshall(G[, weight]) Find all-pairs shortest path lengths using Floyd’s algo-
rithm.
floyd_warshall_predecessor_and_distance(G[, Find all-pairs shortest path lengths using Floyd’s algo-
. . . ]) rithm.
floyd_warshall_numpy(G[, nodelist, weight]) Find all-pairs shortest path lengths using Floyd’s algo-
rithm.
reconstruct_path(source, target, predecessors) Reconstruct a path from source to target us-
ing the predecessors dict as returned by
floyd_warshall_predecessor_and_distance
networkx.algorithms.shortest_paths.dense.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 – A dictionary, keyed by source and target, of shortest paths distances between
nodes.
Return type dict
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 𝑂(𝑛3 )
with running space of 𝑂(𝑛2 ).
See also:
floyd_warshall_predecessor_and_distance(), floyd_warshall_numpy(),
all_pairs_shortest_path(), all_pairs_shortest_path_length()
networkx.algorithms.shortest_paths.dense.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, keyed by source and target, of predecessors and dis-
tances in the shortest path.
Return type dictionaries
Examples
>>> 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)])
>>> predecessors, _ = nx.floyd_warshall_predecessor_and_distance(G)
>>> print(nx.reconstruct_path('s', 'v', predecessors))
['s', 'x', 'u', 'v']
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 𝑂(𝑛3 )
with running space of 𝑂(𝑛2 ).
See also:
floyd_warshall(), floyd_warshall_numpy(), all_pairs_shortest_path(),
all_pairs_shortest_path_length()
networkx.algorithms.shortest_paths.dense.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 𝑂(𝑛3 )
with running space of 𝑂(𝑛2 ).
networkx.algorithms.shortest_paths.dense.reconstruct_path
Notes
3.45.8 A* Algorithm
Shortest paths and path lengths using the A* (“A star”) algorithm.
astar_path(G, source, target[, heuristic, . . . ]) Returns a list of nodes in a shortest path between source
and target using the A* (“A-star”) algorithm.
astar_path_length(G, source, target[, . . . ]) Returns the length of the shortest path between source
and target using the A* (“A-star”) algorithm.
networkx.algorithms.shortest_paths.astar.astar_path
• weight (string, optional (default=’weight’)) – Edge data key corresponding to the edge
weight.
Raises NetworkXNoPath – If no path exists between source and target.
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)
>>> nx.set_edge_attributes(G, {e: e[1][0]*2 for e in G.edges()}, 'cost')
>>> 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), heuristic=dist, weight='cost'))
[(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
See also:
shortest_path(), dijkstra_path()
networkx.algorithms.shortest_paths.astar.astar_path_length
graph_edit_distance(G1, G2[, node_match, Returns GED (graph edit distance) between graphs G1
. . . ]) and G2.
optimal_edit_paths(G1, G2[, node_match, . . . ]) Returns all minimum-cost edit paths transforming G1 to
G2.
optimize_graph_edit_distance(G1, G2[, Returns consecutive approximations of GED (graph edit
. . . ]) distance) between graphs G1 and G2.
optimize_edit_paths(G1, G2[, node_match, GED (graph edit distance) calculation: advanced inter-
. . . ]) face.
3.46.1 networkx.algorithms.similarity.graph_edit_distance
Examples
>>> G1 = nx.cycle_graph(6)
>>> G2 = nx.wheel_graph(7)
>>> nx.graph_edit_distance(G1, G2)
7.0
See also:
optimal_edit_paths(), optimize_graph_edit_distance(), is_isomorphic()
References
3.46.2 networkx.algorithms.similarity.optimal_edit_paths
node_match(G1.nodes[n1], G2.nodes[n2]).
That is, the function will receive the node attribute dictionaries for n1 and n2 as inputs.
Ignored if node_subst_cost is specified. If neither node_match nor node_subst_cost are
specified then node attributes are not considered.
• edge_match (callable) – A function that returns True if the edge attribute dictionaries for
the pair of nodes (u1, v1) in G1 and (u2, v2) in G2 should be considered equal during
matching.
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 consider-
ation.
Ignored if edge_subst_cost is specified. If neither edge_match nor edge_subst_cost are spec-
ified then edge attributes are not considered.
• node_subst_cost, node_del_cost, node_ins_cost (callable) – Functions that return the
costs of node substitution, node deletion, and node insertion, respectively.
The functions will be called like
node_subst_cost(G1.nodes[n1], G2.nodes[n2]), node_del_cost(G1.nodes[n1]),
node_ins_cost(G2.nodes[n2]).
That is, the functions will receive the node attribute dictionaries as inputs. The functions are
expected to return positive numeric values.
Function node_subst_cost overrides node_match if specified. If neither node_match nor
node_subst_cost are specified then default node substitution cost of 0 is used (node attributes
are not considered during matching).
If node_del_cost is not specified then default node deletion cost of 1 is used. If
node_ins_cost is not specified then default node insertion cost of 1 is used.
• edge_subst_cost, edge_del_cost, edge_ins_cost (callable) – Functions that return the costs
of edge substitution, edge deletion, and edge insertion, respectively.
The functions will be called like
edge_subst_cost(G1[u1][v1], G2[u2][v2]), edge_del_cost(G1[u1][v1]),
edge_ins_cost(G2[u2][v2]).
That is, the functions will receive the edge attribute dictionaries as inputs. The functions are
expected to return positive numeric values.
Function edge_subst_cost overrides edge_match if specified. If neither edge_match nor
edge_subst_cost are specified then default edge substitution cost of 0 is used (edge attributes
are not considered during matching).
If edge_del_cost is not specified then default edge deletion cost of 1 is used. If edge_ins_cost
is not specified then default edge insertion cost of 1 is used.
• upper_bound (numeric) – Maximum edit distance to consider.
Returns
• edit_paths (list of tuples (node_edit_path, edge_edit_path)) – node_edit_path : list of tuples
(u, v) edge_edit_path : list of tuples ((u1, v1), (u2, v2))
• cost (numeric) – Optimal edit path cost (graph edit distance).
Examples
>>> G1 = nx.cycle_graph(6)
>>> G2 = nx.wheel_graph(7)
>>> paths, cost = nx.optimal_edit_paths(G1, G2)
>>> len(paths)
84
>>> cost
7.0
See also:
graph_edit_distance(), optimize_edit_paths()
References
3.46.3 networkx.algorithms.similarity.optimize_graph_edit_distance
Examples
>>> G1 = nx.cycle_graph(6)
>>> G2 = nx.wheel_graph(7)
>>> for v in nx.optimize_graph_edit_distance(G1, G2):
... minv = v
>>> minv
7.0
See also:
graph_edit_distance(), optimize_edit_paths()
References
3.46.4 networkx.algorithms.similarity.optimize_edit_paths
References
all_simple_paths(G, source, target[, cutoff]) Generate all simple paths in the graph G from source to
target.
is_simple_path(G, nodes) Returns True if and only if the given nodes form a sim-
ple path in G.
shortest_simple_paths(G, source, target[, . . . ]) Generate all simple paths in the graph G from source to
target,
3.47.1 networkx.algorithms.simple_paths.all_simple_paths
• cutoff (integer, optional) – Depth to stop the search. Only paths of length <= cutoff are
returned.
Returns path_generator – A generator that produces lists of simple paths. If there are no paths
between the source and target within the given cutoff the generator produces no output.
Return type generator
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]
You can generate only those paths that are shorter than a certain length by using the cutoff keyword argument:
To get each path as the corresponding list of edges, you can use the networkx.utils.pairwise() helper
function:
Pass an iterable of nodes as target to generate all paths ending in any of several nodes:
>>> G = nx.complete_graph(4)
>>> for path in nx.all_simple_paths(G, source=0, target=[3, 2]):
... print(path)
...
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 3]
[0, 1, 3, 2]
[0, 2]
[0, 2, 1, 3]
[0, 2, 3]
[0, 3]
[0, 3, 1, 2]
[0, 3, 2]
Iterate over each path from the root nodes to the leaf nodes in a directed acyclic graph using a functional
programming approach:
Iterate over each path from the root nodes to the leaf nodes in a directed acyclic graph passing all leaves together
to avoid unnecessary compute:
Notes
This algorithm uses a modified depth-first search to generate the paths1 . 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 𝑛.
References
See also:
all_shortest_paths(), shortest_path()
1 R. Sedgewick, “Algorithms in C, Part 5: Graph Algorithms”, Addison Wesley Professional, 3rd ed., 2001.
3.47.2 networkx.algorithms.simple_paths.is_simple_path
is_simple_path(G, nodes)
Returns True if and only if the given nodes form a simple path in G.
A simple path in a graph is a nonempty sequence of nodes in which no node appears more than once in the
sequence, and each adjacent pair of nodes in the sequence is adjacent in the graph.
Parameters nodes (list) – A list of one or more nodes in the graph G.
Returns Whether the given list of nodes represents a simple path in G.
Return type bool
Notes
A list of zero nodes is not a path and a list of one node is a path. Here’s an explanation why.
This function operates on node paths. One could also consider edge paths. There is a bijection between node
paths and edge paths.
The length of a path is the number of edges in the path, so a list of nodes of length n corresponds to a path of
length n - 1. Thus the smallest edge path would be a list of zero edges, the empty path. This corresponds to a
list of one node.
To convert between a node path and an edge path, you can use code like the following:
Examples
>>> G = nx.cycle_graph(4)
>>> nx.is_simple_path(G, [2, 3, 0])
True
>>> nx.is_simple_path(G, [0, 2])
False
3.47.3 networkx.algorithms.simple_paths.shortest_simple_paths
Examples
>>> G = nx.cycle_graph(7)
>>> paths = list(nx.shortest_simple_paths(G, 0, 3))
>>> print(paths)
[[0, 1, 2, 3], [0, 6, 5, 4, 3]]
You can use this function to efficiently compute the k shortest/best paths between two nodes.
Notes
This procedure is based on algorithm by Jin Y. Yen1 . Finding the first 𝐾 paths requires 𝑂(𝐾𝑁 3 ) operations.
See also:
all_shortest_paths(), shortest_path(), all_simple_paths()
References
712-716.
Both coefficients compare the average clustering coefficient and shortest path length of a given graph against the same
quantities for an equivalent random or lattice graph.
For more information, see the Wikipedia article on small-world network1 .
random_reference(G[, niter, connectivity, seed]) Compute a random graph by swapping edges of a given
graph.
lattice_reference(G[, niter, D, . . . ]) Latticize the given graph by swapping edges.
sigma(G[, niter, nrand, seed]) Returns the small-world coefficient (sigma) of the given
graph.
omega(G[, niter, nrand, seed]) Returns the small-world coefficient (omega) of a graph
3.48.1 networkx.algorithms.smallworld.random_reference
Notes
The implementation is adapted from the algorithm by Maslov and Sneppen (2002)1 .
References
3.48.2 networkx.algorithms.smallworld.lattice_reference
Notes
The implementation is adapted from the algorithm by Sporns et al.1 . which is inspired from the original work
by Maslov and Sneppen(2002)2 .
References
3.48.3 networkx.algorithms.smallworld.sigma
Notes
References
3.48.4 networkx.algorithms.smallworld.omega
Notes
References
3.49 s metric
3.49.1 networkx.algorithms.smetric.s_metric
s_metric(G, normalized=True)
Returns the s-metric of graph.
The s-metric is defined as the sum of the products deg(u)*deg(v) for every edge (u,v) in G. If norm is provided
construct the s-max graph and compute it’s s_metric, and return the normalized s value
Parameters
1
Telesford, Joyce, Hayasaka, Burdette, and Laurienti (2011). “The Ubiquity of Small-World Networks”. Brain Connectivity. 1 (0038): 367-75.
PMC 3604768. PMID 22432451. doi:10.1089/brain.2011.0038.
References
3.50 Sparsifiers
spanner(G, stretch[, weight, seed]) Returns a spanner of the given graph with the given
stretch.
3.50.1 networkx.algorithms.sparsifiers.spanner
Notes
This function implements the spanner algorithm by Baswana and Sen, see [1].
This algorithm is a randomized las vegas algorithm: The expected running time is O(km) where k = (stretch +
1) // 2 and m is the number of edges in G. The returned graph is always a spanner of the given graph with the
specified stretch. For weighted graphs the number of edges in the spanner is O(k * n^(1 + 1 / k)) where k is
defined as above and n is the number of nodes in G. For unweighted graphs the number of edges is O(n^(1 + 1 /
k) + kn).
References
[1] S. Baswana, S. Sen. A Simple and Linear Time Randomized Algorithm for Computing Sparse Spanners in
Weighted Graphs. Random Struct. Algorithms 30(4): 532-563 (2007).
constraint(G[, nodes, weight]) Returns the constraint on all nodes in the graph G.
effective_size(G[, nodes, weight]) Returns the effective size of all nodes in the graph G.
local_constraint(G, u, v[, weight]) Returns the local constraint on the node u with respect
to the node v in the graph G.
3.51.1 networkx.algorithms.structuralholes.constraint
where N(v) is the subset of the neighbors of v that are either predecessors or successors of v and
ell(v, w) is the local constraint on v with respect to w1 . For the definition of local constraint, see
local_constraint().
Parameters
• G (NetworkX graph) – The graph containing v. This can be either directed or undirected.
• nodes (container, optional) – Container of nodes in the graph G to compute the constraint.
If None, the constraint of every node is computed.
• weight (None or string, optional) – If None, all edge weights are considered equal. Other-
wise holds the name of the edge attribute used as weight.
Returns Dictionary with nodes as keys and the constraint on the node as values.
Return type dict
See also:
local_constraint()
References
3.51.2 networkx.algorithms.structuralholes.effective_size
𝑒(𝑢), is defined by
⎛ ⎞
∑︁ ∑︁
𝑒(𝑢) = ⎝1 − 𝑝𝑢𝑤 𝑚𝑣𝑤 ⎠
𝑣∈𝑁 (𝑢)∖{𝑢} 𝑤∈𝑁 (𝑣)
where 𝑁 (𝑢) is the set of neighbors of 𝑢 and 𝑝𝑢𝑤 is the normalized mutual weight of the (directed or undirected)
edges joining 𝑢 and 𝑣, for each vertex 𝑢 and 𝑣 1 . And 𝑚𝑣𝑤 is the mutual weight of 𝑣 and 𝑤 divided by 𝑣 highest
mutual weight with any of its neighbors. The mutual weight of 𝑢 and 𝑣 is the sum of the weights of edges joining
them (edge weights are assumed to be one if the graph is unweighted).
For the case of unweighted and undirected graphs, Borgatti proposed a simplified formula to compute effective
size2
2𝑡
𝑒(𝑢) = 𝑛 −
𝑛
where t is the number of ties in the ego network (not including ties to ego) and n is the number of nodes
(excluding ego).
Parameters
• G (NetworkX graph) – The graph containing v. Directed graphs are treated like undirected
graphs when computing neighbors of v.
• nodes (container, optional) – Container of nodes in the graph G to compute the effective
size. If None, the effective size of every node is computed.
• weight (None or string, optional) – If None, all edge weights are considered equal. Other-
wise holds the name of the edge attribute used as weight.
Returns Dictionary with nodes as keys and the constraint on the node as values.
Return type dict
Notes
Burt also defined the related concept of efficiency of a node’s ego network, which is its effective size divided by
the degree of that node1 . So you can easily compute efficiency:
>>> G = nx.DiGraph()
>>> G.add_edges_from([(0, 1), (0, 2), (1, 0), (2, 1)])
>>> esize = nx.effective_size(G)
>>> efficiency = {n: v / G.degree(n) for n, v in esize.items()}
See also:
constraint()
References
3.51.3 networkx.algorithms.structuralholes.local_constraint
local_constraint(G, u, v, weight=None)
Returns the local constraint on the node u with respect to the node v in the graph G.
2 Borgatti, S. “Structural Holes: Unpacking Burt’s Redundancy Measures” CONNECTIONS 20(1):35-38. http://www.analytictech.com/
connections/v20(1)/holes.htm
where 𝑁 (𝑣) is the set of neighbors of 𝑣 and 𝑝𝑢𝑣 is the normalized mutual weight of the (directed or undirected)
edges joining 𝑢 and 𝑣, for each vertex 𝑢 and 𝑣 1 . The mutual weight of 𝑢 and 𝑣 is the sum of the weights of edges
joining them (edge weights are assumed to be one if the graph is unweighted).
Parameters
• G (NetworkX graph) – The graph containing u and v. This can be either directed or undi-
rected.
• u (node) – A node in the graph G.
• v (node) – A node in the graph G.
• weight (None or string, optional) – If None, all edge weights are considered equal. Other-
wise holds the name of the edge attribute used as weight.
Returns The constraint of the node v in the graph G.
Return type float
See also:
constraint()
References
3.52 Swap
double_edge_swap(G[, nswap, max_tries, seed]) Swap two edges in the graph while keeping the node
degrees fixed.
connected_double_edge_swap(G[, nswap, Attempts the specified number of double-edge swaps in
. . . ]) the graph G.
3.52.1 networkx.algorithms.swap.double_edge_swap
u--v u v
becomes | |
x--y x y
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
1 Burt, Ronald S. “Structural holes and good ideas”. American Journal of Sociology (110): 349–399.
Notes
3.52.2 networkx.algorithms.swap.connected_double_edge_swap
u--v u v
becomes | |
x--y x y
If either (u, x) or (v, y) already exist, then no swap is performed so the actual number of swapped edges
is always at most nswap.
Parameters
• G (graph) – An undirected graph
• nswap (integer (optional, default=1)) – Number of double-edge swaps to perform
• _window_threshold (integer) – The window size below which connectedness of the graph
will be checked after each swap.
The “window” in this function is a dynamically updated integer that represents the number of
swap attempts to make before checking if the graph remains connected. It is an optimization
used to decrease the running time of the algorithm in exchange for increased complexity of
implementation.
If the window size is below this threshold, then the algorithm checks after each swap if the
graph remains connected by checking if there is a path joining the two nodes whose edge
was just removed. If the window size is above this threshold, then the algorithm performs
do all the swaps in the window and only then check if the graph is still connected.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns The number of successful swaps
Return type int
Raises NetworkXError – If the input graph is not connected, or if the graph has fewer than four
nodes.
Notes
The initial graph G must be connected, and the resulting graph is connected. The graph G is modified in place.
References
3.53 Tournament
3.53.1 networkx.algorithms.tournament.hamiltonian_path
hamiltonian_path(G)
Returns a Hamiltonian path in the given tournament graph.
Each tournament has a Hamiltonian path. If furthermore, the tournament is strongly connected, then the returned
Hamiltonian path is a Hamiltonian cycle (by joining the endpoints of the path).
Parameters G (NetworkX graph) – A directed graph representing a tournament.
Returns Whether the given graph is a tournament graph.
Return type bool
Notes
This is a recursive implementation with an asymptotic running time of 𝑂(𝑛2 ), ignoring multiplicative polylog-
arithmic factors, where 𝑛 is the number of nodes in the graph.
3.53.2 networkx.algorithms.tournament.is_reachable
is_reachable(G, s, t)
Decides whether there is a path from s to t in the tournament.
This function is more theoretically efficient than the reachability checks than the shortest path algorithms in
networkx.algorithms.shortest_paths.
The given graph must be a tournament, otherwise this function’s behavior is undefined.
Parameters
• G (NetworkX graph) – A directed graph representing a tournament.
• s (node) – A node in the graph.
• t (node) – A node in the graph.
Returns Whether there is a path from s to t in G.
Return type bool
Notes
Although this function is more theoretically efficient than the generic shortest path functions, a speedup requires
the use of parallelism. Though it may in the future, the current implementation does not use parallelism, thus
you may not see much of a speedup.
This algorithm comes from [1].
References
3.53.3 networkx.algorithms.tournament.is_strongly_connected
is_strongly_connected(G)
Decides whether the given tournament is strongly connected.
This function is more theoretically efficient than the is_strongly_connected() function.
The given graph must be a tournament, otherwise this function’s behavior is undefined.
Parameters G (NetworkX graph) – A directed graph representing a tournament.
Returns Whether the tournament is strongly connected.
Return type bool
Notes
Although this function is more theoretically efficient than the generic strong connectivity function, a speedup
requires the use of parallelism. Though it may in the future, the current implementation does not use parallelism,
thus you may not see much of a speedup.
References
3.53.4 networkx.algorithms.tournament.is_tournament
is_tournament(G)
Returns True if and only if G is a tournament.
A tournament is a directed graph, with neither self-loops nor multi-edges, in which there is exactly one directed
edge joining each pair of distinct nodes.
Parameters G (NetworkX graph) – A directed graph representing a tournament.
Returns Whether the given graph is a tournament graph.
Return type bool
Notes
Some definitions require a self-loop on each node, but that is not the convention used here.
3.53.5 networkx.algorithms.tournament.random_tournament
random_tournament(n, seed=None)
Returns a random tournament graph on n nodes.
Parameters
• n (int) – The number of nodes in the returned graph.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns Whether the given graph is a tournament graph.
Return type bool
Notes
This algorithm adds, for each pair of distinct nodes, an edge with uniformly random orientation. In other words,
binom{n}{2} flips of an unbiased coin decide the orientations of the edges in the graph.
3.53.6 networkx.algorithms.tournament.score_sequence
score_sequence(G)
Returns the score sequence for the given tournament graph.
The score sequence is the sorted list of the out-degrees of the nodes of the graph.
Parameters G (NetworkX graph) – A directed graph representing a tournament.
Returns A sorted list of the out-degrees of the nodes of G.
Return type list
3.54 Traversal
networkx.algorithms.traversal.depth_first_search.dfs_edges
Examples
>>> G = nx.path_graph(5)
>>> list(nx.dfs_edges(G, source=0))
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> list(nx.dfs_edges(G, source=0, depth_limit=2))
[(0, 1), (1, 2)]
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
See also:
dfs_preorder_nodes(), dfs_postorder_nodes(), dfs_labeled_edges(), edge_dfs()
networkx.algorithms.traversal.depth_first_search.dfs_tree
Examples
>>> G = nx.path_graph(5)
>>> T = nx.dfs_tree(G, source=0, depth_limit=2)
>>> list(T.edges())
[(0, 1), (1, 2)]
>>> T = nx.dfs_tree(G, source=0)
>>> list(T.edges())
[(0, 1), (1, 2), (2, 3), (3, 4)]
networkx.algorithms.traversal.depth_first_search.dfs_predecessors
Examples
>>> G = nx.path_graph(4)
>>> nx.dfs_predecessors(G, source=0)
{1: 0, 2: 1, 3: 2}
>>> nx.dfs_predecessors(G, source=0, depth_limit=2)
{1: 0, 2: 1}
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
networkx.algorithms.traversal.depth_first_search.dfs_successors
Examples
>>> G = nx.path_graph(5)
>>> nx.dfs_successors(G, source=0)
{0: [1], 1: [2], 2: [3], 3: [4]}
>>> nx.dfs_successors(G, source=0, depth_limit=2)
{0: [1], 1: [2]}
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
networkx.algorithms.traversal.depth_first_search.dfs_preorder_nodes
• G (NetworkX graph)
• source (node, optional) – Specify starting node for depth-first search and return edges in the
component reachable from source.
• depth_limit (int, optional (default=len(G))) – Specify the maximum search depth.
Returns nodes – A generator of nodes in a depth-first-search pre-ordering.
Return type generator
Examples
>>> G = nx.path_graph(5)
>>> list(nx.dfs_preorder_nodes(G, source=0))
[0, 1, 2, 3, 4]
>>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
[0, 1, 2]
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
See also:
dfs_edges(), dfs_postorder_nodes(), dfs_labeled_edges()
networkx.algorithms.traversal.depth_first_search.dfs_postorder_nodes
Examples
>>> G = nx.path_graph(5)
>>> list(nx.dfs_postorder_nodes(G, source=0))
[4, 3, 2, 1, 0]
>>> list(nx.dfs_postorder_nodes(G, source=0, depth_limit=2))
[1, 0]
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
See also:
dfs_edges(), dfs_preorder_nodes(), dfs_labeled_edges()
networkx.algorithms.traversal.depth_first_search.dfs_labeled_edges
Examples
The labels reveal the complete transcript of the depth-first search algorithm in more detail than, for example,
dfs_edges():
Notes
If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph
are searched.
The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with
modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.
See also:
dfs_edges(), dfs_preorder_nodes(), dfs_postorder_nodes()
networkx.algorithms.traversal.breadth_first_search.bfs_edges
Examples
Notes
networkx.algorithms.traversal.breadth_first_search.bfs_tree
Examples
>>> G = nx.path_graph(3)
>>> print(list(nx.bfs_tree(G,1).edges()))
[(1, 0), (1, 2)]
>>> H = nx.Graph()
>>> nx.add_path(H, [0, 1, 2, 3, 4, 5, 6])
>>> nx.add_path(H, [2, 7, 8, 9, 10])
>>> print(sorted(list(nx.bfs_tree(H, source=3, depth_limit=3).edges())))
[(1, 0), (2, 1), (2, 7), (3, 2), (3, 4), (4, 5), (5, 6), (7, 8)]
Notes
networkx.algorithms.traversal.breadth_first_search.bfs_predecessors
• source (node) – Specify starting node for breadth-first search and return edges in the com-
ponent reachable from source.
• depth_limit (int, optional(default=len(G))) – Specify the maximum search depth
Returns pred – (node, predecessors) iterator where predecessors is the list of predecessors of the
node.
Return type iterator
Examples
>>> G = nx.path_graph(3)
>>> print(dict(nx.bfs_predecessors(G, 0)))
{1: 0, 2: 1}
>>> H = nx.Graph()
>>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
>>> print(dict(nx.bfs_predecessors(H, 0)))
{1: 0, 2: 0, 3: 1, 4: 1, 5: 2, 6: 2}
>>> M = nx.Graph()
>>> nx.add_path(M, [0, 1, 2, 3, 4, 5, 6])
>>> nx.add_path(M, [2, 7, 8, 9, 10])
>>> print(sorted(nx.bfs_predecessors(M, source=1, depth_limit=3)))
[(0, 1), (2, 1), (3, 2), (4, 3), (7, 2), (8, 7)]
Notes
networkx.algorithms.traversal.breadth_first_search.bfs_successors
Examples
>>> G = nx.path_graph(3)
>>> print(dict(nx.bfs_successors(G,0)))
{0: [1], 1: [2]}
>>> H = nx.Graph()
>>> H.add_edges_from([(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (2, 6)])
(continues on next page)
Notes
networkx.algorithms.traversal.beamsearch.bfs_beam_edges
Examples
To give nodes with, for example, a higher centrality precedence during the search, set the value function to
return the centrality value of the node:
>>> G = nx.karate_club_graph()
>>> centrality = nx.eigenvector_centrality(G)
(continues on next page)
networkx.algorithms.traversal.edgedfs.edge_dfs
Examples
Notes
The goal of this function is to visit edges. It differs from the more familiar depth-first traversal of nodes, as
provided by networkx.algorithms.traversal.depth_first_search.dfs_edges(), in that
it does not stop once every node has been visited. In a directed graph with edges [(0, 1), (1, 2), (2, 1)], the edge
(2, 1) would not be visited if not for the functionality provided by this function.
See also:
dfs_edges()
networkx.algorithms.traversal.edgebfs.edge_bfs
edges. When set to ‘reverse’ every edge is traversed in the reverse direction. When set to
‘ignore’, every edge is treated as undirected. When set to ‘original’, every edge is treated as
directed. In all three cases, the yielded edge tuples add a last entry to indicate the direction
in which that edge was traversed. If orientation is None, the yielded edge has no direction
indicated. The direction is respected, but not reported.
Yields edge (directed edge) – A directed edge indicating the path taken by the breadth-first-search.
For graphs, edge is of the form (u, v) where u and v are the tail and head of the edge as
determined by the traversal. For multigraphs, edge is of the form (u, v, key), where key
is the key of the edge. When the graph is directed, then u and v are always in the order of the
actual directed edge. If orientation is not None then the edge tuple is extended to include the
direction of traversal (‘forward’ or ‘reverse’) on that edge.
Examples
Notes
The goal of this function is to visit edges. It differs from the more familiar breadth-first-search of nodes,
as provided by networkx.algorithms.traversal.breadth_first_search.bfs_edges(), in
that it does not stop once every node has been visited. In a directed graph with edges [(0, 1), (1, 2), (2, 1)], the
edge (2, 1) would not be visited if not for the functionality provided by this function.
See also:
bfs_edges(), bfs_tree(), edge_dfs()
3.55 Tree
3.55.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 A | Convention B |
+=============================+
| 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 convention “A”. 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 convention B, 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 convention B, 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
convention B, 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 convention B, this is known as a tree.
For trees and arborescences, the adjective “spanning” may be added to designate that the graph, when considered as
a forest/branching, consists of a single tree/arborescence that includes all nodes in the graph. It is true, by definition,
that every tree/arborescence is spanning with respect to the nodes that define the tree/arborescence and so, it might
seem redundant to introduce the notion of “spanning”. However, the nodes may represent a subset of nodes from a
larger graph, and it is in this context that the term “spanning” becomes a useful notion.
networkx.algorithms.tree.recognition.is_tree
is_tree(G)
Returns True if G is a tree.
A tree is a connected graph with no undirected cycles.
For directed graphs, G 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 – A boolean that is True if G is a tree.
Return type bool
Notes
In another convention, a directed tree is known as a polytree and then tree corresponds to an arborescence.
See also:
is_arborescence()
networkx.algorithms.tree.recognition.is_forest
is_forest(G)
Returns True if G is a forest.
A forest is a graph with no undirected cycles.
For directed graphs, G 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 – A boolean that is True if G is a forest.
Return type bool
Notes
In another convention, a directed forest is known as a polyforest and then forest corresponds to a branching.
See also:
is_branching()
networkx.algorithms.tree.recognition.is_arborescence
is_arborescence(G)
Returns True if G is an arborescence.
An arborescence is a directed tree with maximum in-degree equal to 1.
Parameters G (graph) – The graph to test.
Returns b – A boolean that is True if G is an arborescence.
Return type bool
Notes
networkx.algorithms.tree.recognition.is_branching
is_branching(G)
Returns True if G is a branching.
A branching is a directed forest with maximum in-degree equal to 1.
Parameters G (directed graph) – The directed graph to test.
Returns b – A boolean that is True if G is a branching.
Return type bool
Notes
networkx.algorithms.tree.branchings.branching_weight
networkx.algorithms.tree.branchings.greedy_branching
networkx.algorithms.tree.branchings.maximum_branching
networkx.algorithms.tree.branchings.minimum_branching
networkx.algorithms.tree.branchings.maximum_spanning_arborescence
networkx.algorithms.tree.branchings.minimum_spanning_arborescence
• preserve_attrs (bool) – If True, preserve the other attributes of the original graph (that are
not passed to attr)
Returns B – A minimum spanning arborescence.
Return type (multi)digraph-like
Raises NetworkXException – If the graph does not contain a minimum spanning arborescence.
networkx.algorithms.tree.branchings.Edmonds
Methods
networkx.algorithms.tree.coding.from_nested_tuple
from_nested_tuple(sequence, sensible_relabeling=False)
Returns the rooted tree corresponding to the given nested tuple.
The nested tuple representation of a tree is defined recursively. The tree with one node and no edges is rep-
resented by the empty tuple, (). A tree with k subtrees is represented by a tuple of length k in which each
element is the nested tuple representation of a subtree.
Parameters
• sequence (tuple) – A nested tuple representing a rooted tree.
• sensible_relabeling (bool) – Whether to relabel the nodes of the tree so that nodes are
labeled in increasing order according to their breadth-first search order from the root node.
Returns The tree corresponding to the given nested tuple, whose root node is node 0. If
sensible_labeling is True, nodes will be labeled in breadth-first search order starting
from the root node.
Return type NetworkX graph
Notes
This function is not the inverse of to_nested_tuple(); the only guarantee is that the rooted trees are
isomorphic.
See also:
to_nested_tuple(), from_prufer_sequence()
Examples
Sensible relabeling ensures that the nodes are labeled from the root starting at 0:
networkx.algorithms.tree.coding.to_nested_tuple
Notes
This function is not the inverse of from_nested_tuple(); the only guarantee is that the rooted trees are
isomorphic.
See also:
from_nested_tuple(), to_prufer_sequence()
Examples
>>> T = nx.Graph()
>>> T.add_edges_from([(0, 1), (0, 2), (0, 3)])
>>> T.add_edges_from([(1, 4), (1, 5)])
>>> T.add_edges_from([(3, 6), (3, 7)])
>>> root = 0
>>> nx.to_nested_tuple(T, root)
(((), ()), (), ((), ()))
Continuing the above example, if canonical_form is True, the nested tuples will be sorted:
>>> T = nx.path_graph(4)
>>> root = 0
>>> nx.to_nested_tuple(T, root)
((((),),),)
networkx.algorithms.tree.coding.from_prufer_sequence
from_prufer_sequence(sequence)
Returns the tree corresponding to the given Prüfer sequence.
A Prüfer sequence is a list of n - 2 numbers between 0 and n - 1, inclusive. The tree corresponding to a given
Prüfer sequence can be recovered by repeatedly joining a node in the sequence with a node with the smallest
potential degree according to the sequence.
Parameters sequence (list) – A Prüfer sequence, which is a list of n - 2 integers between zero and
n - 1, inclusive.
Returns The tree corresponding to the given Prüfer sequence.
Return type NetworkX graph
Notes
There is a bijection from labeled trees to Prüfer sequences. This function is the inverse of the
from_prufer_sequence() function.
Sometimes Prüfer sequences use nodes labeled from 1 to n instead of from 0 to n - 1. This function requires
nodes to be labeled in the latter form. You can use networkx.relabel_nodes() to relabel the nodes of
your tree to the appropriate format.
This implementation is from1 and has a running time of 𝑂(𝑛 log 𝑛).
1 Wang, Xiaodong, Lei Wang, and Yingjie Wu. “An optimal algorithm for Prufer codes.” Journal of Software Engineering and Applications
References
See also:
from_nested_tuple(), to_prufer_sequence()
Examples
There is a bijection between Prüfer sequences and labeled trees, so this function is the inverse of the
to_prufer_sequence() function:
>>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
>>> tree = nx.Graph(edges)
>>> sequence = nx.to_prufer_sequence(tree)
>>> sequence
[3, 3, 3, 4]
>>> tree2 = nx.from_prufer_sequence(sequence)
>>> list(tree2.edges()) == edges
True
networkx.algorithms.tree.coding.to_prufer_sequence
to_prufer_sequence(T)
Returns the Prüfer sequence of the given tree.
A Prüfer sequence is a list of n - 2 numbers between 0 and n - 1, inclusive. The tree corresponding to a given
Prüfer sequence can be recovered by repeatedly joining a node in the sequence with a node with the smallest
potential degree according to the sequence.
Parameters T (NetworkX graph) – An undirected graph object representing a tree.
Returns The Prüfer sequence of the given tree.
Return type list
Raises
• NetworkXPointlessConcept – If the number of nodes in T is less than two.
• NotATree – If T is not a tree.
• KeyError – If the set of nodes in T is not {0, . . . , n - 1}.
Notes
There is a bijection from labeled trees to Prüfer sequences. This function is the inverse of the
from_prufer_sequence() function.
Sometimes Prüfer sequences use nodes labeled from 1 to n instead of from 0 to n - 1. This function requires
nodes to be labeled in the latter form. You can use relabel_nodes() to relabel the nodes of your tree to the
appropriate format.
This implementation is from1 and has a running time of 𝑂(𝑛 log 𝑛).
See also:
to_nested_tuple(), from_prufer_sequence()
1 Wang, Xiaodong, Lei Wang, and Yingjie Wu. “An optimal algorithm for Prufer codes.” Journal of Software Engineering and Applications
2.02 (2009): 111. <https://doi.org/10.4236/jsea.2009.22016>
References
Examples
There is a bijection between Prüfer sequences and labeled trees, so this function is the inverse of the
from_prufer_sequence() function:
>>> edges = [(0, 3), (1, 3), (2, 3), (3, 4), (4, 5)]
>>> tree = nx.Graph(edges)
>>> sequence = nx.to_prufer_sequence(tree)
>>> sequence
[3, 3, 3, 4]
>>> tree2 = nx.from_prufer_sequence(sequence)
>>> list(tree2.edges()) == edges
True
3.55.4 Operations
Operations on trees.
join(rooted_trees[, label_attribute]) Returns a new rooted tree with a root node joined with
the roots of each of the given rooted trees.
networkx.algorithms.tree.operations.join
join(rooted_trees, label_attribute=None)
Returns a new rooted tree with a root node joined with the roots of each of the given rooted trees.
Parameters
• rooted_trees (list) – A list of pairs in which each left element is a NetworkX graph object
representing a tree and each right element is the root node of that tree. The nodes of these
trees will be relabeled to integers.
• label_attribute (str) – If provided, the old node labels will be stored in the new tree under
this node attribute. If not provided, the node attribute '_old' will store the original label
of the node in the rooted trees given in the input.
Returns The rooted tree whose subtrees are the given rooted trees. The new root node is la-
beled 0. Each non-root node has an attribute, as described under the keyword argument
label_attribute, that indicates the label of the original node in the input tree.
Return type NetworkX graph
Notes
Graph, edge, and node attributes are propagated from the given rooted trees to the created tree. If there are
any overlapping graph attributes, those from later trees will overwrite those from earlier trees in the tuple of
positional arguments.
Examples
Join two full balanced binary trees of height h to get a full balanced binary tree of depth h + 1:
>>> h = 4
>>> left = nx.balanced_tree(2, h)
>>> right = nx.balanced_tree(2, h)
>>> joined_tree = nx.join([(left, 0), (right, 0)])
>>> nx.is_isomorphic(joined_tree, nx.balanced_tree(2, h + 1))
True
networkx.algorithms.tree.mst.minimum_spanning_tree
Examples
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2)
>>> T = nx.minimum_spanning_tree(G)
>>> sorted(T.edges(data=True))
[(0, 1, {}), (1, 2, {}), (2, 3, {})]
Notes
For Borůvka’s algorithm, each edge must have a weight attribute, and each edge weight must be distinct.
For the other algorithms, if the graph edges do not have a weight attribute a default weight of 1 will be used.
There may be more than one tree with the same minimum or maximum weight. See networkx.tree.
recognition for more detailed definitions.
Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
networkx.algorithms.tree.mst.maximum_spanning_tree
Examples
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2)
>>> T = nx.maximum_spanning_tree(G)
>>> sorted(T.edges(data=True))
[(0, 1, {}), (0, 3, {'weight': 2}), (1, 2, {})]
Notes
For Borůvka’s algorithm, each edge must have a weight attribute, and each edge weight must be distinct.
For the other algorithms, if the graph edges do not have a weight attribute a default weight of 1 will be used.
There may be more than one tree with the same minimum or maximum weight. See networkx.tree.
recognition for more detailed definitions.
Isolated nodes with self-loops are in the tree as edgeless isolated nodes.
networkx.algorithms.tree.mst.minimum_spanning_edges
Examples
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2)
>>> mst = tree.minimum_spanning_edges(G, algorithm='kruskal', data=False)
>>> edgelist = list(mst)
>>> sorted(edgelist)
[(0, 1), (1, 2), (2, 3)]
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2)
>>> mst = tree.minimum_spanning_edges(G, algorithm='prim', data=False)
>>> edgelist = list(mst)
>>> sorted(edgelist)
[(0, 1), (1, 2), (2, 3)]
Notes
For Borůvka’s algorithm, each edge must have a weight attribute, and each edge weight must be distinct.
For the other algorithms, if the graph edges do not have a weight attribute a default weight of 1 will be used.
Modified code from David Eppstein, April 2006 http://www.ics.uci.edu/~eppstein/PADS/
networkx.algorithms.tree.mst.maximum_spanning_edges
Examples
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2)
>>> mst = tree.maximum_spanning_edges(G, algorithm='kruskal', data=False)
>>> edgelist = list(mst)
>>> sorted(edgelist)
[(0, 1), (0, 3), (1, 2)]
>>> G = nx.cycle_graph(4)
>>> G.add_edge(0, 3, weight=2) # assign weight 2 to edge 0-3
>>> mst = tree.maximum_spanning_edges(G, algorithm='prim', data=False)
>>> edgelist = list(mst)
(continues on next page)
Notes
For Borůvka’s algorithm, each edge must have a weight attribute, and each edge weight must be distinct.
For the other algorithms, if the graph edges do not have a weight attribute a default weight of 1 will be used.
Modified code from David Eppstein, April 2006 http://www.ics.uci.edu/~eppstein/PADS/
3.55.6 Exceptions
networkx.algorithms.tree.coding.NotATree
exception NotATree
Raised when a function expects a tree (that is, a connected undirected graph with no cycles) but gets a non-tree
graph as input instead.
3.56 Triads
3.56.1 networkx.algorithms.triads.triadic_census
triadic_census(G)
Determines the triadic census of a directed graph.
The triadic census is a count of how many of the 16 possible types of triads are present in a directed graph.
Parameters G (digraph) – A NetworkX DiGraph
Returns census – Dictionary with triad names as keys and number of occurrences as values.
Return type dict
Notes
This algorithm has complexity 𝑂(𝑚) where 𝑚 is the number of edges in the graph.
See also:
triad_graph()
References
3.57 Vitality
Vitality measures.
closeness_vitality(G[, node, weight, . . . ]) Returns the closeness vitality for nodes in the graph.
3.57.1 networkx.algorithms.vitality.closeness_vitality
Examples
>>> G = nx.cycle_graph(3)
>>> nx.closeness_vitality(G)
{0: 2.0, 1: 2.0, 2: 2.0}
See also:
closeness_centrality()
References
3.58.1 networkx.algorithms.voronoi.voronoi_cells
Examples
To get only the partition of the graph induced by the Voronoi cells, take the collection of all values in the returned
dictionary:
>>> G = nx.path_graph(6)
>>> center_nodes = {0, 3}
>>> cells = nx.voronoi_cells(G, center_nodes)
>>> partition = set(map(frozenset, cells.values()))
>>> sorted(map(sorted, partition))
[[0, 1], [2, 3, 4, 5]]
References
3.59.1 networkx.algorithms.wiener.wiener_index
wiener_index(G, weight=None)
Returns the Wiener index of the given graph.
The Wiener index of a graph is the sum of the shortest-path distances between each pair of reachable nodes. For
pairs of nodes in undirected graphs, only one orientation of the pair is counted.
Parameters
• G (NetworkX graph)
• weight (object) – The edge attribute to use as distance when computing shortest-path dis-
tances. This is passed directly to the networkx.shortest_path_length() func-
tion.
Returns The Wiener index of the graph G.
Return type float
Raises NetworkXError – If the graph G is not connected.
Notes
If a pair of nodes is not reachable, the distance is assumed to be infinity. This means that for graphs that are not
strongly-connected, this function returns inf.
The Wiener index is not usually defined for directed graphs, however this function uses the natural generalization
of the Wiener index to directed graphs.
Examples
The Wiener index of the (unweighted) complete graph on n nodes equals the number of pairs of the n nodes,
since each pair of nodes is at distance one:
>>> G = nx.empty_graph(2)
>>> nx.wiener_index(G)
inf
FOUR
FUNCTIONS
4.1 Graph
4.1.1 networkx.classes.function.degree
491
NetworkX Reference, Release 2.3rc1.dev20190222214247
4.1.2 networkx.classes.function.degree_histogram
degree_histogram(G)
Returns a list of the frequency of each degree value.
Parameters G (Networkx graph) – A graph
Returns hist – A list of frequencies of degrees. The degree values are the index in the list.
Return type list
Notes
Note: the bins are width one, hence len(list) can be large (Order(number_of_edges))
4.1.3 networkx.classes.function.density
density(G)
Returns the density of a graph.
The density for undirected graphs is
2𝑚
𝑑= ,
𝑛(𝑛 − 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.
4.1.4 networkx.classes.function.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
4.1.5 networkx.classes.function.create_empty_copy
create_empty_copy(G, with_data=True)
Returns a copy of the graph G with all of the edges removed.
Parameters
4.1.6 networkx.classes.function.is_directed
is_directed(G)
Return True if graph is directed.
4.1.7 networkx.classes.function.to_directed
to_directed(graph)
Returns a directed view of the graph graph.
Identical to graph.to_directed(as_view=True) Note that graph.to_directed defaults to as_view=False while
this function always provides a view.
4.1.8 networkx.classes.function.to_undirected
to_undirected(graph)
Returns an undirected view of the graph graph.
Identical to graph.to_undirected(as_view=True) Note that graph.to_undirected defaults to as_view=False
while this function always provides a view.
4.1.9 networkx.classes.function.is_empty
is_empty(G)
Returns True if G has no edges.
Parameters G (graph) – A NetworkX graph.
Returns True if G has no edges, and False otherwise.
Return type bool
Notes
An empty graph can have nodes but not edges. The empty graph with zero nodes is known as the null graph.
This is an 𝑂(𝑛) operation where n is the number of nodes in the graph.
4.1.10 networkx.classes.function.add_star
Examples
>>> G = nx.Graph()
>>> nx.add_star(G, [0, 1, 2, 3])
>>> nx.add_star(G, [10, 11, 12], weight=2)
4.1.11 networkx.classes.function.add_path
Examples
>>> G = nx.Graph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> nx.add_path(G, [10, 11, 12], weight=7)
4.1.12 networkx.classes.function.add_cycle
See also:
add_path(), add_star()
Examples
4.1.13 networkx.classes.function.subgraph
subgraph(G, nbunch)
Returns the subgraph induced on nodes in nbunch.
Parameters
• G (graph) – A NetworkX graph
• nbunch (list, iterable) – A container of nodes that will be iterated through once (thus it
should be an iterator or be iterable). Each element of the container should be a valid node
type: any hashable type except None. If nbunch is None, return all edges data in the graph.
Nodes in nbunch that are not in the graph will be (quietly) ignored.
Notes
4.1.14 networkx.classes.function.induced_subgraph
induced_subgraph(G, nbunch)
Returns a SubGraph view of G showing only nodes in nbunch.
The induced subgraph of a graph on a set of nodes N is the graph with nodes N and edges from G which have
both ends in N.
Parameters
• G (NetworkX Graph)
• nbunch (node, container of nodes or None (for all nodes))
Returns subgraph – A read-only view of the subgraph in G induced by the nodes. Changes to the
graph G will be reflected in the view.
Return type SubGraph View
Notes
To create a mutable subgraph with its own copies of nodes edges and attributes use subgraph.copy() or
Graph(subgraph)
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))
If you are going to compute subgraphs of your subgraphs you could end up with a chain of views that can be
very slow once the chain has about 15 views in it. If they are all induced subgraphs, you can short-cut the chain
by making them all subgraphs of the original graph. The graph class method G.subgraph does this when G
is a subgraph. In contrast, this function allows you to choose to build chains or not, as you wish. The returned
subgraph is a view on G.
Examples
4.1.15 networkx.classes.function.restricted_view
Notes
To create a mutable subgraph with its own copies of nodes edges and attributes use subgraph.copy() or
Graph(subgraph)
If you create a subgraph of a subgraph recursively you may end up with a chain of subgraph views. Such
chains can get quite slow for lengths near 15. To avoid long chains, try to make your subgraph based on the
original graph. We do not rule out chains programmatically so that odd cases like an edge_subgraph of a
restricted_view can be created.
Examples
4.1.16 networkx.classes.function.reverse_view
reverse_view(digraph)
Provide a reverse view of the digraph with edges reversed.
Identical to digraph.reverse(copy=False)
4.1.17 networkx.classes.function.edge_subgraph
edge_subgraph(G, edges)
Returns a view of the subgraph induced by the specified edges.
The induced subgraph contains each edge in edges and each node incident to any of those edges.
Parameters
• G (NetworkX Graph)
• edges (iterable) – An iterable of edges. Edges not present in G are ignored.
Returns subgraph – A read-only edge-induced subgraph of G. Changes to G are reflected in the
view.
Return type SubGraph View
Notes
To create a mutable subgraph with its own copies of nodes edges and attributes use subgraph.copy() or
Graph(subgraph)
If you create a subgraph of a subgraph recursively you can end up with a chain of subgraphs that becomes very
slow with about 15 nested subgraph views. Luckily the edge_subgraph filter nests nicely so you can use the
original graph as G in this function to avoid chains. We do not rule out chains programmatically so that odd
cases like an edge_subgraph of a restricted_view can be created.
Examples
4.2 Nodes
4.2.1 networkx.classes.function.nodes
nodes(G)
Returns an iterator over the graph nodes.
4.2.2 networkx.classes.function.number_of_nodes
number_of_nodes(G)
Returns the number of nodes in the graph.
4.2.3 networkx.classes.function.neighbors
neighbors(G, n)
Returns a list of nodes connected to node n.
4.2.4 networkx.classes.function.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 of neighbors
Return type iterator
4.2.5 networkx.classes.function.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.
Returns non_neighbors – Iterator of nodes in the graph that are not neighbors of the node.
Return type iterator
4.2.6 networkx.classes.function.common_neighbors
common_neighbors(G, u, v)
Returns 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 of common neighbors of u and v in the graph.
Return type iterator
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]
4.3 Edges
4.3.1 networkx.classes.function.edges
edges(G, nbunch=None)
Returns an edge view of edges incident to nodes in nbunch.
Return all edges if nbunch is unspecified or nbunch=None.
For digraphs, edges=out_edges
4.3.2 networkx.classes.function.number_of_edges
number_of_edges(G)
Returns the number of edges in the graph.
4.3.3 networkx.classes.function.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 of edges that are not in the graph.
4.4.1 networkx.classes.function.selfloop_edges
Examples
4.4.2 networkx.classes.function.number_of_selfloops
number_of_selfloops(G)
Returns the number of selfloop edges.
A selfloop edge has the same node at both ends.
Examples
4.4.3 networkx.classes.function.nodes_with_selfloops
nodes_with_selfloops(G)
Returns an iterator over nodes with self loops.
A node with a self loop has an edge with both ends adjacent to that node.
Returns nodelist – A iterator over nodes with self loops.
Return type iterator
See also:
selfloop_edges(), number_of_selfloops()
Examples
4.5 Attributes
4.5.1 networkx.classes.function.is_weighted
Examples
>>> G = nx.path_graph(4)
>>> nx.is_weighted(G)
False
>>> nx.is_weighted(G, (2, 3))
False
>>> G = nx.DiGraph()
>>> G.add_edge(1, 2, weight=1)
>>> nx.is_weighted(G)
True
4.5.2 networkx.classes.function.is_negatively_weighted
Examples
>>> G = nx.Graph()
>>> G.add_edges_from([(1, 3), (2, 4), (2, 6)])
>>> G.add_edge(1, 2, weight=4)
>>> nx.is_negatively_weighted(G, (1, 2))
False
>>> G[2][4]['weight'] = -2
>>> nx.is_negatively_weighted(G)
True
>>> G = nx.DiGraph()
>>> edges = [('0', '3', 3), ('0', '1', -5), ('1', '0', -2)]
>>> G.add_weighted_edges_from(edges)
>>> nx.is_negatively_weighted(G)
True
4.5.3 networkx.classes.function.set_node_attributes
Warning: The call order of arguments values and name switched between v1.x & v2.x.
Parameters
• G (NetworkX Graph)
• values (scalar value, dict-like) – What the node attribute should be set to. If values is not
a dictionary, then it is treated as a single attribute value that is then applied to every node in
G. This means that if you provide a mutable object, like a list, updates to that object will be
reflected in the node attribute for every node. The attribute name will be name.
If values is a dict or a dict of dict, it should be keyed by node to either an attribute value
or a dict of attribute key/value pairs used to update the node’s attributes.
• name (string (optional, default=None)) – Name of the node attribute to set if values is a
scalar.
Examples
After computing some property of the nodes of a graph, you may want to assign a node attribute to store the
value of that property for each node:
>>> G = nx.path_graph(3)
>>> bb = nx.betweenness_centrality(G)
>>> isinstance(bb, dict)
True
>>> nx.set_node_attributes(G, bb, 'betweenness')
>>> G.nodes[1]['betweenness']
1.0
If you provide a list as the second argument, updates to the list will be reflected in the node attribute for each
node:
>>> G = nx.path_graph(3)
>>> labels = []
>>> nx.set_node_attributes(G, labels, 'labels')
>>> labels.append('foo')
>>> G.nodes[0]['labels']
['foo']
>>> G.nodes[1]['labels']
['foo']
>>> G.nodes[2]['labels']
['foo']
If you provide a dictionary of dictionaries as the second argument, the outer dictionary is assumed to be keyed
by node to an inner dictionary of node attributes for that node:
>>> G = nx.path_graph(3)
>>> attrs = {0: {'attr1': 20, 'attr2': 'nothing'}, 1: {'attr2': 3}}
>>> nx.set_node_attributes(G, attrs)
>>> G.nodes[0]['attr1']
20
>>> G.nodes[0]['attr2']
'nothing'
>>> G.nodes[1]['attr2']
3
>>> G.nodes[2]
{}
4.5.4 networkx.classes.function.get_node_attributes
get_node_attributes(G, name)
Get node attributes from graph
Parameters
• G (NetworkX Graph)
• name (string) – Attribute name
Returns
Return type 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'
4.5.5 networkx.classes.function.set_edge_attributes
Warning: The call order of arguments values and name switched between v1.x & v2.x.
Parameters
• G (NetworkX Graph)
• values (scalar value, dict-like) – What the edge attribute should be set to. If values is not
a dictionary, then it is treated as a single attribute value that is then applied to every edge in
G. This means that if you provide a mutable object, like a list, updates to that object will be
reflected in the edge attribute for each edge. The attribute name will be name.
If values is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute
value or a dict of attribute key/value pairs used to update the edge’s attributes. For multi-
graphs, the edge tuples must be of the form (u, v, key), where u and v are nodes and
key is the edge key. For non-multigraphs, the keys must be tuples of the form (u, v).
• name (string (optional, default=None)) – Name of the edge attribute to set if values is a
scalar.
Examples
After computing some property of the edges of a graph, you may want to assign a edge attribute to store the
value of that property for each edge:
>>> G = nx.path_graph(3)
>>> bb = nx.edge_betweenness_centrality(G, normalized=False)
>>> nx.set_edge_attributes(G, bb, 'betweenness')
>>> G.edges[1, 2]['betweenness']
2.0
If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each
edge:
>>> labels = []
>>> nx.set_edge_attributes(G, labels, 'labels')
>>> labels.append('foo')
>>> G.edges[0, 1]['labels']
['foo']
>>> G.edges[1, 2]['labels']
['foo']
If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update
edge attributes:
>>> G = nx.path_graph(3)
>>> attrs = {(0, 1): {'attr1': 20, 'attr2': 'nothing'},
... (1, 2): {'attr2': 3}}
>>> nx.set_edge_attributes(G, attrs)
>>> G[0][1]['attr1']
20
>>> G[0][1]['attr2']
'nothing'
>>> G[1][2]['attr2']
3
4.5.6 networkx.classes.function.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()
>>> nx.add_path(G, [1, 2, 3], color='red')
>>> color = nx.get_edge_attributes(G, 'color')
>>> color[(1, 2)]
'red'
4.6.1 networkx.classes.function.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
Examples
>>> G = nx.path_graph(4)
>>> G = nx.freeze(G)
>>> try:
... G.add_edge(4, 5)
... except nx.NetworkXError as e:
... print(str(e))
Frozen graph can't be modified
Notes
To “unfreeze” a graph you must make a copy by creating a new graph object:
See also:
is_frozen()
4.6.2 networkx.classes.function.is_frozen
is_frozen(G)
Returns True if graph is frozen.
Parameters G (graph) – A NetworkX graph
See also:
freeze()
FIVE
GRAPH GENERATORS
5.1 Atlas
5.1.1 networkx.generators.atlas.graph_atlas
graph_atlas(i)
Returns graph number i from the Graph Atlas.
For more information, see graph_atlas_g().
Parameters i (int) – The index of the graph from the atlas to get. The graph at index 0 is assumed
to be the null graph.
Returns A list of Graph objects, the one at index i corresponding to the graph i in the Graph Atlas.
Return type list
See also:
graph_atlas_g()
Notes
The time required by this function increases linearly with the argument i, since it reads a large file sequentially
in order to generate the graph1 .
References
5.1.2 networkx.generators.atlas.graph_atlas_g
graph_atlas_g()
Returns the list of all graphs with up to seven nodes named in the Graph Atlas.
The graphs are listed in increasing order by
1 Ronald C. Read and Robin J. Wilson, An Atlas of Graphs. Oxford University Press, 1998.
509
NetworkX Reference, Release 2.3rc1.dev20190222214247
1. number of nodes,
2. number of edges,
3. degree sequence (for example 111223 < 112222),
4. number of automorphisms,
in that order, with three exceptions as described in the Notes section below. This causes the list to correspond
with the index of the graphs in the Graph Atlas [atlas], with the first graph, G[0], being the null graph.
Returns A list of Graph objects, the one at index i corresponding to the graph i in the Graph Atlas.
Return type list
See also:
graph_atlas()
Notes
This function may be expensive in both time and space, since it reads a large file sequentially in order to populate
the list.
Although the NetworkX atlas functions match the order of graphs given in the “Atlas of Graphs” book, there
are (at least) three errors in the ordering described in the book. The following three pairs of nodes violate the
lexicographically nondecreasing sorted degree sequence rule:
• graphs 55 and 56 with degree sequences 001111 and 000112,
• graphs 1007 and 1008 with degree sequences 3333444 and 3333336,
• graphs 1012 and 1213 with degree sequences 1244555 and 1244456.
References
5.2 Classic
>>> G = nx.complete_graph(100)
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).
balanced_tree(r, h[, create_using]) Returns the perfectly balanced r-ary tree of height h.
barbell_graph(m1, m2[, create_using]) Returns the Barbell Graph: two complete graphs con-
nected by a path.
complete_graph(n[, create_using]) Return the complete graph K_n with n nodes.
complete_multipartite_graph(*subset_sizes) Returns the complete multipartite graph with the speci-
fied subset sizes.
circular_ladder_graph(n[, create_using]) Returns the circular ladder graph 𝐶𝐿𝑛 of length n.
circulant_graph(n, offsets[, create_using]) Generates the circulant graph 𝐶𝑖𝑛 (𝑥1 , 𝑥2 , ..., 𝑥𝑚 ) with
𝑛 vertices.
Continued on next page
5.2.1 networkx.generators.classic.balanced_tree
balanced_tree(r, h, create_using=None)
Returns the perfectly balanced r-ary tree of height h.
Parameters
• r (int) – Branching factor of the tree; each node will have r children.
• h (int) – Height of the tree.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns G – A balanced r-ary tree of height h.
Return type NetworkX graph
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 integers, starting from zero.
A balanced tree is also known as a complete r-ary tree.
5.2.2 networkx.generators.classic.barbell_graph
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 e-text on Random Walks on Graphs.
5.2.3 networkx.generators.classic.complete_graph
complete_graph(n, create_using=None)
Return the complete graph K_n with n nodes.
Parameters
• n (int or iterable container of nodes) – If n is an integer, nodes are from range(n). If n is a
container of nodes, those nodes appear in the graph.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Examples
>>> G = nx.complete_graph(9)
>>> len(G)
9
>>> G.size()
36
>>> G = nx.complete_graph(range(11, 14))
>>> list(G.nodes())
[11, 12, 13]
>>> G = nx.complete_graph(4, nx.DiGraph())
>>> G.is_directed()
True
5.2.4 networkx.generators.classic.complete_multipartite_graph
complete_multipartite_graph(*subset_sizes)
Returns the complete multipartite graph with the specified subset sizes.
Parameters subset_sizes (tuple of integers or tuple of node iterables) – The arguments can either
all be integer number of nodes or they can all be iterables of nodes. If integers, they represent
the number of vertices in each subset of the multipartite graph. If iterables, each is used to create
the nodes for that subset. The length of subset_sizes is the number of subsets.
Returns
G – Returns the complete multipartite graph with the specified subsets.
For each node, the node attribute ‘subset’ is an integer indicating which subset contains the node.
Return type NetworkX Graph
Examples
Creating a complete tripartite graph, with subsets of one, two, and three vertices, respectively.
Notes
5.2.5 networkx.generators.classic.circular_ladder_graph
circular_ladder_graph(n, create_using=None)
Returns the circular ladder graph 𝐶𝐿𝑛 of length 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
5.2.6 networkx.generators.classic.circulant_graph
Examples
Many well-known graph families are subfamilies of the circulant graphs; for example, to generate the cycle
graph on n points, we connect every vertex to every other at offset plus or minus one. For n = 10,
Similarly, we can generate the complete graph on 5 points with the set of offsets [1, 2]:
5.2.7 networkx.generators.classic.cycle_graph
cycle_graph(n, create_using=None)
Returns the cycle graph 𝐶𝑛 of cyclically connected nodes.
𝐶𝑛 is a path with its two end-nodes connected.
Parameters
• n (int or iterable container of nodes) – If n is an integer, nodes are from range(n). If n is
a container of nodes, those nodes appear in the graph.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Notes
5.2.8 networkx.generators.classic.dorogovtsev_goltsev_mendes_graph
dorogovtsev_goltsev_mendes_graph(n, create_using=None)
Returns the hierarchically constructed Dorogovtsev-Goltsev-Mendes graph.
n is the generation. See: arXiv:/cond-mat/0112143 by Dorogovtsev, Goltsev and Mendes.
5.2.9 networkx.generators.classic.empty_graph
Examples
>>> G = nx.empty_graph(10)
>>> G.number_of_nodes()
10
>>> G.number_of_edges()
0
>>> G = nx.empty_graph("ABC")
>>> G.number_of_nodes()
3
>>> sorted(G)
['A', 'B', 'C']
Notes
The variable create_using should be a Graph Constructor or a “graph”-like object. Constructors, e.g. nx.
Graph or nx.MultiGraph will be used to create the returned graph. “graph”-like objects will be cleared
(nodes and edges will be removed) and refitted as an empty “graph” with nodes specified in n. 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 three main uses: Firstly, the variable create_using can be used to create an empty
digraph, multigraph, etc. For example,
>>> n = 10
>>> G = nx.empty_graph(n, create_using=nx.DiGraph)
5.2.10 networkx.generators.classic.full_rary_tree
full_rary_tree(r, n, create_using=None)
Creates a full r-ary tree of n vertices.
Sometimes called a k-ary, n-ary, or m-ary tree. “. . . all non-leaf vertices have exactly r children and all levels
are full except for some rightmost position of the bottom level (if a leaf at the bottom level is missing, then so
are all of the leaves to its right.”1
Parameters
• r (int) – branching factor of the tree
• n (int) – Number of nodes in the tree
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns G – An r-ary tree with n nodes
Return type networkx Graph
References
5.2.11 networkx.generators.classic.ladder_graph
ladder_graph(n, create_using=None)
Returns the Ladder graph of length n.
This is two paths of n nodes, with each pair connected by a single edge.
Node labels are the integers 0 to 2*n - 1.
5.2.12 networkx.generators.classic.lollipop_graph
lollipop_graph(m, n, create_using=None)
Returns the Lollipop Graph; K_m connected to P_n.
This is the Barbell Graph without the right barbell.
Parameters
1 An introduction to data structures and algorithms, James Andrew Storer, Birkhauser Boston 2001, (page 225).
• m, n (int or iterable container of nodes (default = 0)) – If an integer, nodes are from
range(m) and range(m,m+n). If a container, the entries are the coordinate of the node.
The nodes for m appear in the complete graph 𝐾𝑚 and the nodes for n appear in the path
𝑃𝑛
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Notes
The 2 subgraphs are joined via an edge (m-1, m). If n=0, this is merely a complete graph.
(This graph is an extremal example in David Aldous and Jim Fill’s etext on Random Walks on Graphs.)
5.2.13 networkx.generators.classic.null_graph
null_graph(create_using=None)
Returns the Null graph with no nodes or edges.
See empty_graph for the use of create_using.
5.2.14 networkx.generators.classic.path_graph
path_graph(n, create_using=None)
Returns the Path graph P_n of linearly connected nodes.
Parameters
• n (int or iterable) – If an integer, node labels are 0 to n with center 0. If an iterable of nodes,
the center is the first.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
5.2.15 networkx.generators.classic.star_graph
star_graph(n, create_using=None)
Return the star graph
The star graph consists of one center node connected to n outer nodes.
Parameters
• n (int or iterable) – If an integer, node labels are 0 to n with center 0. If an iterable of nodes,
the center is the first.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Notes
The graph has n+1 nodes for integer n. So star_graph(3) is the same as star_graph(range(4)).
5.2.16 networkx.generators.classic.trivial_graph
trivial_graph(create_using=None)
Return the Trivial graph with one node (with label 0) and no edges.
5.2.17 networkx.generators.classic.turan_graph
turan_graph(n, r)
Return the Turan Graph
The Turan Graph is a complete multipartite graph on 𝑛 vertices with 𝑟 disjoint subsets. It is the graph with the
edges for any graph with 𝑛 vertices and 𝑟 disjoint subsets.
Given 𝑛 and 𝑟, we generate a complete multipartite graph with 𝑟 − (𝑛 mod 𝑟) partitions of size 𝑛/𝑟, rounded
down, and 𝑛 mod 𝑟 partitions of size 𝑛/𝑟 + 1, rounded down.
Parameters
• n (int) – The number of vertices.
• r (int) – The number of partitions. Must be less than or equal to n.
Notes
Must satisfy 1 <= 𝑟 <= 𝑛. The graph has (𝑟 − 1)(𝑛2 )/(2𝑟) edges, rounded down.
5.2.18 networkx.generators.classic.wheel_graph
wheel_graph(n, create_using=None)
Return the wheel graph
The wheel graph consists of a hub node connected to a cycle of (n-1) nodes.
Parameters
• n (int or iterable) – If an integer, node labels are 0 to n with center 0. If an iterable of nodes,
the center is the first.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
• Node labels are the integers 0 to n - 1.
5.3 Expanders
5.3.1 networkx.generators.expanders.margulis_gabber_galil_graph
margulis_gabber_galil_graph(n, create_using=None)
Returns the Margulis-Gabber-Galil undirected MultiGraph on n^2 nodes.
The undirected MultiGraph is regular with degree 8. Nodes are integer pairs. The second-largest eigenvalue of
the adjacency matrix of the graph is at most 5 sqrt{2}, regardless of n.
Parameters
• n (int) – Determines the number of nodes in the graph: n^2.
• create_using (NetworkX graph constructor, optional (default MultiGraph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns G – The constructed undirected multigraph.
Return type graph
Raises NetworkXError – If the graph is directed or not a multigraph.
5.3.2 networkx.generators.expanders.chordal_cycle_graph
chordal_cycle_graph(p, create_using=None)
Returns the chordal cycle graph on p nodes.
The returned graph is a cycle graph on p nodes with chords joining each vertex x to its inverse modulo p. This
graph is a (mildly explicit) 3-regular expander1 .
p must be a prime number.
Parameters
• p (a prime number) – The number of vertices in the graph. This also indicates where the
chordal edges in the cycle will be created.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns G – The constructed undirected multigraph.
Return type graph
Raises NetworkXError – If create_using indicates directed or not a multigraph.
References
5.4 Lattice
1 Theorem 4.4.2 in A. Lubotzky. “Discrete groups, expanding graphs and invariant measures”, volume 125 of Progress in Mathematics.
5.4.1 networkx.generators.lattice.grid_2d_graph
5.4.2 networkx.generators.lattice.grid_graph
grid_graph(dim, periodic=False)
Returns the n-dimensional grid graph.
The dimension n is the length of the list dim and the size in each dimension is the value of the corresponding
list element.
Parameters
• dim (list or tuple of numbers or iterables of nodes) – ‘dim’ is a tuple or list with, for each
dimension, either a number that is the size of that dimension or an iterable of nodes for that
dimension. The dimension of the grid_graph is the length of dim.
• periodic (bool) – If periodic is True the nodes on the grid boundaries are joined to
the corresponding nodes on the opposite grid boundaries.
Returns The (possibly periodic) grid graph of the specified dimensions.
Return type NetworkX graph
Examples
5.4.3 networkx.generators.lattice.hexagonal_lattice_graph
5.4.4 networkx.generators.lattice.hypercube_graph
hypercube_graph(n)
Returns the n-dimensional hypercube graph.
The nodes are the integers between 0 and 2 ** n - 1, inclusive.
For more information on the hypercube graph, see the Wikipedia article Hypercube graph.
Parameters n (int) – The dimension of the hypercube. The number of nodes in the graph will be 2
** n.
Returns The hypercube graph of dimension n.
5.4.5 networkx.generators.lattice.triangular_lattice_graph
5.5 Small
Various small and named graphs, together with some compact generators.
5.5.1 networkx.generators.small.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]]])
5.5.2 networkx.generators.small.LCF_graph
n (number of nodes) The starting graph is the n-cycle with nodes 0,. . . ,n-1. (The null graph is returned if n <
0.)
shift_list = [s1,s2,..,sk], a list of integer shifts mod n,
repeats integer specifying the number of times that shifts in shift_list are successively applied to each v_current
in the n-cycle to generate an edge between v_current and v_current+shift mod n.
For v1 cycling through the n-cycle a total of k*repeats with shift cycling through shiftlist repeats times connect
v1 with v1+shift mod n
The utility graph 𝐾3,3
5.5.3 networkx.generators.small.bull_graph
bull_graph(create_using=None)
Returns the Bull graph.
5.5.4 networkx.generators.small.chvatal_graph
chvatal_graph(create_using=None)
Returns the Chvátal graph.
5.5.5 networkx.generators.small.cubical_graph
cubical_graph(create_using=None)
Returns the 3-regular Platonic Cubical graph.
5.5.6 networkx.generators.small.desargues_graph
desargues_graph(create_using=None)
Return the Desargues graph.
5.5.7 networkx.generators.small.diamond_graph
diamond_graph(create_using=None)
Returns the Diamond graph.
5.5.8 networkx.generators.small.dodecahedral_graph
dodecahedral_graph(create_using=None)
Return the Platonic Dodecahedral graph.
5.5.9 networkx.generators.small.frucht_graph
frucht_graph(create_using=None)
Returns the Frucht Graph.
The Frucht Graph is the smallest cubical graph whose automorphism group consists only of the identity element.
5.5.10 networkx.generators.small.heawood_graph
heawood_graph(create_using=None)
Return the Heawood graph, a (3,6) cage.
5.5.11 networkx.generators.small.hoffman_singleton_graph
hoffman_singleton_graph()
Return the Hoffman-Singleton Graph.
5.5.12 networkx.generators.small.house_graph
house_graph(create_using=None)
Returns the House graph (square with triangle on top).
5.5.13 networkx.generators.small.house_x_graph
house_x_graph(create_using=None)
Returns the House graph with a cross inside the house square.
5.5.14 networkx.generators.small.icosahedral_graph
icosahedral_graph(create_using=None)
Returns the Platonic Icosahedral graph.
5.5.15 networkx.generators.small.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.
5.5.16 networkx.generators.small.moebius_kantor_graph
moebius_kantor_graph(create_using=None)
Returns the Moebius-Kantor graph.
5.5.17 networkx.generators.small.octahedral_graph
octahedral_graph(create_using=None)
Returns the Platonic Octahedral graph.
5.5.18 networkx.generators.small.pappus_graph
pappus_graph()
Return the Pappus graph.
5.5.19 networkx.generators.small.petersen_graph
petersen_graph(create_using=None)
Returns the Petersen graph.
5.5.20 networkx.generators.small.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
5.5.21 networkx.generators.small.tetrahedral_graph
tetrahedral_graph(create_using=None)
Return the 3-regular Platonic Tetrahedral graph.
5.5.22 networkx.generators.small.truncated_cube_graph
truncated_cube_graph(create_using=None)
Returns the skeleton of the truncated cube.
5.5.23 networkx.generators.small.truncated_tetrahedron_graph
truncated_tetrahedron_graph(create_using=None)
Returns the skeleton of the truncated Platonic tetrahedron.
5.5.24 networkx.generators.small.tutte_graph
tutte_graph(create_using=None)
Returns the Tutte graph.
fast_gnp_random_graph(n, p[, seed, directed]) Returns a 𝐺𝑛,𝑝 random graph, also known as an Erdős-
Rényi graph or a binomial graph.
gnp_random_graph(n, p[, seed, directed]) Returns a 𝐺𝑛,𝑝 random graph, also known as an Erdős-
Rényi graph or a binomial graph.
dense_gnm_random_graph(n, m[, seed]) Returns a 𝐺𝑛,𝑚 random graph.
gnm_random_graph(n, m[, seed, directed]) Returns a 𝐺𝑛,𝑚 random graph.
erdos_renyi_graph(n, p[, seed, directed]) Returns a 𝐺𝑛,𝑝 random graph, also known as an Erdős-
Rényi graph or a binomial graph.
binomial_graph(n, p[, seed, directed]) Returns a 𝐺𝑛,𝑝 random graph, also known as an Erdős-
Rényi graph or a binomial graph.
newman_watts_strogatz_graph(n, k, p[, seed]) Returns a Newman–Watts–Strogatz small-world graph.
watts_strogatz_graph(n, k, p[, seed]) Returns a Watts–Strogatz small-world graph.
connected_watts_strogatz_graph(n, k, p[, Returns a connected Watts–Strogatz small-world graph.
. . . ])
random_regular_graph(d, n[, seed]) Returns a random 𝑑-regular graph on 𝑛 nodes.
barabasi_albert_graph(n, m[, seed]) Returns a random graph according to the
Barabási–Albert preferential attachment model.
dual_barabasi_albert_graph(n, m1, m2, p[, Returns a random graph according to the dual
seed]) Barabási–Albert preferential attachment model.
extended_barabasi_albert_graph(n, m, p, Returns an extended Barabási–Albert model graph.
q[, . . . ])
powerlaw_cluster_graph(n, m, p[, seed]) Holme and Kim algorithm for growing graphs with
powerlaw degree distribution and approximate average
clustering.
random_kernel_graph(n, kernel_integral[, . . . ]) Returns an random graph based on the specified kernel.
random_lobster(n, p1, p2[, seed]) Returns a random lobster graph.
random_shell_graph(constructor[, seed]) Returns a random shell graph for the constructor given.
random_powerlaw_tree(n[, gamma, seed, tries]) Returns a tree with a power law degree distribution.
random_powerlaw_tree_sequence(n[, gamma, Returns a degree sequence for a tree with a power law
. . . ]) distribution.
random_kernel_graph(n, kernel_integral[, . . . ]) Returns an random graph based on the specified kernel.
5.6.1 networkx.generators.random_graphs.fast_gnp_random_graph
Notes
The 𝐺𝑛,𝑝 graph algorithm chooses each of the [𝑛(𝑛 − 1)]/2 (undirected) or 𝑛(𝑛 − 1) (directed) possible edges
with probability 𝑝.
This algorithm1 runs in 𝑂(𝑛 + 𝑚) time, where m is the expected number of edges, which equals 𝑝𝑛(𝑛 − 1)/2.
This should be faster than gnp_random_graph() when 𝑝 is small and the expected number of edges is small
(that is, the graph is sparse).
See also:
gnp_random_graph()
References
5.6.2 networkx.generators.random_graphs.gnp_random_graph
Notes
This algorithm2 runs in 𝑂(𝑛2 ) time. For sparse graphs (that is, for small values of 𝑝),
fast_gnp_random_graph() is a faster algorithm.
References
5.6.3 networkx.generators.random_graphs.dense_gnm_random_graph
dense_gnm_random_graph(n, m, seed=None)
Returns a 𝐺𝑛,𝑚 random graph.
In the 𝐺𝑛,𝑚 model, a graph is chosen uniformly at random from the set of all graphs with 𝑛 nodes and 𝑚 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.
1 Vladimir Batagelj and Ulrik Brandes, “Efficient generation of large random networks”, Phys. Rev. E, 71, 036113, 2005.
2
Notes
Algorithm by Keith M. Briggs Mar 31, 2006. Inspired by Knuth’s Algorithm S (Selection sampling technique),
in section 3.4.2 of1 .
References
5.6.4 networkx.generators.random_graphs.gnm_random_graph
5.6.5 networkx.generators.random_graphs.erdos_renyi_graph
See also:
fast_gnp_random_graph()
Notes
This algorithm2 runs in 𝑂(𝑛2 ) time. For sparse graphs (that is, for small values of 𝑝),
fast_gnp_random_graph() is a faster algorithm.
References
5.6.6 networkx.generators.random_graphs.binomial_graph
Notes
This algorithm2 runs in 𝑂(𝑛2 ) time. For sparse graphs (that is, for small values of 𝑝),
fast_gnp_random_graph() is a faster algorithm.
References
5.6.7 networkx.generators.random_graphs.newman_watts_strogatz_graph
newman_watts_strogatz_graph(n, k, p, seed=None)
Returns a Newman–Watts–Strogatz small-world graph.
Parameters
• n (int) – The number of nodes.
• k (int) – Each node is joined with its k nearest neighbors in a ring topology.
2
Notes
First create a ring over 𝑛 nodes1 . Then each node in the ring is connected with its 𝑘 nearest neighbors (or 𝑘 − 1
neighbors if 𝑘 is odd). Then shortcuts are created by adding new edges as follows: for each edge (𝑢, 𝑣) in the
underlying “𝑛-ring with 𝑘 nearest neighbors” with probability 𝑝 add a new edge (𝑢, 𝑤) with randomly-chosen
existing node 𝑤. In contrast with watts_strogatz_graph(), no edges are removed.
See also:
watts_strogatz_graph()
References
5.6.8 networkx.generators.random_graphs.watts_strogatz_graph
watts_strogatz_graph(n, k, p, seed=None)
Returns a Watts–Strogatz small-world graph.
Parameters
• n (int) – The number of nodes
• k (int) – Each node is joined with its k nearest neighbors in a ring topology.
• p (float) – The probability of rewiring each edge
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
See also:
newman_watts_strogatz_graph(), connected_watts_strogatz_graph()
Notes
First create a ring over 𝑛 nodes1 . Then each node in the ring is joined to its 𝑘 nearest neighbors (or 𝑘 − 1
neighbors if 𝑘 is odd). Then shortcuts are created by replacing some edges as follows: for each edge (𝑢, 𝑣)
in the underlying “𝑛-ring with 𝑘 nearest neighbors” with probability 𝑝 replace it with a new edge (𝑢, 𝑤) with
uniformly random choice of existing node 𝑤.
In contrast with newman_watts_strogatz_graph(), the random rewiring does not in-
crease the number of edges. The rewired graph is not guaranteed to be connected as in
connected_watts_strogatz_graph().
1 M. E. J. Newman and D. J. Watts, Renormalization group analysis of the small-world network model, Physics Letters A, 263, 341, 1999.
https://doi.org/10.1016/S0375-9601(99)00757-4
1 Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp. 440–442, 1998.
References
5.6.9 networkx.generators.random_graphs.connected_watts_strogatz_graph
Notes
First create a ring over 𝑛 nodes1 . Then each node in the ring is joined to its 𝑘 nearest neighbors (or 𝑘 − 1
neighbors if 𝑘 is odd). Then shortcuts are created by replacing some edges as follows: for each edge (𝑢, 𝑣)
in the underlying “𝑛-ring with 𝑘 nearest neighbors” with probability 𝑝 replace it with a new edge (𝑢, 𝑤) with
uniformly random choice of existing node 𝑤. The entire process is repeated until a connected graph results.
See also:
newman_watts_strogatz_graph(), watts_strogatz_graph()
References
5.6.10 networkx.generators.random_graphs.random_regular_graph
random_regular_graph(d, n, seed=None)
Returns a random 𝑑-regular graph on 𝑛 nodes.
The resulting graph has no self-loops or parallel edges.
Parameters
• d (int) – The degree of each node.
• n (integer) – The number of nodes. The value of 𝑛 × 𝑑 must be even.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
1 Duncan J. Watts and Steven H. Strogatz, Collective dynamics of small-world networks, Nature, 393, pp. 440–442, 1998.
Notes
References
5.6.11 networkx.generators.random_graphs.barabasi_albert_graph
barabasi_albert_graph(n, m, seed=None)
Returns a random graph according to the Barabási–Albert preferential attachment model.
A graph of 𝑛 nodes is grown by attaching new nodes each with 𝑚 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 (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns G
Return type Graph
Raises NetworkXError – If m does not satisfy 1 <= m < n.
References
5.6.12 networkx.generators.random_graphs.dual_barabasi_albert_graph
References
5.6.13 networkx.generators.random_graphs.extended_barabasi_albert_graph
extended_barabasi_albert_graph(n, m, p, q, seed=None)
Returns an extended Barabási–Albert model graph.
An extended Barabási–Albert model graph is a random graph constructed using preferential attachment. The
extended model allows new edges, rewired edges or new nodes. Based on the probabilities 𝑝 and 𝑞 with 𝑝+𝑞 < 1,
the growing behavior of the graph is determined as:
1) With 𝑝 probability, 𝑚 new edges are added to the graph, starting from randomly chosen existing nodes and
attached preferentially at the other end.
2) With 𝑞 probability, 𝑚 existing edges are rewired by randomly choosing an edge and rewiring one end to a
preferentially chosen node.
3) With (1 − 𝑝 − 𝑞) probability, 𝑚 new nodes are added to the graph with edges attached preferentially.
When 𝑝 = 𝑞 = 0, the model behaves just like the Barabási–Alber mo
Parameters
• n (int) – Number of nodes
• m (int) – Number of edges with which a new node attaches to existing nodes
• p (float) – Probability value for adding an edge between existing nodes. p + q < 1
• q (float) – Probability value of rewiring of existing edges. p + q < 1
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns G
Return type Graph
Raises NetworkXError – If m does not satisfy 1 <= m < n or 1 >= p + q
References
5.6.14 networkx.generators.random_graphs.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
Notes
The average clustering has a hard time getting above a certain cutoff that depends on m. This cutoff is often
quite low. The transitivity (fraction of triangles to possible triangles) seems to decrease with network size.
It is essentially the Barabási–Albert (BA) 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 BA 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 BA model.
Raises NetworkXError – If m does not satisfy 1 <= m <= n or p does not satisfy 0 <= p
<= 1.
References
5.6.15 networkx.generators.random_graphs.random_kernel_graph
Notes
The kernel is specified through its definite integral which must be provided as one of the arguments. If the
integral and root of the kernel integral can be found in 𝑂(1) time then this algorithm runs in time 𝑂(𝑛 + 𝑚)
where m is the expected number of edges2 .
The nodes are set to integers from 0 to 𝑛 − 1.
1 Bollobás, Béla, Janson, S. and Riordan, O. “The phase transition in inhomogeneous random graphs”, Random Structures Algorithms, 31,
3–122, 2007.
2 Hagberg A, Lemons N (2015), “Fast Generation of Sparse Random Kernel Graphs”. PLoS ONE 10(9): e0135177, 2015.
doi:10.1371/journal.pone.0135177
Examples
Generate an Erdős–Rényi random graph 𝐺(𝑛, 𝑐/𝑛), with kernel 𝜅(𝑥, 𝑦) = 𝑐 where 𝑐 is the mean expected
degree.
>>> def integral(u, w, z):
... return c * (z - w)
>>> def root(u, w, r):
... return r / c + w
>>> c = 1
>>> graph = nx.random_kernel_graph(1000, integral, root)
See also:
gnp_random_graph(), expected_degree_graph()
References
5.6.16 networkx.generators.random_graphs.random_lobster
5.6.17 networkx.generators.random_graphs.random_shell_graph
random_shell_graph(constructor, seed=None)
Returns a random shell graph for the constructor given.
Parameters
• constructor (list of three-tuples) – Represents the parameters for a shell, starting at the
center shell. Each element of the list must be of the form (n, m, d), where n is the
number of nodes in the shell, m is the number of edges in the shell, and d is the ratio of
inter-shell (next) edges to intra-shell edges. If d is zero, there will be no intra-shell edges,
and if d is one there will be all possible intra-shell edges.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Examples
5.6.18 networkx.generators.random_graphs.random_powerlaw_tree
Notes
A trial power law degree sequence is chosen and then elements are swapped with new elements from a powerlaw
distribution until the sequence makes a tree (by checking, for example, that the number of edges is one smaller
than the number of nodes).
5.6.19 networkx.generators.random_graphs.random_powerlaw_tree_sequence
Notes
A trial power law degree sequence is chosen and then elements are swapped with new elements from a power
law distribution until the sequence makes a tree (by checking, for example, that the number of edges is one
smaller than the number of nodes).
5.7.1 networkx.generators.duplication.duplication_divergence_graph
duplication_divergence_graph(n, p, seed=None)
Returns an undirected graph using the duplication-divergence model.
A graph of n nodes is created by duplicating the initial nodes and retaining edges incident to the original nodes
with a retention probability p.
Parameters
• n (int) – The desired number of nodes in the graph.
• p (float) – The probability for retaining the edge of the replicated node.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns G
Return type Graph
Raises NetworkXError – If p is not a valid probability. If n is less than 2.
Notes
References
5.7.2 networkx.generators.duplication.partial_duplication_graph
partial_duplication_graph(N, n, p, q, seed=None)
Returns a random graph using the partial duplication model.
Parameters
• N (int) – The total number of nodes in the final graph.
• n (int) – The number of nodes in the initial clique.
• p (float) – The probability of joining each neighbor of a node to the duplicate node. Must
be a number in the between zero and one, inclusive.
• q (float) – The probability of joining the source node to the duplicate node. Must be a
number in the between zero and one, inclusive.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Notes
A graph of nodes is grown by creating a fully connected graph of size n. The following procedure is then
repeated until a total of N nodes have been reached.
1. A random node, u, is picked and a new node, v, is created.
2. For each neighbor of u an edge from the neighbor to v is created with probability p.
3. An edge from u to v is created with probability q.
This algorithm appears in [1].
This implementation allows the possibility of generating disconnected graphs.
References
5.8.1 networkx.generators.degree_seq.configuration_model
Raises NetworkXError – If the degree sequence does not have an even sum.
See also:
is_graphical()
Notes
As described by Newman1 .
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 degree sequence does not have an even
sum.
This configuration model 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.
The density of self-loops and parallel edges tends to decrease as the number of nodes increases. However,
typically the number of self-loops will approach a Poisson distribution with a nonzero mean, and similarly for
the number of parallel edges. Consider a node with k stubs. The probability of being joined to another stub of
the same node is basically (k - 1) / N, where k is the degree and N is the number of nodes. So the probability of
a self-loop scales like c / N for some constant c. As N grows, this means we expect c self-loops. Similarly for
parallel edges.
References
Examples
You can create a degree sequence following a particular distribution by using the one of the distribution functions
in random_sequence (or one of your own). For example, to create an undirected multigraph on one hundred
nodes with degree sequence chosen from the power law distribution:
The returned graph is a multigraph, which may have parallel edges. To remove any parallel edges from the
returned graph:
>>> G = nx.Graph(G)
>>> G.remove_edges_from(nx.selfloop_edges(G))
1 M.E.J. Newman, “The structure and function of complex networks”, SIAM REVIEW 45-2, pp 167-256, 2003.
5.8.2 networkx.generators.degree_seq.directed_configuration_model
Notes
References
Examples
One can modify the in- and out-degree sequences from an existing directed graph in order to create a new
directed graph. For example, here we modify the directed path graph:
>>> D = nx.DiGraph([(0, 1), (1, 2), (2, 3)])
>>> din = list(d for n, d in D.in_degree())
>>> dout = list(d for n, d in D.out_degree())
>>> din.append(1)
(continues on next page)
1 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)
The returned graph is a directed multigraph, which may have parallel edges. To remove any parallel edges from
the returned graph:
>>> D = nx.DiGraph(D)
>>> D.remove_edges_from(nx.selfloop_edges(D))
5.8.3 networkx.generators.degree_seq.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 (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns
Return type Graph
Examples
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 in1 includes the possibility of self-loop edges. Set selfloops=False to produce a graph without self
loops.
1 Fan Chung and L. Lu, Connected components in random graphs with given expected degree sequences, Ann. Combinatorics, 6, pp. 125-145,
2002.
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
5.8.4 networkx.generators.degree_seq.havel_hakimi_graph
havel_hakimi_graph(deg_sequence, create_using=None)
Returns 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 (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated. 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 Hakimi1 and was generalized by Kleitman and Wang2 .
References
5.8.5 networkx.generators.degree_seq.directed_havel_hakimi_graph
Notes
References
5.8.6 networkx.generators.degree_seq.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
5.8.7 networkx.generators.degree_seq.random_degree_sequence_graph
See also:
is_graphical(), configuration_model()
Notes
References
Examples
5.9.1 networkx.generators.random_clustered.random_clustered_graph
Raises NetworkXError – If the independent edge degree sequence sum is not even or the triangle
degree sequence sum is not divisible by 3.
Notes
References
Examples
>>> deg = [(1, 0), (1, 0), (1, 0), (2, 0), (1, 0), (2, 1), (0, 1), (0, 1)]
>>> G = nx.random_clustered_graph(deg)
>>> G = nx.Graph(G)
>>> G.remove_edges_from(nx.selfloop_edges(G))
5.10 Directed
Generators for some directed graphs, including growing network (GN) graphs and scale-free graphs.
gn_graph(n[, kernel, create_using, seed]) Returns the growing network (GN) digraph with n
nodes.
gnr_graph(n, p[, create_using, seed]) Returns the growing network with redirection (GNR)
digraph with n nodes and redirection probability p.
gnc_graph(n[, create_using, seed]) Returns the growing network with copying (GNC) di-
graph with n nodes.
random_k_out_graph(n, k, alpha[, . . . ]) Returns a random k-out graph with preferential attach-
ment.
scale_free_graph(n[, alpha, beta, gamma, . . . ]) Returns a scale-free directed graph.
1 Joel C. Miller. “Percolation and epidemics in random clustered networks”. In: Physical review. E, Statistical, nonlinear, and soft matter
5.10.1 networkx.generators.directed.gn_graph
Examples
References
5.10.2 networkx.generators.directed.gnr_graph
Examples
References
5.10.3 networkx.generators.directed.gnc_graph
References
5.10.4 networkx.generators.directed.random_k_out_graph
Notes
The returned multidigraph may not be strongly connected, or even weakly connected.
References
[1]: Peterson, Nicholas R., and Boris Pittel. “Distance between two random k-out digraphs, with and without
preferential attachment.” arXiv preprint arXiv:1311.5961 (2013). <https://arxiv.org/abs/1311.5961>
5.10.5 networkx.generators.directed.scale_free_graph
Examples
>>> G = nx.scale_free_graph(100)
Notes
References
5.11 Geometric
random_geometric_graph(n, radius[, dim, . . . ]) Returns a random geometric graph in the unit cube of
dimensions dim.
soft_random_geometric_graph(n, radius[, Returns a soft random geometric graph in the unit cube.
. . . ])
geographical_threshold_graph(n, theta[, Returns a geographical threshold graph.
. . . ])
waxman_graph(n[, beta, alpha, L, domain, . . . ]) Returns a Waxman random graph.
navigable_small_world_graph(n[, p, q, r, Returns a navigable small-world graph.
. . . ])
thresholded_random_geometric_graph(n, Returns a thresholded random geometric graph in the
. . . [, . . . ]) unit cube.
5.11.1 networkx.generators.geometric.random_geometric_graph
Examples
Create a random geometric graph on twenty nodes where nodes are joined by an edge if their distance is at most
0.1:
Notes
References
5.11.2 networkx.generators.geometric.soft_random_geometric_graph
Examples
Default Graph:
G = nx.soft_random_geometric_graph(50, 0.2)
Custom Graph:
Create a soft random geometric graph on 100 uniformly distributed nodes where nodes are joined by an edge
with probability computed from an exponential distribution with rate parameter 𝜆 = 1 if their Euclidean distance
is at most 0.2.
Notes
References
5.11.3 networkx.generators.geometric.geographical_threshold_graph
The geographical threshold graph model places 𝑛 nodes uniformly at random in a rectangular domain. Each
node 𝑢 is assigned a weight 𝑤𝑢 . Two nodes 𝑢 and 𝑣 are joined by an edge if
(𝑤𝑢 + 𝑤𝑣 )ℎ(𝑟) ≥ 𝜃
where r is the distance between u and v, h(r) is a probability of connection as a function of r, and 𝜃 as the
threshold parameter. h(r) corresponds to the p_dist parameter.
Parameters
• n (int or iterable) – Number of nodes or iterable of nodes
• theta (float) – Threshold value
• dim (int, optional) – Dimension of graph
• pos (dict) – Node positions as a dictionary of tuples keyed by node.
• weight (dict) – Node weights as a dictionary of numbers keyed by node.
• metric (function) – A metric on vectors of numbers (represented as lists or tuples). This
must be a function that accepts two lists (or tuples) as input and yields a number as output.
The function must also satisfy the four requirements of a metric. Specifically, if 𝑑 is the
function and 𝑥, 𝑦, and 𝑧 are vectors in the graph, then 𝑑 must satisfy
1. 𝑑(𝑥, 𝑦) ≥ 0,
2. 𝑑(𝑥, 𝑦) = 0 if and only if 𝑥 = 𝑦,
3. 𝑑(𝑥, 𝑦) = 𝑑(𝑦, 𝑥),
4. 𝑑(𝑥, 𝑧) ≤ 𝑑(𝑥, 𝑦) + 𝑑(𝑦, 𝑧).
If this argument is not specified, the Euclidean distance metric is used.
• p_dist (function, optional) – A probability density function computing the probability of
connecting two nodes that are of distance, r, computed by metric. The probability density
function, p_dist, must be any function that takes the metric value as input and outputs a
single probability value between 0-1. The scipy.stats package has many probability distri-
bution functions implemented and tools for custom probability distribution definitions [2],
and passing the .pdf method of scipy.stats distributions can be used here. If the probability
function, p_dist, is not supplied, the default exponential function :math: r^{-2} is used.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns
A random geographic threshold graph, undirected and without self-loops.
Each node has a node attribute pos that stores the position of that node in Euclidean space
as provided by the pos keyword argument or, if pos was not provided, as generated by this
function. Similarly, each node has a node attribute weight that stores the weight of that node
as provided or as generated.
Return type Graph
Examples
Specify an alternate distance metric using the metric keyword argument. For example, to use the taxicab
metric instead of the default Euclidean metric:
Notes
If weights are not specified they are assigned to nodes by drawing randomly from the exponential distribution
with rate parameter 𝜆 = 1. To specify weights from a different distribution, use the weight keyword argument:
If node positions are not specified they are randomly assigned from the uniform distribution.
Starting in NetworkX 2.1 the parameter alpha is deprecated and replaced with the customizable p_dist
function parameter, which defaults to r^-2 if p_dist is not supplied. To reproduce networks of earlier Net-
workX versions, a custom function needs to be defined and passed as the p_dist parameter. For example,
if the parameter alpha = 2 was used in NetworkX 2.0, the custom function def custom_dist(r): r**-2 can be
passed in versions >=2.1 as the parameter p_dist = custom_dist to produce an equivalent network. Note the
change in sign from +2 to -2 in this parameter change.
References
5.11.4 networkx.generators.geometric.waxman_graph
𝑝 = 𝛽 exp(−𝑑/𝛼𝐿).
This function implements both Waxman models, using the L keyword argument.
• Waxman-1: if L is not specified, it is set to be the maximum distance between any pair of nodes.
• Waxman-2: if L is specified, the distance between a pair of nodes is chosen uniformly at random from the
interval [0, L].
Parameters
• n (int or iterable) – Number of nodes or iterable of nodes
• beta (float) – Model parameter
• alpha (float) – Model parameter
• L (float, optional) – Maximum distance between nodes. If not specified, the actual distance
is calculated.
• domain (four-tuple of numbers, optional) – Domain size, given as a tuple of the form
(x_min, y_min, x_max, y_max).
Examples
Specify an alternate distance metric using the metric keyword argument. For example, to use the “taxicab
metric” instead of the default Euclidean metric:
Notes
Starting in NetworkX 2.0 the parameters alpha and beta align with their usual roles in the probability distribution.
In earlier versions their positions in the expression were reversed. Their position in the calling sequence reversed
as well to minimize backward incompatibility.
References
5.11.5 networkx.generators.geometric.navigable_small_world_graph
—1
Parameters
• n (int) – The length of one side of the lattice; the number of nodes in the graph is therefore
𝑛2 .
• p (int) – The diameter of short range connections. Each node is joined with every other node
within this lattice distance.
• q (int) – The number of long-range connections for each node.
• r (float) – Exponent for decaying probability of connections. The probability of connecting
to a node at lattice distance 𝑑 is 1/𝑑𝑟 .
• dim (int) – Dimension of grid
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
References
5.11.6 networkx.generators.geometric.thresholded_random_geometric_graph
Returns
A thresholded random geographic graph, undirected and without self-loops.
Each node has a node attribute 'pos' that stores the position of that node in Euclidean space
as provided by the pos keyword argument or, if pos was not provided, as generated by this
function. Similarly, each node has a nodethre attribute 'weight' that stores the weight of that
node as provided or as generated.
Return type Graph
Examples
Default Graph:
G = nx.thresholded_random_geometric_graph(50, 0.2, 0.1)
Custom Graph:
Create a thresholded random geometric graph on 50 uniformly distributed nodes where nodes are joined by
an edge if their sum weights drawn from a exponential distribution with rate = 5 are >= theta = 0.1 and their
Euclidean distance is at most 0.2.
Notes
::
References
5.12.1 networkx.generators.line.line_graph
line_graph(G, create_using=None)
Returns 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 joining those nodes if the two edges in
G share a common node. For directed graphs, nodes are adjacent exactly when the edges they represent form a
directed path of length two.
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 third element).
For information about self-loops and more discussion, see the Notes section below.
Parameters
• G (graph) – A NetworkX Graph, DiGraph, MultiGraph, or MultiDigraph.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Returns L – The line graph of G.
Return type graph
Examples
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.
Self-loops in undirected graphs
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 pairwise
intersections of edges in G.
Trivially, every edge 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 a simple graph and thus, self-loops in
L are not part of the standard definition of a line graph. In a pairwise intersection matrix, this is analogous to
excluding the diagonal entries from 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.
Self-loops in directed graphs
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 and y 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, for example, if x = (a, b) and y = (b, c) for some vertices a, b, and c in G.
Due to the directed nature of the edges, it is no longer the case that every edge in G should have a self-loop in
L. Now, the only time self-loops arise is if a node in 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.
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., Selected Topics in Graph Theory, Academic Press Inc., pp. 271–305.
5.12.2 networkx.generators.line.inverse_line_graph
inverse_line_graph(G)
Returns the inverse line graph of graph G.
If H is a graph, and G is the line graph of H, such that H = L(G). Then H is the inverse line graph of G.
Not all graphs are line graphs and these do not have an inverse line graph. In these cases this generator returns
a NetworkXError.
Parameters G (graph) – A NetworkX Graph
Returns H – The inverse line graph of G.
Return type graph
Raises
• NetworkXNotImplemented – If G is directed or a multigraph
• NetworkXError – If G is not a line graph
Notes
References
• Roussopolous, N, “A max {m, n} algorithm for determining the graph H from its line graph G”, Informa-
tion Processing Letters 2, (1973), 108–112.
Ego graph.
ego_graph(G, n[, radius, center, . . . ]) Returns induced subgraph of neighbors centered at node
n within a given radius.
5.13.1 networkx.generators.ego.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.
5.14 Stochastic
Functions for generating stochastic graphs from a given weighted directed graph.
5.14.1 networkx.generators.stochastic.stochastic_graph
• weight (edge attribute key (optional, default=’weight’)) – Edge attribute key used for read-
ing the existing weight and setting the new weight. If no attribute with this key is found for
an edge, then the edge weight is assumed to be 1. If an edge has a weight, it must be a a
positive number.
5.15 Intersection
5.15.1 networkx.generators.intersection.uniform_random_intersection_graph
uniform_random_intersection_graph(n, m, p, seed=None)
Returns 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 (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
See also:
gnp_random_graph()
References
5.15.2 networkx.generators.intersection.k_random_intersection_graph
k_random_intersection_graph(n, m, k, seed=None)
Returns 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 (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
See also:
gnp_random_graph(), uniform_random_intersection_graph()
References
5.15.3 networkx.generators.intersection.general_random_intersection_graph
general_random_intersection_graph(n, m, p, seed=None)
Returns 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 (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
See also:
gnp_random_graph(), uniform_random_intersection_graph()
References
5.16.1 networkx.generators.social.karate_club_graph
karate_club_graph()
Returns Zachary’s Karate Club graph.
Each node in the returned graph has a node attribute ‘club’ that indicates the name of the club to which the
member represented by that node belongs, either ‘Mr. Hi’ or ‘Officer’.
Examples
References
5.16.2 networkx.generators.social.davis_southern_women_graph
davis_southern_women_graph()
Returns Davis Southern women social network.
This is a bipartite graph.
References
5.16.3 networkx.generators.social.florentine_families_graph
florentine_families_graph()
Returns Florentine families graph.
References
5.16.4 networkx.generators.social.les_miserables_graph
les_miserables_graph()
Returns coappearance network of characters in the novel Les Miserables.
References
5.17 Community
5.17.1 networkx.generators.community.caveman_graph
caveman_graph(l, k)
Returns a caveman graph of l cliques of size k.
Parameters
• l (int) – Number of cliques
• k (int) – Size of cliques
Returns G – caveman graph
Return type NetworkX Graph
Notes
This returns an undirected graph, it can be converted to a directed graph using nx.to_directed(), or a
multigraph using nx.MultiGraph(nx.caveman_graph(l, k)). Only the undirected version is de-
scribed in1 and it is unclear which of the directed generalizations is most useful.
Examples
>>> G = nx.caveman_graph(3, 3)
See also:
connected_caveman_graph()
References
5.17.2 networkx.generators.community.connected_caveman_graph
connected_caveman_graph(l, k)
Returns a connected caveman graph of l cliques of size k.
The connected caveman graph is formed by creating n cliques of size k, then a single edge in each clique is
rewired to a node in an adjacent clique.
Parameters
• l (int) – number of cliques
• k (int) – size of cliques
Returns G – connected caveman graph
Return type NetworkX Graph
1 Watts, D. J. ‘Networks, Dynamics, and the Small-World Phenomenon.’ Amer. J. Soc. 105, 493-527, 1999.
Notes
This returns an undirected graph, it can be converted to a directed graph using nx.to_directed(), or a
multigraph using nx.MultiGraph(nx.caveman_graph(l, k)). Only the undirected version is de-
scribed in1 and it is unclear which of the directed generalizations is most useful.
Examples
>>> G = nx.connected_caveman_graph(3, 3)
References
5.17.3 networkx.generators.community.relaxed_caveman_graph
relaxed_caveman_graph(l, k, p, seed=None)
Returns a relaxed caveman graph.
A relaxed caveman graph starts with l cliques of size k. Edges are then randomly rewired with probability p to
link different cliques.
Parameters
• l (int) – Number of groups
• k (int) – Size of cliques
• p (float) – Probabilty of rewiring each edge.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns G – Relaxed Caveman Graph
Return type NetworkX Graph
Raises NetworkXError: – If p is not in [0,1]
Examples
References
5.17.4 networkx.generators.community.random_partition_graph
Examples
>>> G = nx.random_partition_graph([10,10,10],.25,.01)
>>> len(G)
30
>>> partition = G.graph['partition']
>>> len(partition)
3
Notes
This is a generalization of the planted-l-partition described in1 . It allows for the creation of groups of any size.
The partition is store as a graph attribute ‘partition’.
References
5.17.5 networkx.generators.community.planted_partition_graph
Examples
See also:
random_partition_model()
References
5.17.6 networkx.generators.community.gaussian_random_partition_graph
Notes
Note the number of partitions is dependent on s,v and n, and that the last partition may be considerably smaller,
as it is sized to simply fill out the nodes [1]
See also:
random_partition_graph()
Examples
>>> G = nx.gaussian_random_partition_graph(100,10,10,.25,.1)
>>> len(G)
100
References
5.17.7 networkx.generators.community.ring_of_cliques
ring_of_cliques(num_cliques, clique_size)
Defines a “ring of cliques” graph.
A ring of cliques graph is consisting of cliques, connected through single links. Each clique is a complete graph.
Parameters
• num_cliques (int) – Number of cliques
• clique_size (int) – Size of cliques
Returns G – ring of cliques graph
Return type NetworkX Graph
Raises NetworkXError – If the number of cliques is lower than 2 or if the size of cliques is
smaller than 2.
Examples
>>> G = nx.ring_of_cliques(8, 4)
See also:
connected_caveman_graph()
Notes
The connected_caveman_graph graph removes a link from each clique to connect it with the next clique.
Instead, the ring_of_cliques graph simply adds the link without removing any link from the cliques.
5.17.8 networkx.generators.community.stochastic_block_model
Examples
See also:
random_partition_graph(), planted_partition_graph(), gaussian_random_partition_graph(),
gnp_random_graph()
References
5.17.9 networkx.generators.community.windmill_graph
windmill_graph(n, k)
Generate a windmill graph. A windmill graph is a graph of n cliques each of size k that are all joined at one
node. It can be thought of as taking a disjoint union of n cliques of size k, selecting one point from each, and
contracting all of the selected points. Alternatively, one could generate n cliques of size k-1 and one node that
is connected to all other nodes in the graph.
Parameters
• n (int) – Number of cliques
• k (int) – Size of cliques
Returns G – windmill graph with n cliques of size k
Return type NetworkX Graph
Raises NetworkXError – If the number of cliques is less than two If the size of the cliques are
less than two
Examples
>>> G = nx.windmill_graph(4, 5)
Notes
The node labeled 0 will be the node connected to all other nodes. Note that windmill graphs are usually denoted
Wd(k,n), so the parameters are in the opposite order as the parameters of this method.
5.18 Spectral
5.18.1 networkx.generators.spectral_graph_forge.spectral_graph_forge
Notes
Spectral Graph Forge (SGF) generates a random simple graph resembling the global properties of the given
one. It leverages the low-rank approximation of the associated adjacency matrix driven by the alpha precision
parameter. SGF preserves the number of nodes of the input graph and their ordering. This way, nodes of output
graphs resemble the properties of the input one and attributes can be directly mapped.
It considers the graph adjacency matrices which can optionally be transformed to other symmetric real matrices
(currently transformation options include identity and modularity). The modularity transformation, in the sense
of Newman’s modularity matrix allows the focusing on community structure related properties of the graph.
SGF applies a low-rank approximation whose fixed rank is computed from the ratio alpha of the input graph
adjacency matrix dimension. This step performs a filtering on the input eigenvectors similar to the low pass
filtering common in telecommunications.
The filtered values (after truncation) are used as input to a Bernoulli sampling for constructing a random adja-
cency matrix.
References
Examples
5.19 Trees
5.19.1 networkx.generators.trees.random_tree
random_tree(n, seed=None)
Returns a uniformly random tree on n nodes.
Parameters
• n (int) – A positive integer representing the number of nodes in the tree.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns A tree, given as an undirected graph, whose nodes are numbers in the set {0, . . . , n - 1}.
Return type NetworkX graph
Raises NetworkXPointlessConcept – If n is zero (because the null graph is not a tree).
Notes
The current implementation of this function generates a uniformly random Prüfer sequence then converts that
to a tree via the from_prufer_sequence() function. Since there is a bijection between Prüfer sequences
of length n - 2 and trees on n nodes, the tree is chosen uniformly at random from the set of all trees on n nodes.
5.19.2 networkx.generators.trees.prefix_tree
prefix_tree(paths)
Creates a directed prefix tree from the given list of iterables.
Parameters paths (iterable of lists) – An iterable over “paths”, which are themselves lists of nodes.
Common prefixes among these paths are converted into common initial segments in the gener-
ated tree.
Most commonly, this may be an iterable over lists of integers, or an iterable over Python strings.
Returns
• T (DiGraph) – A directed graph representing an arborescence consisting of the prefix tree
generated by paths. Nodes are directed “downward”, from parent to child. A special
“synthetic” root node is added to be the parent of the first node in each path. A special
“synthetic” leaf node, the “nil” node, is added to be the child of all nodes representing
the last element in a path. (The addition of this nil node technically makes this not an
arborescence but a directed acyclic graph; removing the nil node makes it an arborescence.)
Each node has an attribute ‘source’ whose value is the original element of the path to which
this node corresponds. The ‘source’ of the root node is None, and the ‘source’ of the nil
node is NIL.
The root node is the only node of in-degree zero in the graph, and the nil node is the only
node of out-degree zero. For convenience, the nil node can be accessed via the NIL attribute;
for example:
Notes
Examples
Create a prefix tree from a list of strings with some common prefixes:
Continuing the above example, to recover the original paths that generated the prefix tree, traverse up the tree
from the NIL node to the root:
Implementation of the Wright, Richmond, Odlyzko and McKay (WROM) algorithm for the enumeration of all non-
isomorphic free trees of a given order. Rooted trees are represented by level sequences, i.e., lists in which the i-th
element specifies the distance of vertex i to the root.
5.20.1 networkx.generators.nonisomorphic_trees.nonisomorphic_trees
nonisomorphic_trees(order, create=’graph’)
Returns a list of nonisomporphic trees
Parameters
• order (int) – order of the desired tree(s)
• create (graph or matrix (default=”Graph)) – If graph is selected a list of trees will be
returned, if matrix is selected a list of adjancency matrix will be returned
Returns
• G (List of NetworkX Graphs)
• M (List of Adjacency matrices)
References
5.20.2 networkx.generators.nonisomorphic_trees.number_of_nonisomorphic_trees
number_of_nonisomorphic_trees(order)
Returns the number of nonisomorphic trees
Parameters order (int) – order of the desired tree(s)
Returns length
Return type Number of nonisomorphic graphs for the given order
References
5.21 Triads
Functions that generate the triad graphs, that is, the possible digraphs on three nodes.
5.21.1 networkx.generators.triads.triad_graph
triad_graph(triad_name)
Returns the triad graph with the given name.
Each string in the following tuple is a valid triad name:
Each triad name corresponds to one of the possible valid digraph on three nodes.
Parameters triad_name (string) – The name of a triad, as described above.
Returns The digraph on three nodes with the given name. The nodes of the graph are the single-
character strings ‘a’, ‘b’, and ‘c’.
Return type DiGraph
Raises ValueError – If triad_name is not the name of a triad.
See also:
triadic_census()
5.22.1 networkx.generators.joint_degree_seq.is_valid_joint_degree
is_valid_joint_degree(joint_degrees)
Checks whether the given joint degree dictionary is realizable as a simple graph.
A joint degree dictionary is a dictionary of dictionaries, in which entry joint_degrees[k][l] is an integer
representing the number of edges joining nodes of degree k with nodes of degree l. Such a dictionary is realizable
as a simple graph if and only if the following conditions are satisfied.
• each entry must be an integer,
References
5.22.2 networkx.generators.joint_degree_seq.joint_degree_graph
joint_degree_graph(joint_degrees, seed=None)
Generates a random simple graph with the given joint degree dictionary.
Parameters
• joint_degrees (dictionary of dictionary of integers) – A joint degree dictionary in which
entry joint_degrees[k][l] is the number of edges joining nodes of degree k with
nodes of degree l.
• seed (integer, random_state, or None (default)) – Indicator of random number generation
state. See Randomness.
Returns G – A graph with the specified joint degree dictionary.
Return type Graph
Raises NetworkXError – If joint_degrees dictionary is not realizable.
Notes
In each iteration of the “while loop” the algorithm picks two disconnected nodes v and w, of degree k and l
correspondingly, for which joint_degrees[k][l] has not reached its target yet. It then adds edge (v, w)
and increases the number of edges in graph G by one.
The intelligence of the algorithm lies in the fact that it is always possible to add an edge between such discon-
nected nodes v and w, even if one or both nodes do not have free stubs. That is made possible by executing a
“neighbor switch”, an edge rewiring move that releases a free stub while keeping the joint degree of G the same.
The algorithm continues for E (number of edges) iterations of the “while loop”, at the which point all entries of
the given joint_degrees[k][l] have reached their target values and the construction is complete.
References
Examples
5.23 Mycielski
Functions related to the Mycielski Operation and the Mycielskian family of graphs.
5.23.1 networkx.generators.mycielski.mycielskian
mycielskian(G, iterations=1)
Returns the Mycielskian of a simple, undirected graph G
The Mycielskian of graph preserves a graph’s triangle free property while increasing the chromatic number by
1.
The Mycielski Operation on a graph, 𝐺 = (𝑉, 𝐸), constructs a new graph with 2|𝑉 | + 1 nodes and 3|𝐸| + |𝑉 |
edges.
The construction is as follows:
Let 𝑉 = 0, ..., 𝑛⋃︀− 1.⋃︀ Construct another vertex set 𝑈 = 𝑛, ..., 2𝑛 and a vertex, w. Construct a new graph, M,
with vertices 𝑈 𝑉 𝑤. For edges, (𝑢, 𝑣) ∈ 𝐸 add edges (𝑢, 𝑣), (𝑢, 𝑣 + 𝑛), and (𝑢 + 𝑛, 𝑣) to M. Finally, for
all vertices 𝑢 ∈ 𝑈 , add edge (𝑢, 𝑤) to M.
The Mycielski Operation can be done multiple times by repeating the above process iteratively.
More information can be found at https://en.wikipedia.org/wiki/Mycielskian
Parameters
• G (graph) – A simple, undirected NetworkX graph
• iterations (int) – The number of iterations of the Mycielski operation to perform on G.
Defaults to 1. Must be a non-negative integer.
Returns M – The Mycielskian of G after the specified number of iterations.
Return type graph
Notes
Graph, node, and edge data are not necessarily propagated to the new graph.
5.23.2 networkx.generators.mycielski.mycielski_graph
mycielski_graph(n)
Generator for the n_th Mycielski Graph.
The Mycielski family of graphs is an infinite set of graphs. 𝑀1 is the singleton graph, 𝑀2 is two vertices with
an edge, and, for 𝑖 > 2, 𝑀𝑖 is the Mycielskian of 𝑀𝑖−1 .
More information can be found at http://mathworld.wolfram.com/MycielskiGraph.html
Parameters n (int) – The desired Mycielski Graph.
Returns M – The n_th Mycielski Graph
Return type graph
Notes
The first graph in the Mycielski sequence is the singleton graph. The Mycielskian of this graph is not the 𝑃2
graph, but rather the 𝑃2 graph with an extra, isolated vertex. The second Mycielski graph is the 𝑃2 graph, so the
first two are hard coded. The remaining graphs are generated using the Mycielski operation.
SIX
LINEAR ALGEBRA
6.1.1 networkx.linalg.graphmatrix.adjacency_matrix
Notes
579
NetworkX Reference, Release 2.3rc1.dev20190222214247
See also:
to_numpy_matrix(), to_scipy_sparse_matrix(), to_dict_of_dicts()
6.1.2 networkx.linalg.graphmatrix.incidence_matrix
Notes
References
6.2.1 networkx.linalg.laplacianmatrix.laplacian_matrix
Notes
6.2.2 networkx.linalg.laplacianmatrix.normalized_laplacian_matrix
𝑁 = 𝐷−1/2 𝐿𝐷−1/2
where L is the graph Laplacian and D 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 N – The normalized Laplacian matrix of G.
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 adjacency matrix2 .
See also:
laplacian_matrix()
References
6.2.3 networkx.linalg.laplacianmatrix.directed_laplacian_matrix
where I is the identity matrix, P is the transition matrix of the graph, and Phi a matrix with the Perron vector
of P in the diagonal and zeros elsewhere.
Depending on the value of walk_type, P 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.
• walk_type (string or None, optional (default=None)) – If None, P is selected depending on
the properties of the graph. Otherwise is one of ‘random’, ‘lazy’, or ‘pagerank’
• alpha (real) – (1 - alpha) is the teleportation probability used with pagerank
Returns L – Normalized Laplacian of G.
Return type NumPy array
Notes
References
6.3 Spectrum
6.3.1 networkx.linalg.spectrum.laplacian_spectrum
laplacian_spectrum(G, weight=’weight’)
Returns 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 – Eigenvalues
Return type NumPy array
Notes
For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options.
See also:
laplacian_matrix()
6.3.2 networkx.linalg.spectrum.adjacency_spectrum
adjacency_spectrum(G, weight=’weight’)
Returns 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 – Eigenvalues
Return type NumPy array
Notes
For MultiGraph/MultiDiGraph, the edges weights are summed. See to_numpy_matrix for other options.
See also:
adjacency_matrix()
6.3.3 networkx.linalg.spectrum.modularity_spectrum
modularity_spectrum(G)
Returns eigenvalues of the modularity matrix of G.
Parameters G (Graph) – A NetworkX Graph or DiGraph
Returns evals – Eigenvalues
Return type NumPy array
See also:
modularity_matrix()
References
6.4.1 networkx.linalg.algebraicconnectivity.algebraic_connectivity
Value Solver
‘tracemin_pcg’ Preconditioned conjugate gradient method
‘tracemin_chol’ Cholesky factorization
‘tracemin_lu’ LU factorization
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.
See also:
laplacian_matrix()
6.4.2 networkx.linalg.algebraicconnectivity.fiedler_vector
Value Solver
‘tracemin_pcg’ Preconditioned conjugate gradient method
‘tracemin_chol’ Cholesky factorization
‘tracemin_lu’ LU factorization
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.
See also:
laplacian_matrix()
6.4.3 networkx.linalg.algebraicconnectivity.spectral_ordering
Value Solver
‘tracemin_pcg’ Preconditioned conjugate gradient method
‘tracemin_chol’ Cholesky factorization
‘tracemin_lu’ LU factorization
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.
See also:
laplacian_matrix()
6.5.1 networkx.linalg.attrmatrix.attr_matrix
• node_attr (str, optional) – 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).
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.
• order ({‘C’, ‘F’}, optional) – Whether to store multidimensional data in C- or Fortran-
contiguous (row- or column-wise) order in memory. This parameter is passed to
numpy.zeros(). If unspecified, the NumPy default is used.
Returns
• M (NumPy matrix) – The attribute matrix.
• ordering (list) – If rc_order was specified, then only the matrix is returned. However, if
rc_order was None, then the ordering used to construct the matrix is returned as well.
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)
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
6.5.2 networkx.linalg.attrmatrix.attr_sparse_matrix
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.
Returns
• M (SciPy sparse matrix) – The attribute matrix.
• ordering (list) – If rc_order was specified, then only the matrix is returned. However, if
rc_order was None, then the ordering used to construct the matrix is returned as well.
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)
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.
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
6.6.1 networkx.linalg.modularitymatrix.modularity_matrix
𝑘𝑖 𝑘𝑗
𝐴𝑖𝑗 −
2𝑚
where k_i is the degree of node i, and where m is the number of edges in the graph. When weight is set to a
name of an attribute edge, Aij, k_i, k_j and m are computed using its value.
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=None)) – The edge attribute that holds the numer-
ical value used for the edge weight. If None then all edge weights are 1.
Returns B – The modularity matrix of G.
Return type Numpy matrix
Examples
See also:
to_numpy_matrix(), adjacency_matrix(), laplacian_matrix(),
directed_modularity_matrix()
References
6.6.2 networkx.linalg.modularitymatrix.directed_modularity_matrix
where 𝑘𝑖𝑖𝑛 is the in degree of node i, and 𝑘𝑗𝑜𝑢𝑡 is the out degree of node j, with m the number of edges in the
graph. When weight is set to a name of an attribute edge, Aij, k_i, k_j and m are computed using its value.
Parameters
• G (DiGraph) – A NetworkX DiGraph
• 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=None)) – The edge attribute that holds the numer-
ical value used for the edge weight. If None then all edge weights are 1.
Returns B – The modularity matrix of G.
Return type Numpy matrix
Examples
Notes
NetworkX defines the element A_ij of the adjacency matrix as 1 if there is a link going from node i to node j.
Leicht and Newman use the opposite definition. This explains the different expression for B_ij.
See also:
to_numpy_matrix(), adjacency_matrix(), laplacian_matrix(),
modularity_matrix()
References
SEVEN
Examples
See also:
nx_agraph, nx_pydot
7.1.1 networkx.convert.to_networkx_graph
>>> G = nx.from_dict_of_dicts(d)
Parameters
• data (object to be converted) –
Current known types are: any NetworkX graph dict-of-dicts dict-of-lists list of edges
Pandas DataFrame (row per edge) numpy matrix numpy ndarray scipy sparse matrix py-
graphviz agraph
595
NetworkX Reference, Release 2.3rc1.dev20190222214247
7.2 Dictionaries
7.2.1 networkx.convert.to_dict_of_dicts
7.2.2 networkx.convert.from_dict_of_dicts
Examples
or
7.3 Lists
7.3.1 networkx.convert.to_dict_of_lists
to_dict_of_lists(G, nodelist=None)
Returns adjacency representation of graph as a dictionary of lists.
Parameters
• G (graph) – A NetworkX graph
• nodelist (list) – Use only nodes specified in nodelist
Notes
7.3.2 networkx.convert.from_dict_of_lists
from_dict_of_lists(d, create_using=None)
Returns a graph from a dictionary of lists.
Parameters
• d (dictionary of lists) – A dictionary of lists adjacency representation.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Examples
or
7.3.3 networkx.convert.to_edgelist
to_edgelist(G, nodelist=None)
Returns a list of edges in the graph.
Parameters
• G (graph) – A NetworkX graph
7.3.4 networkx.convert.from_edgelist
from_edgelist(edgelist, create_using=None)
Returns a graph from a list of edges.
Parameters
• edgelist (list or iterator) – Edge tuples
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Examples
or
7.4 Numpy
Examples
or equivalently
See also:
nx_agraph, nx_pydot
to_numpy_matrix(G[, nodelist, dtype, order, . . . ]) Returns the graph adjacency matrix as a NumPy matrix.
to_numpy_array(G[, nodelist, dtype, order, . . . ]) Returns the graph adjacency matrix as a NumPy array.
to_numpy_recarray(G[, nodelist, dtype, order]) Returns the graph adjacency matrix as a NumPy recar-
ray.
from_numpy_matrix(A[, parallel_edges, . . . ]) Returns a graph from numpy matrix.
from_numpy_array(A[, parallel_edges, . . . ]) Returns a graph from NumPy array.
7.4.1 networkx.convert_matrix.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 parameter. The default is to sum the weight attributes for each of the parallel
edges.
When nodelist does not contain every node in G, the matrix is built from the subgraph of G that is induced
by the nodes in nodelist.
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 Numpy matrix can be modified as follows:
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_matrix(G, nodelist=[0, 1, 2])
matrix([[ 0., 2., 0.],
[ 1., 0., 0.],
[ 0., 0., 4.]])
7.4.2 networkx.convert_matrix.to_numpy_array
Notes
Entries in the adjacency matrix 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 parameter. The default is to sum the weight attributes for each of
the parallel edges.
When nodelist does not contain every node in G, the adjacency matrix is built from the subgraph of G that is
induced by the nodes in nodelist.
The convention used for self-loop edges in graphs is to assign the diagonal array 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 NumPy array can be modified as follows:
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_numpy_array(G, nodelist=[0, 1, 2])
array([[ 0., 2., 0.],
[ 1., 0., 0.],
[ 0., 0., 4.]])
7.4.3 networkx.convert_matrix.to_numpy_recarray
Parameters
• G (graph) – The NetworkX graph used to construct the NumPy matrix.
• 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().
• dtype (NumPy data-type, optional) – A valid NumPy named dtype used to initialize the
NumPy recarray. The data type names are assumed to be keys in the graph edge attribute
dictionary.
• order ({‘C’, ‘F’}, optional) – Whether to store multidimensional data in C- or Fortran-
contiguous (row- or column-wise) order in memory. If None, then the NumPy default is
used.
Returns M – The graph with specified edge data as a Numpy recarray
Return type NumPy recarray
Notes
When nodelist does not contain every node in G, the matrix is built from the subgraph of G that is induced
by the nodes in nodelist.
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]]
7.4.4 networkx.convert_matrix.from_numpy_matrix
Notes
Examples
If create_using indicates a multigraph and the matrix has only integer entries and parallel_edges is
False, then the entries will be treated as weights for edges joining the nodes (without creating parallel edges):
If create_using indicates a multigraph and the matrix has only integer entries and parallel_edges is
True, then the entries will be treated as the number of parallel edges joining those two vertices:
7.4.5 networkx.convert_matrix.from_numpy_array
Notes
Examples
If create_using indicates a multigraph and the array has only integer entries and parallel_edges is
False, then the entries will be treated as weights for edges joining the nodes (without creating parallel edges):
If create_using indicates a multigraph and the array has only integer entries and parallel_edges is
True, then the entries will be treated as the number of parallel edges joining those two vertices:
7.5 Scipy
to_scipy_sparse_matrix(G[, nodelist, dtype, Returns the graph adjacency matrix as a SciPy sparse
. . . ]) matrix.
from_scipy_sparse_matrix(A[, . . . ]) Creates a new graph from an adjacency matrix given as
a SciPy sparse matrix.
7.5.1 networkx.convert_matrix.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 nodelist does not contain every node in G, the matrix is built from the subgraph of G that is induced
by the nodes in nodelist.
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:
>>> import scipy as sp
>>> G = nx.Graph([(1, 1)])
>>> A = nx.to_scipy_sparse_matrix(G)
>>> print(A.todense())
[[1]]
>>> A.setdiag(A.diagonal() * 2)
>>> print(A.todense())
[[2]]
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> S = nx.to_scipy_sparse_matrix(G, nodelist=[0, 1, 2])
>>> print(S.todense())
[[0 2 0]
[1 0 0]
[0 0 4]]
References
7.5.2 networkx.convert_matrix.from_scipy_sparse_matrix
Notes
Examples
If create_using indicates a multigraph and the matrix has only integer entries and parallel_edges is
False, then the entries will be treated as weights for edges joining the nodes (without creating parallel edges):
If create_using indicates a multigraph and the matrix has only integer entries and parallel_edges is
True, then the entries will be treated as the number of parallel edges joining those two vertices:
7.6 Pandas
7.6.1 networkx.convert_matrix.to_pandas_adjacency
Notes
The DataFrame 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’ parameter. The default is to sum the weight attributes for each of the parallel edges.
When nodelist does not contain every node in G, the matrix is built from the subgraph of G that is induced
by the nodes in nodelist.
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 Pandas DataFrame can be modified as follows:
Examples
>>> G = nx.MultiDiGraph()
>>> G.add_edge(0, 1, weight=2)
0
>>> G.add_edge(1, 0)
0
>>> G.add_edge(2, 2, weight=3)
0
>>> G.add_edge(2, 2)
1
>>> nx.to_pandas_adjacency(G, nodelist=[0, 1, 2], dtype=int)
0 1 2
0 0 2 0
1 1 0 0
2 0 0 4
7.6.2 networkx.convert_matrix.from_pandas_adjacency
from_pandas_adjacency(df, create_using=None)
Returns a graph from Pandas DataFrame.
The Pandas DataFrame is interpreted as an adjacency matrix for the graph.
Parameters
• df (Pandas DataFrame) – An adjacency matrix representation of a graph
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
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.
See also:
to_pandas_adjacency()
Examples
7.6.3 networkx.convert_matrix.to_pandas_edgelist
Examples
7.6.4 networkx.convert_matrix.from_pandas_edgelist
• target (str or int) – A valid column name (string or integer) for the target nodes (for the
directed case).
• edge_attr (str or int, iterable, True) – A valid column name (str or integer) or list of column
names that will be used to retrieve items from the row and add them to the graph as edge
attributes. If True, all of the remaining columns will be added.
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
See also:
to_pandas_edgelist()
Examples
EIGHT
RELABELING NODES
8.1 Relabeling
8.1.1 networkx.relabel.convert_node_labels_to_integers
Notes
Node and edge attribute data are copied to the new (relabeled) graph.
There is no guarantee that the relabeling of nodes to integers will give the same two integers for two (even
identical graphs). Use the ordering argument to try to preserve the order.
See also:
relabel_nodes()
8.1.2 networkx.relabel.relabel_nodes
613
NetworkX Reference, Release 2.3rc1.dev20190222214247
Examples
>>> G = nx.path_graph(3)
>>> sorted(G)
[0, 1, 2]
>>> mapping = {0: 'a', 1: 'b', 2: 'c'}
>>> H = nx.relabel_nodes(G, mapping)
>>> sorted(H)
['a', 'b', 'c']
Nodes can be relabeled with any hashable object, including numbers and strings:
To perform a partial in-place relabeling, provide a dictionary mapping only a subset of the nodes, and set the
copy keyword argument to False:
>>> G = nx.path_graph(3)
>>> H = nx.relabel_nodes(G, lambda x: x ** 2)
>>> list(H)
[0, 1, 4]
Notes
b->c, are ordered such that “b” gets renamed to “c” before “a” gets renamed “b”. In cases of circular mappings
(e.g. a->b, b->a), modifying the graph is not possible in-place and an exception is raised. In that case, use
copy=True.
See also:
convert_node_labels_to_integers()
NINE
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):
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 networkx.readwrite.adjlist.read_adjlist
617
NetworkX Reference, Release 2.3rc1.dev20190222214247
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.
>>> nx.write_adjlist(G,"test.adjlist.gz")
>>> G=nx.read_adjlist("test.adjlist.gz")
Notes
9.1.3 networkx.readwrite.adjlist.write_adjlist
Parameters
• G (NetworkX graph)
• path (string or file) – Filename or file handle for data output. Filenames ending in .gz or
.bz2 will be compressed.
• comments (string, optional) – Marker for comment lines
• delimiter (string, optional) – Separator for node labels
• encoding (string, optional) – Text encoding.
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)
Notes
9.1.4 networkx.readwrite.adjlist.parse_adjlist
Examples
See also:
read_adjlist()
9.1.5 networkx.readwrite.adjlist.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 – Lines of data in adjlist format.
Return type string
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
See also:
write_adjlist(), read_adjlist()
The multi-line adjacency list format is useful for graphs with nodes that can be meaningfully represented as strings.
With this format simple edge data can be stored but node or graph data is not.
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
9.2.2 networkx.readwrite.multiline_adjlist.read_multiline_adjlist
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.
>>> nx.write_multiline_adjlist(G,"test.adjlist.gz")
>>> G=nx.read_multiline_adjlist("test.adjlist.gz")
>>> G=nx.read_multiline_adjlist("test.adjlist")
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
Notes
9.2.3 networkx.readwrite.multiline_adjlist.write_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)
See also:
read_multiline_adjlist()
9.2.4 networkx.readwrite.multiline_adjlist.parse_multiline_adjlist
Examples
9.2.5 networkx.readwrite.multiline_adjlist.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 – Lines of data in multiline adjlist format.
Return type string
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
See also:
write_multiline_adjlist(), read_multiline_adjlist()
Format
You can read or write three formats of edge lists with these functions.
Node pairs with no data:
1 2
1 2 {'weight':7, 'color':'green'}
Arbitrary data:
1 2 7 green
9.3.2 networkx.readwrite.edgelist.read_edgelist
Examples
Notes
Since nodes must be hashable, the function nodetype must return hashable types (e.g. int, float, str, frozenset -
or tuples of those, etc.)
9.3.3 networkx.readwrite.edgelist.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'])
See also:
write_edgelist(), write_weighted_edgelist()
9.3.4 networkx.readwrite.edgelist.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 networkx.readwrite.edgelist.write_weighted_edgelist
Parameters
• G (graph) – A NetworkX graph
• path (file or string) – File or filename to write. If a file is provided, it must be opened in
‘wb’ mode. Filenames ending in .gz or .bz2 will be compressed.
• comments (string, optional) – The character used to indicate the start of a comment
• delimiter (string, optional) – The string used to separate values. The default is whitespace.
• encoding (string, optional) – Specify which encoding to use when writing file.
Examples
>>> G=nx.Graph()
>>> G.add_edge(1,2,weight=7)
>>> nx.write_weighted_edgelist(G, 'test.weighted.edgelist')
See also:
read_edgelist(), write_edgelist(), write_weighted_edgelist()
9.3.6 networkx.readwrite.edgelist.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
See also:
write_adjlist(), read_adjlist()
9.3.7 networkx.readwrite.edgelist.parse_edgelist
Examples
See also:
read_weighted_edgelist()
9.4 GEXF
9.4.1 Format
GEXF is an XML format. See https://gephi.org/gexf/format/schema.html for the specification and https://gephi.org/
gexf/format/basic.html for examples.
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.
generate_gexf(G[, encoding, prettyprint, . . . ]) Generate lines of GEXF format representation of G.
relabel_gexf_graph(G) Relabel graph using “label” node keyword for node la-
bel.
9.4.2 networkx.readwrite.gexf.read_gexf
Notes
This implementation does not support mixed graphs (directed and undirected edges together).
References
9.4.3 networkx.readwrite.gexf.write_gexf
Examples
>>> G = nx.path_graph(4)
>>> nx.write_gexf(G, "test.gexf")
# visualization data >>> G.nodes[0][‘viz’] = {‘size’: 54} >>> G.nodes[0][‘viz’][‘position’] = {‘x’ : 0, ‘y’ : 1}
>>> G.nodes[0][‘viz’][‘color’] = {‘r’ : 0, ‘g’ : 0, ‘b’ : 256}
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
9.4.4 networkx.readwrite.gexf.generate_gexf
Examples
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed=
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.
1 GEXF File Format, https://gephi.org/gexf/format/
References
9.4.5 networkx.readwrite.gexf.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 – A NetworkX graph with relabed nodes
Return type graph
Raises NetworkXError – If node labels are missing or not unique while relabel=True.
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 networkx.readwrite.gml.read_gml
Notes
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing
as HTML character entities. Without specifying a stringizer/destringizer, the code is capable of
handling int/float/str/dict/list data as required by the GML specification. For other data types, you
need to explicitly supply a stringizer/destringizer.
For additional documentation on the GML file format, please see the GML website.
See the module docstring networkx.readwrite.gml for more details.
Examples
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, 'test.gml')
>>> H = nx.read_gml('test.gml')
9.5.2 networkx.readwrite.gml.write_gml
Raises NetworkXError – If stringizer cannot convert a value into a string, or the value to
convert is not a string while stringizer is None.
See also:
read_gml(), generate_gml(), literal_stringizer()
Notes
Graph attributes named ‘directed’, ‘multigraph’, ‘node’ or ‘edge’, node attributes named ‘id’ or ‘label’, edge
attributes named ‘source’ or ‘target’ (or ‘key’ if G is a multigraph) are ignored because these attribute names are
used to encode the graph structure.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing
as HTML character entities. Without specifying a stringizer/destringizer, the code is capable of
handling int/float/str/dict/list data as required by the GML specification. For other data types, you
need to explicitly supply a stringizer/destringizer.
Note that while we allow non-standard GML to be read from a file, we make sure to write GML format. In
particular, underscores are not allowed in attribute names. For additional documentation on the GML file format,
please see the GML website.
See the module docstring networkx.readwrite.gml for more details.
Examples
>>> G = nx.path_graph(4)
>>> nx.write_gml(G, "test.gml")
9.5.3 networkx.readwrite.gml.parse_gml
Notes
This stores nested GML attributes as dictionaries in the NetworkX graph, node, and edge attribute structures.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing
as HTML character entities. Without specifying a stringizer/destringizer, the code is capable of
handling int/float/str/dict/list data as required by the GML specification. For other data types, you
need to explicitly supply a stringizer/destringizer.
For additional documentation on the GML file format, please see the GML website.
See the module docstring networkx.readwrite.gml for more details.
9.5.4 networkx.readwrite.gml.generate_gml
generate_gml(G, stringizer=None)
Generate a single entry of the graph G in GML format.
Parameters
• G (NetworkX graph) – The graph to be converted to GML.
• stringizer (callable, optional) – A stringizer which converts non-int/non-float/non-dict
values into strings. If it cannot convert a value into a string, it should raise a ValueError
to indicate that. Default value: None.
Returns lines – Lines of GML data. Newlines are not appended.
Return type generator of strings
Raises NetworkXError – If stringizer cannot convert a value into a string, or the value to
convert is not a string while stringizer is None.
See also:
literal_stringizer()
Notes
Graph attributes named ‘directed’, ‘multigraph’, ‘node’ or ‘edge’, node attributes named ‘id’ or ‘label’, edge
attributes named ‘source’ or ‘target’ (or ‘key’ if G is a multigraph) are ignored because these attribute names are
used to encode the graph structure.
GML files are stored using a 7-bit ASCII encoding with any extended ASCII characters (iso8859-1) appearing
as HTML character entities. Without specifying a stringizer/destringizer, the code is capable of
handling int/float/str/dict/list data as required by the GML specification. For other data types, you
need to explicitly supply a stringizer/destringizer.
For additional documentation on the GML file format, please see the GML website.
See the module docstring networkx.readwrite.gml for more details.
Examples
>>> G = nx.Graph()
>>> G.add_node("1")
>>> print("\n".join(nx.generate_gml(G)))
graph [
(continues on next page)
9.5.5 networkx.readwrite.gml.literal_destringizer
literal_destringizer(rep)
Convert a Python literal to the value it represents.
Parameters rep (string) – A Python literal.
Returns value – The value of the Python literal.
Return type object
Raises ValueError – If rep is not a Python literal.
9.5.6 networkx.readwrite.gml.literal_stringizer
literal_stringizer(value)
Convert a value to a Python literal in GML representation.
Parameters value (object) – The value to be converted to GML representation.
Returns rep – A double-quoted Python literal representing value. Unprintable characters are re-
placed by XML character references.
Return type string
Raises ValueError – If value cannot be converted to GML.
Notes
literal_stringizer is largely the same as repr in terms of functionality but attempts prefix unicode
and bytes literals with u and b to provide better interoperability of data generated by Python 2 and Python 3.
The original value can be recovered using the networkx.readwrite.gml.
literal_destringizer() function.
9.6 Pickle
Format
See https://docs.python.org/2/library/pickle.html
9.6.2 networkx.readwrite.gpickle.read_gpickle
read_gpickle(path)
Read graph object in Python pickle format.
Pickles are a serialized byte stream of a Python object1 . 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 – A NetworkX graph
Return type graph
Examples
>>> G = nx.path_graph(4)
>>> nx.write_gpickle(G, "test.gpickle")
>>> G = nx.read_gpickle("test.gpickle")
1 https://docs.python.org/2/library/pickle.html
References
9.6.3 networkx.readwrite.gpickle.write_gpickle
Examples
>>> G = nx.path_graph(4)
>>> nx.write_gpickle(G, "test.gpickle")
References
9.7 GraphML
9.7.1 GraphML
Unlike many other file formats for graphs, GraphML does not use a custom syntax. Instead, it is based on XML and
hence ideally suited as a common denominator for all kinds of services generating, archiving, or processing graphs.”
http://graphml.graphdrawing.org/
Format
GraphML is an XML format. See http://graphml.graphdrawing.org/specification.html for the specification and http:
//graphml.graphdrawing.org/primer/graphml-primer.html for examples.
9.7.2 networkx.readwrite.graphml.read_graphml
Notes
Default node and edge attributes are not propagated to each node and edge. They can be obtained from G.
graph and applied to node and edge attributes if desired using something like this:
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 networkx.readwrite.graphml.write_graphml
Examples
>>> G = nx.path_graph(4)
>>> nx.write_graphml_lxml(G, "fourpath.graphml") # doctest: +SKIP
Notes
This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges,
nested graphs, or ports.
9.7.4 networkx.readwrite.graphml.generate_graphml
Examples
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed =
Notes
This implementation does not support mixed graphs (directed and unidirected edges together) hyperedges,
nested graphs, or ports.
9.7.5 networkx.readwrite.graphml.parse_graphml
Examples
>>> G = nx.path_graph(4)
>>> linefeed = chr(10) # linefeed =
>>> s = linefeed.join(nx.generate_graphml(G))
>>> H = nx.parse_graphml(s)
Notes
Default node and edge attributes are not propagated to each node and edge. They can be obtained from G.
graph and applied to node and edge attributes if desired using something like this:
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.
9.8 JSON
9.8.2 networkx.readwrite.json_graph.node_link_data
node_link_data(G, attrs=None)
Returns data in node-link format that is suitable for JSON serialization and use in Javascript documents.
Parameters
• G (NetworkX graph)
• attrs (dict) – A dictionary that contains five keys ‘source’, ‘target’, ‘name’, ‘key’ and ‘link’.
The corresponding values provide the attribute names for storing NetworkX-internal graph
data. The values should be unique. Default value:
If some user-defined graph data use these attribute names as data keys, they may be silently
dropped.
Returns data – A dictionary with node-link formatted data.
Return type dict
Raises NetworkXError – If values in attrs are not unique.
Examples
Notes
Graph, node, and link attributes are stored in this format. Note that attribute keys will be converted to strings in
order to comply with JSON.
Attribute ‘key’ is only used for multigraphs.
See also:
node_link_graph(), adjacency_data(), tree_data()
9.8.3 networkx.readwrite.json_graph.node_link_graph
Examples
Notes
9.8.4 networkx.readwrite.json_graph.adjacency_data
Examples
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.
See also:
adjacency_graph(), node_link_data(), tree_data()
9.8.5 networkx.readwrite.json_graph.adjacency_graph
Examples
Notes
9.8.6 networkx.readwrite.json_graph.cytoscape_data
cytoscape_data(G, attrs=None)
Returns data in Cytoscape JSON format (cyjs).
Parameters G (NetworkX Graph)
Returns data – A dictionary with cyjs formatted data.
Return type dict
Raises NetworkXError – If values in attrs are not unique.
9.8.7 networkx.readwrite.json_graph.cytoscape_graph
cytoscape_graph(data, attrs=None)
9.8.8 networkx.readwrite.json_graph.tree_data
• attrs (dict) – A dictionary that contains two keys ‘id’ and ‘children’. The corresponding
values provide the attribute names for storing NetworkX-internal graph data. The values
should be unique. Default value: dict(id='id', children='children').
If some user-defined graph data use these attribute names as data keys, they may be silently
dropped.
Returns data – A dictionary with node-link formatted data.
Return type dict
Raises NetworkXError – If values in attrs are not unique.
Examples
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.
See also:
tree_graph(), node_link_data(), node_link_data()
9.8.9 networkx.readwrite.json_graph.tree_graph
Examples
Notes
9.8.10 networkx.readwrite.json_graph.jit_data
jit_data(G, indent=None)
Returns data in JIT JSON format.
Parameters
• G (NetworkX Graph)
• indent (optional, default=None) – If indent is a non-negative integer, then JSON array el-
ements and object members will be pretty-printed with that indent level. An indent level
of 0, or negative, will only insert newlines. None (the default) selects the most compact
representation.
Returns data
Return type JIT JSON string
9.8.11 networkx.readwrite.json_graph.jit_graph
jit_graph(data, create_using=None)
Read a graph from JIT JSON.
Parameters
• data (JSON Graph Object)
• create_using (Networkx Graph, optional (default: Graph())) – Return graph of this type.
The provided instance will be cleared.
Returns G
Return type NetworkX Graph built from create_using if provided.
9.9 LEDA
9.9.1 Format
See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
9.9.2 networkx.readwrite.leda.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
Return type NetworkX graph
Examples
G=nx.read_leda(‘file.leda’)
References
9.9.3 networkx.readwrite.leda.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
Return type NetworkX graph
Examples
G=nx.parse_leda(string)
References
9.10 YAML
9.10.1 YAML
Format
http://pyyaml.org/wiki/PyYAML
9.10.2 networkx.readwrite.nx_yaml.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 languages1 .
Parameters path (file or string) – File or filename to read. Filenames ending in .gz or .bz2 will be
uncompressed.
Returns G
Return type NetworkX graph
Examples
>>> G=nx.path_graph(4)
>>> nx.write_yaml(G,'test.yaml')
>>> G=nx.read_yaml('test.yaml')
References
9.10.3 networkx.readwrite.nx_yaml.write_yaml
Notes
To use encoding on the output file include e.g. encoding='utf-8' in the keyword arguments.
1 http://www.yaml.org
1 http://www.yaml.org
Examples
>>> G=nx.path_graph(4)
>>> nx.write_yaml(G,'test.yaml')
References
9.11 SparseGraph6
Functions for reading and writing graphs in the graph6 or sparse6 file formats.
According to the author of these formats,
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.
graph6 is suitable for small graphs, or large dense graphs. sparse6 is more space-efficient for large sparse
graphs.
—graph6 and sparse6 homepage
9.11.1 Graph6
networkx.readwrite.graph6.from_graph6_bytes
from_graph6_bytes(string)
Read a simple undirected graph in graph6 format from string.
Parameters string (string) – Data in graph6 format, without a trailing newline.
Returns G
Return type Graph
Raises
• NetworkXError – If the string is unable to be parsed in graph6 format
• ValueError – If any character c in the input string does not satisfy 63 <= ord(c) <
127.
Examples
>>> G = nx.from_graph6_bytes(b'A_')
>>> sorted(G.edges())
[(0, 1)]
See also:
read_graph6(), write_graph6()
References
networkx.readwrite.graph6.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 – If the file contains multiple lines then a list of graphs is returned
Return type Graph or list of Graphs
Raises NetworkXError – If the string is unable to be parsed in graph6 format
Examples
You can read a graph6 file by giving the path to the file:
You can also read a graph6 file by giving an open file-like object:
See also:
from_graph6_bytes(), write_graph6()
References
networkx.readwrite.graph6.to_graph6_bytes
Examples
See also:
from_graph6_bytes(), read_graph6(), write_graph6_bytes()
Notes
References
networkx.readwrite.graph6.write_graph6
• ValueError – If the graph has at least 2 ** 36 nodes; the graph6 format is only defined
for graphs of order less than 2 ** 36.
Examples
See also:
from_graph6_bytes(), read_graph6()
Notes
The function writes a newline character after writing the encoding of the graph.
The format does not support edge or node labels, parallel edges or self loops. If self loops are present they are
silently ignored.
References
9.11.2 Sparse6
networkx.readwrite.sparse6.from_sparse6_bytes
from_sparse6_bytes(string)
Read an undirected graph in sparse6 format from string.
Parameters string (string) – Data in sparse6 format
Returns G
Return type Graph
Raises NetworkXError – If the string is unable to be parsed in sparse6 format
Examples
>>> G = nx.from_sparse6_bytes(b':A_')
>>> sorted(G.edges())
[(0, 1), (0, 1), (0, 1)]
See also:
read_sparse6(), write_sparse6()
References
networkx.readwrite.sparse6.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 – If the file contains multiple lines then a list of graphs is returned
Return type Graph/Multigraph or list of Graphs/MultiGraphs
Raises NetworkXError – If the string is unable to be parsed in sparse6 format
Examples
You can read a sparse6 file by giving the path to the file:
>>> import tempfile
>>> with tempfile.NamedTemporaryFile() as f:
... _ = f.write(b'>>sparse6<<:An\n')
... _ = f.seek(0)
... G = nx.read_sparse6(f.name)
>>> list(G.edges())
[(0, 1)]
You can also read a sparse6 file by giving an open file-like object:
>>> import tempfile
>>> with tempfile.NamedTemporaryFile() as f:
... _ = f.write(b'>>sparse6<<:An\n')
... _ = f.seek(0)
... G = nx.read_sparse6(f)
>>> list(G.edges())
[(0, 1)]
See also:
read_sparse6(), from_sparse6_bytes()
References
networkx.readwrite.sparse6.to_sparse6_bytes
Parameters
• G (Graph (undirected))
• nodes (list or iterable) – Nodes are labeled 0. . . n-1 in the order provided. If None the
ordering given by G.nodes() is used.
• header (bool) – If True add ‘>>sparse6<<’ bytes to head of data.
Raises
• NetworkXNotImplemented – If the graph is directed.
• ValueError – If the graph has at least 2 ** 36 nodes; the sparse6 format is only de-
fined for graphs of order less than 2 ** 36.
Examples
See also:
to_sparse6_bytes(), read_sparse6(), write_sparse6_bytes()
Notes
References
networkx.readwrite.sparse6.write_sparse6
Examples
You can write a sparse6 file by giving the path to the file:
You can also write a sparse6 file by giving an open file-like object:
See also:
read_sparse6(), from_sparse6_bytes()
Notes
References
9.12 Pajek
9.12.1 Pajek
Format
9.12.2 networkx.readwrite.pajek.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
Return type NetworkX MultiGraph or MultiDiGraph.
Examples
>>> G=nx.path_graph(4)
>>> nx.write_pajek(G, "test.net")
>>> G=nx.read_pajek("test.net")
>>> G1=nx.Graph(G)
References
9.12.3 networkx.readwrite.pajek.write_pajek
Examples
>>> G=nx.path_graph(4)
>>> nx.write_pajek(G, "test.net")
Warning: Optional node attributes and edge attributes must be non-empty strings. Otherwise it will not be
written into the file. You will need to convert those attributes to strings if you want to keep them.
References
9.12.4 networkx.readwrite.pajek.parse_pajek
parse_pajek(lines)
Parse Pajek format graph from string or iterable.
Parameters lines (string or iterable) – Data in Pajek format.
Returns G
Return type NetworkX graph
See also:
read_pajek()
9.12.5 networkx.readwrite.pajek.generate_pajek
generate_pajek(G)
Generate lines in Pajek graph format.
Parameters G (graph) – A Networkx graph
References
9.13.1 Shapefile
9.13.2 networkx.readwrite.nx_shp.read_shp
Returns G
Return type NetworkX graph
Raises
• ImportError – If ogr module is not available.
• RuntimeError – If file cannot be open or read.
• NetworkXError – If strict=True and feature is missing geometry or GeometryType is not
supported.
Examples
References
9.13.3 networkx.readwrite.nx_shp.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 software1 .”
Parameters outdir (directory path) – Output directory for the two shapefiles.
Returns
Return type None
Examples
References
1 https://en.wikipedia.org/wiki/Shapefile
TEN
DRAWING
NetworkX provides basic functionality for visualizing graphs, but its main goal is to enable graph analysis rather than
perform graph visualization. In the future, graph visualization functionality may be removed from NetworkX or only
available as an add-on package.
Proper graph visualization is hard, and we highly recommend that people visualize their graphs with tools dedicated to
that task. Notable examples of dedicated and fully-featured graph visualization tools are Cytoscape, Gephi, Graphviz
and, for LaTeX typesetting, PGF/TikZ. To use these and other such tools, you should export your NetworkX graph into
a format that can be read by those tools. For example, Cytoscape can read the GraphML format, and so, networkx.
write_graphml(G) might be an appropriate choice.
10.1 Matplotlib
10.1.1 Matplotlib
661
NetworkX Reference, Release 2.3rc1.dev20190222214247
10.1.2 networkx.drawing.nx_pylab.draw
Examples
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
See also:
draw_networkx(), draw_networkx_nodes(), draw_networkx_edges(),
draw_networkx_labels(), draw_networkx_edge_labels()
Notes
This function has the same name as pylab.draw and pyplot.draw so beware when using
10.1.3 networkx.drawing.nx_pylab.draw_networkx
Draw the graph with Matplotlib with options for node positions, labeling, titles, and many other drawing fea-
tures. See draw() for simple drawing without labels or axes.
Parameters
• G (graph) – A networkx graph
• pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If
not specified a spring layout positioning will be computed. See networkx.drawing.
layout for functions that compute node positions.
• arrows (bool, optional (default=True)) – For directed graphs, if True draw arrowheads.
Note: Arrows will be the same color as edges.
• arrowstyle (str, optional (default=’-|>’)) – For directed graphs, choose the style of the
arrowsheads. See :py:class: matplotlib.patches.ArrowStyle for more options.
• arrowsize (int, optional (default=10)) – For directed graphs, choose the size of the
arrow head head’s length and width. See :py:class: matplotlib.patches.
FancyArrowPatch for attribute mutation_scale for more info.
• with_labels (bool, optional (default=True)) – Set to True to draw labels on the nodes.
• ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes.
• nodelist (list, optional (default G.nodes())) – Draw only specified nodes
• edgelist (list, optional (default=G.edges())) – Draw only specified edges
• node_size (scalar or array, optional (default=300)) – Size of nodes. If an array is specified
it must be the same length as nodelist.
• node_color (color string, or array of floats, (default=’#1f78b4’)) – Node color. Can be
a single color format string, or a sequence of colors with the same length as nodelist. If
numeric values are specified they will be mapped to colors using the cmap and vmin,vmax
parameters. See matplotlib.scatter for more details.
• node_shape (string, optional (default=’o’)) – The shape of the node. Specification is as
matplotlib.scatter marker, one of ‘so^>v<dph8’.
• alpha (float, optional (default=1.0)) – The node and edge transparency
• cmap (Matplotlib colormap, optional (default=None)) – Colormap for mapping intensities
of nodes
• vmin,vmax (float, optional (default=None)) – Minimum and maximum for node colormap
scaling
• linewidths ([None | scalar | sequence]) – Line width of symbol border (default =1.0)
• width (float, optional (default=1.0)) – Line width of edges
• edge_color (color string, or array of floats (default=’r’)) – Edge color. Can be a single color
format string, 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.
• edge_cmap (Matplotlib colormap, optional (default=None)) – Colormap for mapping in-
tensities of edges
• edge_vmin,edge_vmax (floats, optional (default=None)) – Minimum and maximum for
edge colormap scaling
• style (string, optional (default=’solid’)) – Edge line style (solid|dashed|dotted,dashdot)
Notes
For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False.
Examples
>>> G = nx.dodecahedral_graph()
>>> nx.draw(G)
>>> nx.draw(G, pos=nx.spring_layout(G)) # use spring layout
10.1.4 networkx.drawing.nx_pylab.draw_networkx_nodes
• node_color (color string, or array of floats) – Node color. Can be a single color format
string (default=’#1f78b4’), or a sequence of colors with the same length as nodelist. If
numeric values are specified they will be mapped to colors using the cmap and vmin,vmax
parameters. See matplotlib.scatter for more details.
• node_shape (string) – The shape of the node. Specification is as matplotlib.scatter marker,
one of ‘so^>v<dph8’ (default=’o’).
• alpha (float or array of floats) – The node transparency. This can be a single alpha value
(default=1.0), in which case it will be applied to all the nodes of color. Otherwise, if it is
an array, the elements of alpha will be applied to the colors in order (cycling through alpha
multiple times if necessary).
• cmap (Matplotlib colormap) – Colormap for mapping intensities of nodes (default=None)
• vmin,vmax (floats) – Minimum and maximum for node colormap scaling (default=None)
• linewidths ([None | scalar | sequence]) – Line width of symbol border (default =1.0)
• edgecolors ([None | scalar | sequence]) – Colors of node borders (default = node_color)
• label ([None| string]) – Label for legend
Returns PathCollection of the nodes.
Return type matplotlib.collections.PathCollection
Examples
>>> G = nx.dodecahedral_graph()
>>> nodes = nx.draw_networkx_nodes(G, pos=nx.spring_layout(G))
10.1.5 networkx.drawing.nx_pylab.draw_networkx_edges
• 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 (de-
fault=None)
• edge_vmin,edge_vmax (floats) – Minimum and maximum for edge colormap scaling (de-
fault=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.
Note: Arrows will be the same color as edges.
• arrowstyle (str, optional (default=’-|>’)) – For directed graphs, choose the style of the
arrow heads. See :py:class: matplotlib.patches.ArrowStyle for more options.
• arrowsize (int, optional (default=10)) – For directed graphs, choose the size of the
arrow head head’s length and width. See :py:class: matplotlib.patches.
FancyArrowPatch for attribute mutation_scale for more info.
• label ([None| string]) – Label for legend
Returns
• matplotlib.collection.LineCollection – LineCollection of the edges
• list of matplotlib.patches.FancyArrowPatch – FancyArrowPatch instances of the di-
rected edges
• Depending whether the drawing includes arrows or not.
Notes
For directed graphs, arrows are drawn at the head end. Arrows can be turned off with keyword arrows=False.
Be sure to include node_size as a keyword argument; arrows are drawn considering the size of nodes.
Examples
>>> G = nx.dodecahedral_graph()
>>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> G = nx.DiGraph()
>>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
>>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
>>> alphas = [0.3, 0.4, 0.5]
>>> for i, arc in enumerate(arcs): # change alpha values of arcs
... arc.set_alpha(alphas[i])
10.1.6 networkx.drawing.nx_pylab.draw_networkx_labels
Examples
>>> G = nx.dodecahedral_graph()
>>> labels = nx.draw_networkx_labels(G, pos=nx.spring_layout(G))
10.1.7 networkx.drawing.nx_pylab.draw_networkx_edge_labels
• pos (dictionary) – A dictionary with nodes as keys and positions as values. Positions should
be sequences of length 2.
• ax (Matplotlib Axes object, optional) – Draw the graph in the specified Matplotlib axes.
• alpha (float) – The text transparency (default=1.0)
• edge_labels (dictionary) – Edge labels in a dictionary keyed by edge two-tuple of text labels
(default=None). Only labels for the keys in the dictionary are drawn.
• label_pos (float) – Position of edge label along edge (0=head, 0.5=center, 1=tail)
• font_size (int) – Font size for text labels (default=12)
• font_color (string) – Font color string (default=’k’ black)
• font_weight (string) – Font weight (default=’normal’)
• font_family (string) – Font family (default=’sans-serif’)
• bbox (Matplotlib bbox) – Specify text box shape and colors.
• clip_on (bool) – Turn on clipping at axis boundaries (default=True)
Returns dict of labels keyed on the edges
Return type dict
Examples
>>> G = nx.dodecahedral_graph()
>>> edge_labels = nx.draw_networkx_edge_labels(G, pos=nx.spring_layout(G))
10.1.8 networkx.drawing.nx_pylab.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 exception of the pos parameter which is not used by this function.
10.1.9 networkx.drawing.nx_pylab.draw_kamada_kawai
draw_kamada_kawai(G, **kwargs)
Draw the graph G with a Kamada-Kawai force-directed layout.
Parameters
• G (graph) – A networkx graph
10.1.10 networkx.drawing.nx_pylab.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 exception of the pos parameter which is not used by this function.
10.1.11 networkx.drawing.nx_pylab.draw_spectral
draw_spectral(G, **kwargs)
Draw the graph G with a spectral 2D layout.
Using the unnormalized Laplacion, the layout shows possible clusters of nodes which are an approximation of
the ratio cut. The positions are the entries of the second and third eigenvectors corresponding to the ascending
eigenvalues starting from the second one.
Parameters
• G (graph) – A networkx graph
• kwargs (optional keywords) – See networkx.draw_networkx() for a description of optional
keywords, with the exception of the pos parameter which is not used by this function.
10.1.12 networkx.drawing.nx_pylab.draw_spring
draw_spring(G, **kwargs)
Draw the graph G with a spring layout.
Parameters
• G (graph) – A networkx graph
• kwargs (optional keywords) – See networkx.draw_networkx() for a description of optional
keywords, with the exception of the pos parameter which is not used by this function.
10.1.13 networkx.drawing.nx_pylab.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 exception of the pos parameter which is not used by this function.
Examples
>>> G = nx.complete_graph(5)
>>> A = nx.nx_agraph.to_agraph(G)
>>> H = nx.nx_agraph.from_agraph(A)
See also:
Pygraphviz http://pygraphviz.github.io/
10.2.2 networkx.drawing.nx_agraph.from_agraph
from_agraph(A, create_using=None)
Returns a NetworkX Graph or DiGraph from a PyGraphviz graph.
Parameters
• A (PyGraphviz AGraph) – A graph created with PyGraphviz
• create_using (NetworkX graph constructor, optional (default=nx.Graph)) – Graph type to
create. If graph instance, then cleared before populated.
Examples
>>> K5 = nx.complete_graph(5)
>>> A = nx.nx_agraph.to_agraph(K5)
>>> G = nx.nx_agraph.from_agraph(A)
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.
10.2.3 networkx.drawing.nx_agraph.to_agraph
to_agraph(N)
Returns a pygraphviz graph from a NetworkX graph N.
Parameters N (NetworkX graph) – A graph created with NetworkX
Examples
>>> K5 = nx.complete_graph(5)
>>> A = nx.nx_agraph.to_agraph(K5)
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.
10.2.4 networkx.drawing.nx_agraph.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.5 networkx.drawing.nx_agraph.read_dot
read_dot(path)
Returns a NetworkX graph from a dot file on path.
Parameters path (file or string) – File name or file handle to read.
10.2.6 networkx.drawing.nx_agraph.graphviz_layout
Examples
>>> G = nx.petersen_graph()
>>> pos = nx.nx_agraph.graphviz_layout(G)
>>> pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
Notes
10.2.7 networkx.drawing.nx_agraph.pygraphviz_layout
Examples
>>> G = nx.petersen_graph()
>>> pos = nx.nx_agraph.graphviz_layout(G)
>>> pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
Notes
If you use complex node objects, they may have the same string representation and GraphViz could treat them
as the same node. The layout may assign both nodes a single location. See Issue #1568 If this occurs in your
case, consider relabeling the nodes just for the layout computation using something similar to:
H = nx.convert_node_labels_to_integers(G, label_attribute=’node_label’) H_layout =
nx.nx_agraph.pygraphviz_layout(G, prog=’dot’) G_layout = {H.nodes[n][‘node_label’]: p for
n, p in H_layout.items()}
10.3.1 Pydot
Import and export NetworkX graphs in Graphviz dot format using pydot.
Either this module or nx_agraph can be used to interface with graphviz.
See also:
pydot https://github.com/erocarrera/pydot
Graphviz https://www.graphviz.org
DOT
10.3.2 networkx.drawing.nx_pydot.from_pydot
from_pydot(P)
Returns a NetworkX graph from a Pydot graph.
Parameters P (Pydot graph) – A graph created with Pydot
Returns G – A MultiGraph or MultiDiGraph.
Return type NetworkX multigraph
Examples
>>> K5 = nx.complete_graph(5)
>>> A = nx.nx_pydot.to_pydot(K5)
>>> G = nx.nx_pydot.from_pydot(A) # return MultiGraph
10.3.3 networkx.drawing.nx_pydot.to_pydot
to_pydot(N)
Returns 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.nx_pydot.to_pydot(K5)
Notes
10.3.4 networkx.drawing.nx_pydot.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 networkx.drawing.nx_pydot.read_dot
read_dot(path)
Returns a NetworkX MultiGraph or MultiDiGraph from the dot file with the passed path.
If this file contains multiple graphs, only the first such graph is returned. All graphs _except_ the first are silently
ignored.
Parameters path (str or file) – Filename or file handle.
Returns G – A MultiGraph or MultiDiGraph.
Return type MultiGraph or MultiDiGraph
Notes
10.3.6 networkx.drawing.nx_pydot.graphviz_layout
Examples
>>> G = nx.complete_graph(4)
>>> pos = nx.nx_pydot.graphviz_layout(G)
>>> pos = nx.nx_pydot.graphviz_layout(G, prog='dot')
Notes
10.3.7 networkx.drawing.nx_pydot.pydot_layout
• prog (optional[str]) – Basename of the GraphViz command with which to layout this graph.
Defaults to neato: default GraphViz command for undirected graphs.
Returns Dictionary of positions keyed by node.
Return type dict
Examples
>>> G = nx.complete_graph(4)
>>> pos = nx.nx_pydot.pydot_layout(G)
>>> pos = nx.nx_pydot.pydot_layout(G, prog='dot')
Notes
If you use complex node objects, they may have the same string representation and GraphViz could treat them
as the same node. The layout may assign both nodes a single location. See Issue #1568 If this occurs in your
case, consider relabeling the nodes just for the layout computation using something similar to:
H = nx.convert_node_labels_to_integers(G, label_attribute=’node_label’) H_layout =
nx.nx_pydot.pydot_layout(G, prog=’dot’) G_layout = {H.nodes[n][‘node_label’]: p for n, p in
H_layout.items()}
10.4.1 Layout
10.4.2 networkx.drawing.layout.bipartite_layout
Examples
Notes
This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
10.4.3 networkx.drawing.layout.circular_layout
Examples
>>> G = nx.path_graph(4)
>>> pos = nx.circular_layout(G)
Notes
This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
10.4.4 networkx.drawing.layout.kamada_kawai_layout
Examples
>>> G = nx.path_graph(4)
>>> pos = nx.kamada_kawai_layout(G)
10.4.5 networkx.drawing.layout.random_layout
• center (array-like or None) – Coordinate pair around which to center the layout.
• dim (int) – Dimension of layout.
• seed (int, RandomState instance or None optional (default=None)) – Set the random state
for deterministic node layouts. If int, seed is the seed used by the random number gen-
erator, if numpy.random.RandomState instance, seed is the random number generator, if
None, the random number generator is the RandomState instance used by numpy.random.
Returns pos – A dictionary of positions keyed by node
Return type dict
Examples
>>> G = nx.lollipop_graph(4, 3)
>>> pos = nx.random_layout(G)
10.4.6 networkx.drawing.layout.rescale_layout
rescale_layout(pos, scale=1)
Returns scaled position array to (-scale, scale) in all axes.
The function acts on NumPy arrays which hold position information. Each position is one row of the array. The
dimension of the space equals the number of columns. Each coordinate in one column.
To rescale, the mean (center) is subtracted from each axis separately. Then all values are scaled so that the
largest magnitude value from all axes equals scale (thus, the aspect ratio is preserved). The resulting NumPy
Array is returned (order of rows unchanged).
Parameters
• pos (numpy array) – positions to be scaled. Each row is a position.
• scale (number (default: 1)) – The size of the resulting extent in all directions.
Returns pos – scaled positions. Each row is a position.
Return type numpy array
10.4.7 networkx.drawing.layout.shell_layout
Examples
>>> G = nx.path_graph(4)
>>> shells = [[0], [1, 2, 3]]
>>> pos = nx.shell_layout(G, shells)
Notes
This algorithm currently only works in two dimensions and does not try to minimize edge crossings.
10.4.8 networkx.drawing.layout.spring_layout
Examples
>>> G = nx.path_graph(4)
>>> pos = nx.spring_layout(G)
# The same using longer but equivalent function name >>> pos = nx.fruchterman_reingold_layout(G)
10.4.9 networkx.drawing.layout.spectral_layout
Examples
>>> G = nx.path_graph(4)
>>> pos = nx.spectral_layout(G)
Notes
Directed graphs will be considered as undirected graphs when positioning the nodes.
For larger graphs (>500 nodes) this will use the SciPy sparse eigenvalue solver (ARPACK).
ELEVEN
RANDOMNESS
Random Number Generators (RNGs) are often used when generating, drawing and computing properties or manipu-
lating networks. NetworkX provides functions which use one of two standard RNGs: NumPy’s package numpy.
random or Python’s built-in package random. They each provide the same algorithm for generating numbers
(Mersenne Twister). Their interfaces are similar (dangerously similar) and yet distinct. They each provide a global
default instance of their generator that is shared by all programs in a single session. For the most part you can use
the RNGs as NetworkX has them set up and you’ll get reasonable pseudorandom results (results that are statistically
random, but created in a deterministic manner).
Sometimes you want more control over how the numbers are generated. In particular, you need to set the seed of the
generator to make your results reproducible – either for scientific publication or for debugging. Both RNG packages
have easy functions to set the seed to any integer, thus determining the subsequent generated values. Since this package
(and many others) use both RNGs you may need to set the seed of both RNGs. Even if we strictly only used one of
the RNGs, you may find yourself using another package that uses the other. Setting the state of the two global RNGs
is as simple setting the seed of each RNG to an arbitrary integer:
Each NetworkX function that uses an RNG was written with one RNG package in mind. It either uses random
or numpy.random by default. But some users want to only use a single RNG for all their code. This seed
argument provides a mechanism so that any function can use a numpy.random RNG even if the function is written
for random. It works as follows.
The default behavior (when seed=None) is to use the global RNG for the function’s preferred package. If seed is set
to an integer value, a local RNG is created with the indicated seed value and is used for the duration of that function
(including any calls to other functions) and then discarded. Alternatively, you can specify seed=numpy.random
to ensure that the global numpy RNG is used whether the function expects it or not. Finally, you can provide a numpy
681
NetworkX Reference, Release 2.3rc1.dev20190222214247
RNG to be used by the function. The RNG is then available to use in other functions or even other package like
sklearn. In this way you can use a single RNG for all random numbers in your project.
While it is possible to assign seed a random-style RNG for NetworkX functions written for the random package
API, the numpy RNG interface has too many nice features for us to ensure a random-style RNG will work in all
functions. In practice, you can do most things using only random RNGs (useful if numpy is not available). But your
experience will be richer if numpy is available.
To summarize, you can easily ignore the seed argument and use the global RNGs. You can specify to use only the
numpy global RNG with seed=numpy.random. You can use a local RNG by providing an integer seed value. And
you can provide your own numpy RNG, reusing it for all functions. It is easier to use numpy RNGs if you want a
single RNG for your computations.
TWELVE
EXCEPTIONS
12.1 Exceptions
References
class NetworkXAlgorithmError
Exception for unexpected termination of algorithms.
class NetworkXUnfeasible
Exception raised by algorithms trying to solve a problem instance that has no feasible solution.
class NetworkXNoPath
Exception for algorithms that should return a path when running on graphs where such a path does not exist.
class NetworkXNoCycle
Exception for algorithms that should return a cycle when running on graphs where such a cycle does not exist.
class NodeNotFound
Exception raised if requested node is not present in the graph
class HasACycle
Raised if a graph has a cycle when an algorithm expects that it will have no cycles.
class NetworkXUnbounded
Exception raised by algorithms trying to solve a maximization or a minimization problem instance that is un-
bounded.
class NetworkXNotImplemented
Exception raised by algorithms not implemented for a type of graph.
1 Harary, F. and Read, R. “Is the Null Graph a Pointless Concept?” In Graphs and Combinatorics Conference, George Washington University.
683
NetworkX Reference, Release 2.3rc1.dev20190222214247
class AmbiguousSolution
Raised if more than one valid solution exists for an intermediary step of an algorithm.
In the face of ambiguity, refuse the temptation to guess. This may occur, for example, when trying to determine
the bipartite node sets in a disconnected bipartite graph when computing bipartite matchings.
class ExceededMaxIterations
Raised if a loop iterates too many times without breaking.
This may occur, for example, in an algorithm that computes progressively better approximations to a value but
exceeds an iteration bound specified by the user.
class PowerIterationFailedConvergence(num_iterations, *args, **kw)
Raised when the power iteration method fails to converge within a specified iteration limit.
num_iterations is the number of iterations that have been completed when this exception was raised.
THIRTEEN
UTILITIES
13.1.1 networkx.utils.misc.is_string_like
is_string_like(obj)
Check if obj is string.
13.1.2 networkx.utils.misc.flatten
flatten(obj, result=None)
Return flattened version of (possibly nested) iterable object.
685
NetworkX Reference, Release 2.3rc1.dev20190222214247
13.1.3 networkx.utils.misc.iterable
iterable(obj)
Return True if obj is iterable with a well-defined len().
13.1.4 networkx.utils.misc.is_list_of_ints
is_list_of_ints(intlist)
Return True if list is a list of ints.
13.1.5 networkx.utils.misc.make_str
make_str(x)
Returns the string representation of t.
13.1.6 networkx.utils.misc.generate_unique_node
generate_unique_node()
Generate a unique node label.
13.1.7 networkx.utils.misc.default_opener
default_opener(filename)
Opens filename using system’s default program.
Parameters filename (str) – The path of the file to be opened.
13.1.8 networkx.utils.misc.pairwise
pairwise(iterable, cyclic=False)
s -> (s0, s1), (s1, s2), (s2, s3), . . .
13.1.9 networkx.utils.misc.groups
groups(many_to_one)
Converts a many-to-one mapping into a one-to-many mapping.
many_to_one must be a dictionary whose keys and values are all hashable.
The return value is a dictionary mapping values from many_to_one to sets of keys from many_to_one that
have that value.
For example:
13.1.10 networkx.utils.misc.create_random_state
create_random_state(random_state=None)
Returns a numpy.random.RandomState instance depending on input.
Parameters random_state (int or RandomState instance or None optional (default=None)) – If int,
return a numpy.random.RandomState instance set with seed=int. if numpy.random.RandomState
instance, return it. if None or numpy.random, return the global random number generator used
by numpy.random.
UnionFind.union(*objects) Find the sets containing the objects and merge them all.
13.2.1 networkx.utils.union_find.UnionFind.union
UnionFind.union(*objects)
Find the sets containing the objects and merge them all.
Utilities for generating random numbers, random sequences, and random selections.
powerlaw_sequence(n[, exponent, seed]) Return sample sequence of length n from a power law
distribution.
cumulative_distribution(distribution) Returns normalized cumulative distribution from dis-
crete distribution.
discrete_sequence(n[, distribution, . . . ]) Return sample sequence of length n from a given dis-
crete distribution or discrete cumulative distribution.
zipf_rv(alpha[, xmin, seed]) Returns a random value chosen from the Zipf distribu-
tion.
random_weighted_sample(mapping, k[, seed]) Returns k items without replacement from a weighted
sample.
weighted_choice(mapping[, seed]) Returns a single element from a weighted sample.
13.3.1 networkx.utils.random_sequence.powerlaw_sequence
13.3.2 networkx.utils.random_sequence.cumulative_distribution
cumulative_distribution(distribution)
Returns normalized cumulative distribution from discrete distribution.
13.3.3 networkx.utils.random_sequence.discrete_sequence
13.3.4 networkx.utils.random_sequence.zipf_rv
𝑥−𝛼
𝑝(𝑥) = ,
𝜁(𝛼, 𝑥min )
Notes
The rejection algorithm generates random values for a the power-law distribution in uniformly bounded expected
time dependent on parameters. See1 for details on its operation.
Examples
References
13.3.5 networkx.utils.random_sequence.random_weighted_sample
random_weighted_sample(mapping, k, seed=None)
Returns k items without replacement from a weighted sample.
The input is a dictionary of items with weights as values.
1 Luc Devroye, Non-Uniform Random Variate Generation, Springer-Verlag, New York, 1986.
13.3.6 networkx.utils.random_sequence.weighted_choice
weighted_choice(mapping, seed=None)
Returns a single element from a weighted sample.
The input is a dictionary of items with weights as values.
13.4 Decorators
13.4.1 networkx.utils.decorators.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 argu-
ment.
• mode (str) – String for opening mode.
Returns _open_file – Function which cleanly executes the io.
Return type function
Examples
@open_file(0,'r')
def read_function(pathname):
pass
@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):
(continues on next page)
13.4.2 networkx.utils.decorators.not_implemented_for
not_implemented_for(*graph_types)
Decorator to mark algorithms as not implemented
Parameters graph_types (container of strings) – Entries must be one of ‘directed’,’undirected’,
‘multigraph’, ‘graph’.
Returns _require – The decorated function.
Return type function
Raises
• NetworkXNotImplemented
• If any of the packages cannot be imported
Notes
Multiple types are joined logically with “and”. For “or” use multiple @not_implemented_for() lines.
Examples
@not_implemnted_for('directed')
def sp_function(G):
pass
@not_implemnted_for('directed','multigraph')
def sp_np_function(G):
pass
13.4.3 networkx.utils.decorators.nodes_or_number
nodes_or_number(which_args)
Decorator to allow number of nodes or container of nodes.
Parameters which_args (int or sequence of ints) – Location of the node arguments in args. Even if
the argument is a named positional argument (with a default value), you must specify its index
as a positional argument. If more than one node argument is allowed, can be a list of locations.
Returns _nodes_or_numbers – Function which replaces int args with ranges.
Return type function
Examples
@nodes_or_number([0,1])
def grid_2d_graph(m1, m2, periodic=False):
pass
@nodes_or_number(1)
def full_rary_tree(r, n)
# r is a number. n can be a number of a list of nodes
pass
13.4.4 networkx.utils.decorators.preserve_random_state
preserve_random_state(func)
Decorator to preserve the numpy.random state during a function.
Parameters func (function) – function around which to preserve the random state.
Returns wrapper – Function which wraps the input function by saving the state before calling the
function and restoring the function afterward.
Return type function
Examples
Notes
13.4.5 networkx.utils.decorators.random_state
random_state(random_state_index)
Decorator to generate a numpy.random.RandomState instance.
Argument position random_state_index is processed by create_random_state. The result is a
numpy.random.RandomState instance.
Parameters random_state_index (int) – Location of the random_state argument in args that is to
be used to generate the numpy.random.RandomState instance. Even if the argument is a named
positional argument (with a default value), you must specify its index as a positional argument.
Returns _random_state – Function whose random_state keyword argument is a RandomState in-
stance.
Examples
@np_random_state(0)
def random_float(random_state=None):
return random_state.rand()
@np_random_state(1)
def random_array(dims, random_state=1):
return random_state.rand(*dims)
See also:
py_random_state()
13.5.1 networkx.utils.rcm.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)1 .
Parameters
• G (graph) – A NetworkX graph
• heuristic (function, optional) – Function to choose starting node for RCM algorithm. If
None a node from a pseudo-peripheral pair is used. A user-defined function can be supplied
that takes a graph object and returns a single node.
Returns nodes – Generator of nodes in Cuthill-McKee ordering.
Return type generator
Examples
See also:
reverse_cuthill_mckee_ordering()
Notes
References
13.5.2 networkx.utils.rcm.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)1 .
Parameters
• G (graph) – A NetworkX graph
• heuristic (function, optional) – Function to choose starting node for RCM algorithm. If
None a node from a pseudo-peripheral pair is used. A user-defined function can be supplied
that takes a graph object and returns a single node.
Returns nodes – Generator of nodes in reverse Cuthill-McKee ordering.
Return type generator
Examples
2 Steven S. Skiena. 1997. The Algorithm Design Manual. Springer-Verlag New York, Inc., New York, NY, USA.
1 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
See also:
cuthill_mckee_ordering()
Notes
References
13.6.1 networkx.utils.contextmanagers.reversed
reversed(G)
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.
2 Steven S. Skiena. 1997. The Algorithm Design Manual. Springer-Verlag New York, Inc., New York, NY, USA.
FOURTEEN
GLOSSARY
dictionary A Python dictionary maps keys to values. Also known as “hashes”, or “associative arrays” in other pro-
gramming languages. See https://docs.python.org/2/tutorial/datastructures.html#dictionaries
edge Edges are either two-tuples of nodes (u, v) or three tuples of nodes with an edge attribute dictionary (u,
v, dict).
ebunch An iteratable container of edge tuples like a list, iterator, or file.
edge attribute Edges can have arbitrary Python objects assigned as attributes by using keyword/value pairs when
adding an edge assigning to the G.edges[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 https://docs.python.org/2/glossary.html
nbunch An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph,
etc.. To filter an nbunch so that only nodes actually in G appear, use G.nbunch_iter(nbunch).
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.nodes[n] attribute dictionary for the specified node n.
695
NetworkX Reference, Release 2.3rc1.dev20190222214247
TUTORIAL
By definition, a Graph is a collection of nodes (vertices) along with identified pairs of nodes (called edges, links,
etc). In NetworkX, nodes can be any hashable object e.g., a text string, an image, an XML object, another Graph, a
customized node object, etc.
Note: Python’s None object should not be used as a node as it determines whether optional function arguments have
been assigned in many functions.
A.2 Nodes
The graph G can be grown in several ways. NetworkX includes many graph generator functions and facilities to read
and write graphs in many formats. To get started though we’ll look at simple manipulations. You can add one node at
a time,
>>> G.add_node(1)
or add any iterable container of nodes. You can also add nodes along with node attributes if your container yields
2-tuples (node, node_attribute_dict). Node attributes are discussed further below.
>>> H = nx.path_graph(10)
>>> G.add_nodes_from(H)
Note that G now contains the nodes of H as nodes of G. In contrast, you could use the graph H as a node in G.
>>> G.add_node(H)
697
NetworkX Reference, Release 2.3rc1.dev20190222214247
The graph G now contains H as a node. This flexibility is very powerful as it allows graphs of graphs, graphs of files,
graphs of functions and much more. It is worth thinking about how to structure your application so that the nodes are
useful entities. Of course you can always use a unique identifier in G and have a separate dictionary keyed by identifier
to the node information if you prefer.
Note: You should not change the node object if the hash depends on its contents.
A.3 Edges
>>> G.add_edge(1, 2)
>>> e = (2, 3)
>>> G.add_edge(*e) # unpack edge tuple*
or by adding any ebunch of edges. An ebunch is any iterable container of edge-tuples. An edge-tuple can be a
2-tuple of nodes or a 3-tuple with 2 nodes followed by an edge attribute dictionary, e.g., (2, 3, {'weight':
3.1415}). Edge attributes are discussed further below
>>> G.add_edges_from(H.edges)
There are no complaints when adding existing nodes or edges. For example, after removing all nodes and edges,
>>> G.clear()
we add new nodes/edges and NetworkX quietly ignores any that are already present.
At this stage the graph G consists of 8 nodes and 3 edges, as can be seen by:
>>> G.number_of_nodes()
8
>>> G.number_of_edges()
3
We can examine the nodes and edges. Four basic graph properties facilitate reporting: G.nodes, G.edges, G.adj
and G.degree. These are set-like views of the nodes, edges, neighbors (adjacencies), and degrees of nodes in a
graph. They offer a continually updated read-only view into the graph structure. They are also dict-like in that you
can look up node and edge data attributes via the views and iterate with data attributes using methods .items(),
.data('span'). If you want a specific container type instead of a view, you can specify one. Here we use lists,
though sets, dicts, tuples and other containers may be better in other contexts.
>>> list(G.nodes)
[1, 2, 3, 'spam', 's', 'p', 'a', 'm']
>>> list(G.edges)
[(1, 2), (1, 3), (3, 'm')]
>>> list(G.adj[1]) # or list(G.neighbors(1))
[2, 3]
>>> G.degree[1] # the number of edges incident to 1
2
One can specify to report the edges and degree from a subset of all nodes using an nbunch. An nbunch is any of: None
(meaning all nodes), a node, or an iterable container of nodes that is not itself a node in the graph.
One can remove nodes and edges from the graph in a similar fashion to adding. Use meth-
ods Graph.remove_node(), Graph.remove_nodes_from(), Graph.remove_edge() and Graph.
remove_edges_from(), e.g.
>>> G.remove_node(2)
>>> G.remove_nodes_from("spam")
>>> list(G.nodes)
[1, 3, 'spam']
>>> G.remove_edge(1, 3)
When creating a graph structure by instantiating one of the graph classes you can specify data in several formats.
>>> G.add_edge(1, 2)
>>> H = nx.DiGraph(G) # create a DiGraph using the connections from G
>>> list(H.edges())
[(1, 2), (2, 1)]
>>> edgelist = [(0, 1), (1, 2), (2, 3)]
>>> H = nx.Graph(edgelist)
You might notice that nodes and edges are not specified as NetworkX objects. This leaves you free to use meaningful
items as nodes and edges. The most common choices are numbers or strings, but a node can be any hashable object
(except None), and an edge can be associated with any object x using G.add_edge(n1, n2, object=x).
As an example, n1 and n2 could be protein objects from the RCSB Protein Data Bank, and x could refer to an XML
record of publications detailing experimental observations of their interaction.
We have found this power quite useful, but its abuse can lead to unexpected surprises unless one is familiar with Python.
If in doubt, consider using convert_node_labels_to_integers() to obtain a more traditional graph with
integer labels.
In addition to the views Graph.edges(), and Graph.adj(), access to edges and neighbors is possible using
subscript notation.
You can get/set the attributes of an edge using subscript notation if the edge already exists.
>>> G.add_edge(1, 3)
>>> G[1][3]['color'] = "blue"
>>> G.edges[1, 2]['color'] = "red"
Fast examination of all (node, adjacency) pairs is achieved using G.adjacency(), or G.adj.items(). Note
that for undirected graphs, adjacency iteration sees each edge twice.
>>> FG = nx.Graph()
>>> FG.add_weighted_edges_from([(1, 2, 0.125), (1, 3, 0.75), (2, 4, 1.2), (3, 4, 0.
˓→375)])
Attributes such as weights, labels, colors, or whatever Python object you like, can be attached to graphs, nodes, or
edges.
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 attributes can be added or changed using add_edge, add_node or direct
manipulation of the attribute dictionaries named G.graph, G.nodes, and G.edges for a graph G.
>>> G = nx.Graph(day="Friday")
>>> G.graph
{'day': 'Friday'}
Note that adding a node to G.nodes does not add it to the graph, use G.add_node() to add new nodes. Similarly
for edges.
The special attribute weight should be numeric as it is used by algorithms requiring weighted edges.
The DiGraph class provides additional properties specific to directed edges, e.g., DiGraph.out_edges(),
DiGraph.in_degree(), DiGraph.predecessors(), DiGraph.successors() etc. To allow algo-
rithms to work with both classes easily, the directed versions of neighbors() is equivalent to successors()
while degree reports the sum of in_degree and out_degree even though that may feel inconsistent at times.
>>> DG = nx.DiGraph()
>>> DG.add_weighted_edges_from([(1, 2, 0.5), (3, 1, 0.75)])
>>> DG.out_degree(1, weight='weight')
0.5
>>> DG.degree(1, weight='weight')
1.25
>>> list(DG.successors(1))
[2]
>>> list(DG.neighbors(1))
[2]
Some algorithms work only for directed graphs and others are not well defined for directed graphs. Indeed the tendency
to lump directed and undirected graphs together is dangerous. If you want to treat a directed graph as undirected for
some measurement you should probably convert it using Graph.to_undirected() or with
A.8 Multigraphs
NetworkX provides classes for graphs which allow multiple edges between any pair of nodes. The MultiGraph
and MultiDiGraph classes allow you to add the same edge twice, possibly with different edge data. This can be
powerful for some applications, but many algorithms are not well defined on such graphs. Where results are well
defined, e.g., MultiGraph.degree() we provide the function. Otherwise you should convert to a standard graph
in a way that makes the measurement well defined.
>>> MG = nx.MultiGraph()
>>> MG.add_weighted_edges_from([(1, 2, 0.5), (1, 2, 0.75), (2, 3, 0.5)])
>>> dict(MG.degree(weight='weight'))
{1: 1.25, 2: 1.75, 3: 0.5}
>>> GG = nx.Graph()
>>> for n, nbrs in MG.adjacency():
... for nbr, edict in nbrs.items():
... minvalue = min([d['weight'] for d in edict.values()])
... GG.add_edge(n, nbr, weight = minvalue)
...
>>> nx.shortest_path(GG, 1, 3)
[1, 2, 3]
5. Reading a graph stored in a file using common graph formats, such as edge lists, adjacency lists, GML,
GraphML, pickle, LEDA and others.
For details on graph formats see Reading and writing graphs and for graph generator functions see Graph generators
The structure of G can be analyzed using various graph-theoretic functions such as:
>>> G = nx.Graph()
>>> G.add_edges_from([(1, 2), (1, 3)])
>>> G.add_node("spam") # adds node "spam"
>>> list(nx.connected_components(G))
[{1, 2, 3}, {'spam'}]
>>> sorted(d for n, d in G.degree())
[0, 1, 1, 2]
>>> nx.clustering(G)
{1: 0, 2: 0, 3: 0, 'spam': 0}
Some functions with large output iterate over (node, value) 2-tuples. These are easily stored in a dict structure if
you desire.
>>> sp = dict(nx.all_pairs_shortest_path(G))
>>> sp[3]
{3: [3], 1: [3, 1], 2: [3, 1, 2]}
NetworkX is not primarily a graph drawing package but basic drawing with Matplotlib as well as an interface to use
the open source Graphviz software package are included. These are part of the networkx.drawing module and
will be imported if possible.
First import Matplotlib’s plot interface (pylab works too)
You may find it useful to interactively test code using ipython -pylab, which combines the power of ipython and
matplotlib and provides a convenient interactive mode.
To test if the import of networkx.drawing was successful draw G using one of
>>> G = nx.petersen_graph()
>>> plt.subplot(121)
<matplotlib.axes._subplots.AxesSubplot object at ...>
>>> nx.draw(G, with_labels=True, font_weight='bold')
>>> plt.subplot(122)
<matplotlib.axes._subplots.AxesSubplot object at ...>
>>> nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight=
˓→'bold')
0 1
8
4 2
6
5 6 7
1
5 0
3
9 8
9
3
7
2 4
when drawing to an interactive display. Note that you may need to issue a Matplotlib
>>> plt.show()
command if you are not using matplotlib in interactive mode (see Matplotlib FAQ ).
>>> options = {
... 'node_color': 'black',
... 'node_size': 100,
... 'width': 3,
... }
>>> plt.subplot(221)
<matplotlib.axes._subplots.AxesSubplot object at ...>
>>> nx.draw_random(G, **options)
>>> plt.subplot(222)
<matplotlib.axes._subplots.AxesSubplot object at ...>
(continues on next page)
You can find additional options via draw_networkx() and layouts via layout. You can use multiple shells with
draw_shell().
>>> G = nx.dodecahedral_graph()
>>> shells = [[2, 3, 4, 5, 6], [8, 1, 0, 19, 18, 17, 16, 15, 14, 7], [9, 10, 11, 12,
˓→13]]
>>> nx.draw(G)
>>> plt.savefig("path.png")
writes to the file path.png in the local directory. If Graphviz and PyGraphviz or pydot, are available on your system,
you can also use nx_agraph.graphviz_layout(G) or nx_pydot.graphviz_layout(G) to get the node
positions, or write the graph in dot format for further processing.
[atlas] Ronald C. Read and Robin J. Wilson, An Atlas of Graphs. Oxford University Press, 1998.
707
NetworkX Reference, Release 2.3rc1.dev20190222214247
708 Bibliography
PYTHON MODULE INDEX
a 169
networkx.algorithms.approximation, 129 networkx.algorithms.bipartite.spectral,
networkx.algorithms.approximation.clique, 165
133 networkx.algorithms.boundary, 178
networkx.algorithms.bridges,
networkx.algorithms.approximation.clustering_coefficient, 180
135 networkx.algorithms.centrality, 301
networkx.algorithms.chains, 210
networkx.algorithms.approximation.connectivity,
129 networkx.algorithms.chordal, 211
networkx.algorithms.clique, 213
networkx.algorithms.approximation.dominating_set,
135 networkx.algorithms.cluster, 217
networkx.algorithms.coloring, 222
networkx.algorithms.approximation.independent_set,
136 networkx.algorithms.communicability_alg,
networkx.algorithms.approximation.kcomponents, 226
132 networkx.algorithms.community, 227
networkx.algorithms.community.asyn_fluid,
networkx.algorithms.approximation.matching,
137 233
networkx.algorithms.approximation.ramsey,networkx.algorithms.community.centrality,
138 235
networkx.algorithms.community.community_generators,
networkx.algorithms.approximation.steinertree,
138 228
networkx.algorithms.community.community_utils,
networkx.algorithms.approximation.treewidth,
139 237
networkx.algorithms.community.kclique,
networkx.algorithms.approximation.vertex_cover,
140 231
networkx.algorithms.assortativity, 140 networkx.algorithms.community.kernighan_lin,
networkx.algorithms.bipartite, 150 228
networkx.algorithms.bipartite.basic, 151 networkx.algorithms.community.label_propagation,
networkx.algorithms.bipartite.centrality, 232
170 networkx.algorithms.community.modularity_max,
networkx.algorithms.bipartite.cluster, 231
165 networkx.algorithms.community.quality,
networkx.algorithms.bipartite.covering, 234
178 networkx.algorithms.components, 238
networkx.algorithms.bipartite.generators,networkx.algorithms.connectivity, 252
173 networkx.algorithms.connectivity.connectivity,
networkx.algorithms.bipartite.matching, 265
155 networkx.algorithms.connectivity.cuts,
networkx.algorithms.bipartite.matrix, 273
157 networkx.algorithms.connectivity.disjoint_paths,
networkx.algorithms.bipartite.projection, 262
159 networkx.algorithms.connectivity.edge_augmentation,
networkx.algorithms.bipartite.redundancy, 252
709
NetworkX Reference, Release 2.3rc1.dev20190222214247
networkx.algorithms.reciprocity, 399
networkx.algorithms.connectivity.edge_kcomponents,
255 networkx.algorithms.richclub, 400
networkx.algorithms.connectivity.kcomponents,
networkx.algorithms.shortest_paths.astar,
259 436
networkx.algorithms.connectivity.kcutsets,
networkx.algorithms.shortest_paths.dense,
260 434
networkx.algorithms.connectivity.stoerwagner,
networkx.algorithms.shortest_paths.generic,
280 401
networkx.algorithms.connectivity.utils, networkx.algorithms.shortest_paths.unweighted,
281 406
networkx.algorithms.core, 282 networkx.algorithms.shortest_paths.weighted,
networkx.algorithms.covering, 285 411
networkx.algorithms.cuts, 290 networkx.algorithms.similarity, 437
networkx.algorithms.cycles, 286 networkx.algorithms.simple_paths, 444
networkx.algorithms.dag, 294 networkx.algorithms.smallworld, 448
networkx.algorithms.distance_measures, networkx.algorithms.smetric, 451
302 networkx.algorithms.sparsifiers, 452
networkx.algorithms.distance_regular, networkx.algorithms.structuralholes, 453
305 networkx.algorithms.swap, 455
networkx.algorithms.dominance, 307 networkx.algorithms.tournament, 457
networkx.algorithms.dominating, 308 networkx.algorithms.traversal.beamsearch,
networkx.algorithms.efficiency, 310 468
networkx.algorithms.euler, 311 networkx.algorithms.traversal.breadth_first_search,
networkx.algorithms.flow, 313 465
networkx.algorithms.graphical, 340 networkx.algorithms.traversal.depth_first_search,
networkx.algorithms.hierarchy, 344 460
networkx.algorithms.hybrid, 344 networkx.algorithms.traversal.edgebfs,
networkx.algorithms.isolate, 346 470
networkx.algorithms.isomorphism, 347 networkx.algorithms.traversal.edgedfs,
networkx.algorithms.isomorphism.isomorphvf2, 469
350 networkx.algorithms.tree.branchings, 474
networkx.algorithms.tree.coding, 477
networkx.algorithms.link_analysis.hits_alg,
365 networkx.algorithms.tree.mst, 482
networkx.algorithms.tree.operations, 481
networkx.algorithms.link_analysis.pagerank_alg,
361 networkx.algorithms.tree.recognition,
networkx.algorithms.link_prediction, 367 472
networkx.algorithms.triads, 486
networkx.algorithms.lowest_common_ancestors,
373 networkx.algorithms.vitality, 487
networkx.algorithms.matching, 375 networkx.algorithms.voronoi, 488
networkx.algorithms.minors, 377 networkx.algorithms.wiener, 489
networkx.algorithms.mis, 383
networkx.algorithms.node_classification, c
384 networkx.classes.function, 491
networkx.algorithms.node_classification.hmn,
networkx.classes.graphviews, 127
384 networkx.classes.ordered, 126
networkx.algorithms.node_classification.lgc,
networkx.convert, 595
385 networkx.convert_matrix, 598
networkx.algorithms.operators.all, 389
networkx.algorithms.operators.binary, d
387 networkx.drawing.layout, 675
networkx.algorithms.operators.product, networkx.drawing.nx_agraph, 670
391 networkx.drawing.nx_pydot, 672
networkx.algorithms.operators.unary, 386 networkx.drawing.nx_pylab, 661
networkx.algorithms.planarity, 395
e networkx.readwrite.nx_yaml, 649
networkx.exception, 683 networkx.readwrite.pajek, 657
networkx.readwrite.sparse6, 654
g networkx.relabel, 613
networkx.generators.atlas, 509
networkx.generators.classic, 510
u
networkx.generators.community, 563 networkx.utils, 685
networkx.generators.degree_seq, 539 networkx.utils.contextmanagers, 694
networkx.generators.directed, 546 networkx.utils.decorators, 689
networkx.generators.duplication, 537 networkx.utils.misc, 685
networkx.generators.ego, 559 networkx.utils.random_sequence, 687
networkx.generators.expanders, 518 networkx.utils.rcm, 692
networkx.generators.geometric, 550 networkx.utils.union_find, 687
networkx.generators.intersection, 561
networkx.generators.joint_degree_seq,
574
networkx.generators.lattice, 519
networkx.generators.line, 557
networkx.generators.mycielski, 576
networkx.generators.nonisomorphic_trees,
573
networkx.generators.random_clustered,
545
networkx.generators.random_graphs, 526
networkx.generators.small, 522
networkx.generators.social, 562
networkx.generators.spectral_graph_forge,
570
networkx.generators.stochastic, 560
networkx.generators.trees, 571
networkx.generators.triads, 574
l
networkx.linalg.algebraicconnectivity,
584
networkx.linalg.attrmatrix, 587
networkx.linalg.graphmatrix, 579
networkx.linalg.laplacianmatrix, 580
networkx.linalg.modularitymatrix, 591
networkx.linalg.spectrum, 583
r
networkx.readwrite.adjlist, 617
networkx.readwrite.edgelist, 624
networkx.readwrite.gexf, 630
networkx.readwrite.gml, 633
networkx.readwrite.gpickle, 638
networkx.readwrite.graph6, 651
networkx.readwrite.graphml, 639
networkx.readwrite.json_graph, 643
networkx.readwrite.leda, 648
networkx.readwrite.multiline_adjlist,
620
networkx.readwrite.nx_shp, 659
713
NetworkX Reference, Release 2.3rc1.dev20190222214247
714 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
B workx.generators.random_graphs), 530
balanced_tree() (in module net- bipartite_layout() (in module net-
workx.generators.classic), 511 workx.drawing.layout), 676
barabasi_albert_graph() (in module net- boundary_expansion() (in module net-
workx.generators.random_graphs), 533 workx.algorithms.cuts), 290
barbell_graph() (in module net- boykov_kolmogorov() (in module net-
workx.generators.classic), 511 workx.algorithms.flow), 327
bellman_ford_path() (in module net- branching_weight() (in module net-
workx.algorithms.shortest_paths.weighted), workx.algorithms.tree.branchings), 475
425 bridge_components() (in module net-
bellman_ford_path_length() (in module net- workx.algorithms.connectivity.edge_kcomponents),
workx.algorithms.shortest_paths.weighted), 257
425 bridges() (in module networkx.algorithms.bridges),
bellman_ford_predecessor_and_distance() 180
(in module net- build_auxiliary_edge_connectivity() (in
workx.algorithms.shortest_paths.weighted), module networkx.algorithms.connectivity.utils),
430 281
betweenness_centrality() (in module net- build_auxiliary_node_connectivity() (in
workx.algorithms.bipartite.centrality), 172 module networkx.algorithms.connectivity.utils),
betweenness_centrality() (in module net- 281
workx.algorithms.centrality), 192 build_residual_network() (in module net-
betweenness_centrality_subset() (in mod- workx.algorithms.flow), 331
ule networkx.algorithms.centrality), 194 bull_graph() (in module net-
bfs_beam_edges() (in module net- workx.generators.small), 524
workx.algorithms.traversal.beamsearch),
468 C
bfs_edges() (in module net- candidate_pairs_iter() (DiGraphMatcher
workx.algorithms.traversal.breadth_first_search), method), 355
465 candidate_pairs_iter() (GraphMatcher
bfs_predecessors() (in module net- method), 353
workx.algorithms.traversal.breadth_first_search), capacity_scaling() (in module net-
466 workx.algorithms.flow), 338
bfs_successors() (in module net- cartesian_product() (in module net-
workx.algorithms.traversal.breadth_first_search), workx.algorithms.operators.product), 391
467 categorical_edge_match() (in module net-
bfs_tree() (in module net- workx.algorithms.isomorphism), 356
workx.algorithms.traversal.breadth_first_search), categorical_multiedge_match() (in module
466 networkx.algorithms.isomorphism), 357
biadjacency_matrix() (in module net- categorical_node_match() (in module net-
workx.algorithms.bipartite.matrix), 157 workx.algorithms.isomorphism), 356
biconnected_component_edges() (in module caveman_graph() (in module net-
networkx.algorithms.components), 249 workx.generators.community), 564
biconnected_component_subgraphs() (in center() (in module net-
module networkx.algorithms.components), 250 workx.algorithms.distance_measures), 302
biconnected_components() (in module net- chain_decomposition() (in module net-
workx.algorithms.components), 248 workx.algorithms.chains), 210
bidirectional_dijkstra() (in module net- check_planarity() (in module net-
workx.algorithms.shortest_paths.weighted), workx.algorithms.planarity), 395
424 check_structure() (PlanarEmbedding method),
bidirectional_shortest_path() 398
(in module net- chordal_cycle_graph() (in module net-
workx.algorithms.shortest_paths.unweighted), workx.generators.expanders), 519
408 chordal_graph_cliques() (in module net-
binomial_graph() (in module net- workx.algorithms.chordal), 211
Index 715
NetworkX Reference, Release 2.3rc1.dev20190222214247
716 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 717
NetworkX Reference, Release 2.3rc1.dev20190222214247
718 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 719
NetworkX Reference, Release 2.3rc1.dev20190222214247
720 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 721
NetworkX Reference, Release 2.3rc1.dev20190222214247
722 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 723
NetworkX Reference, Release 2.3rc1.dev20190222214247
724 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 725
NetworkX Reference, Release 2.3rc1.dev20190222214247
networkx.algorithms.distance_regular networkx.algorithms.shortest_paths.generic
(module), 305 (module), 401
networkx.algorithms.dominance (module), networkx.algorithms.shortest_paths.unweighted
307 (module), 406
networkx.algorithms.dominating (module), networkx.algorithms.shortest_paths.weighted
308 (module), 411
networkx.algorithms.efficiency (module), networkx.algorithms.similarity (module),
310 437
networkx.algorithms.euler (module), 311 networkx.algorithms.simple_paths (mod-
networkx.algorithms.flow (module), 313 ule), 444
networkx.algorithms.graphical (module), networkx.algorithms.smallworld (module),
340 448
networkx.algorithms.hierarchy (module), networkx.algorithms.smetric (module), 451
344 networkx.algorithms.sparsifiers (module),
networkx.algorithms.hybrid (module), 344 452
networkx.algorithms.isolate (module), 346 networkx.algorithms.structuralholes
networkx.algorithms.isomorphism (module), (module), 453
347 networkx.algorithms.swap (module), 455
networkx.algorithms.isomorphism.isomorphvf2 networkx.algorithms.tournament (module),
(module), 350 457
networkx.algorithms.link_analysis.hits_alg networkx.algorithms.traversal.beamsearch
(module), 365 (module), 468
networkx.algorithms.link_analysis.pagerank_algnetworkx.algorithms.traversal.breadth_first_search
(module), 361 (module), 465
networkx.algorithms.link_prediction networkx.algorithms.traversal.depth_first_search
(module), 367 (module), 460
networkx.algorithms.lowest_common_ancestors networkx.algorithms.traversal.edgebfs
(module), 373 (module), 470
networkx.algorithms.matching (module), 375 networkx.algorithms.traversal.edgedfs
networkx.algorithms.minors (module), 377 (module), 469
networkx.algorithms.mis (module), 383 networkx.algorithms.tree.branchings
networkx.algorithms.node_classification (module), 474
(module), 384 networkx.algorithms.tree.coding (module),
networkx.algorithms.node_classification.hmn 477
(module), 384 networkx.algorithms.tree.mst (module), 482
networkx.algorithms.node_classification.lgc networkx.algorithms.tree.operations
(module), 385 (module), 481
networkx.algorithms.operators.all (mod- networkx.algorithms.tree.recognition
ule), 389 (module), 472
networkx.algorithms.operators.binary networkx.algorithms.triads (module), 486
(module), 387 networkx.algorithms.vitality (module), 487
networkx.algorithms.operators.product networkx.algorithms.voronoi (module), 488
(module), 391 networkx.algorithms.wiener (module), 489
networkx.algorithms.operators.unary networkx.classes.function (module), 491
(module), 386 networkx.classes.graphviews (module), 127
networkx.algorithms.planarity (module), networkx.classes.ordered (module), 126
395 networkx.convert (module), 595
networkx.algorithms.reciprocity (module), networkx.convert_matrix (module), 598
399 networkx.drawing.layout (module), 675
networkx.algorithms.richclub (module), 400 networkx.drawing.nx_agraph (module), 670
networkx.algorithms.shortest_paths.astarnetworkx.drawing.nx_pydot (module), 672
(module), 436 networkx.drawing.nx_pylab (module), 661
networkx.algorithms.shortest_paths.densenetworkx.exception (module), 683
(module), 434 networkx.generators.atlas (module), 509
726 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 727
NetworkX Reference, Release 2.3rc1.dev20190222214247
728 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 729
NetworkX Reference, Release 2.3rc1.dev20190222214247
730 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
Index 731
NetworkX Reference, Release 2.3rc1.dev20190222214247
732 Index
NetworkX Reference, Release 2.3rc1.dev20190222214247
workx.algorithms.dag), 299 W
transitivity() (in module net- watts_strogatz_graph() (in module net-
workx.algorithms.cluster), 218 workx.generators.random_graphs), 531
traverse_face() (PlanarEmbedding method), 399 waxman_graph() (in module net-
tree_all_pairs_lowest_common_ancestor() workx.generators.geometric), 554
(in module net- weakly_connected_component_subgraphs()
workx.algorithms.lowest_common_ancestors), (in module networkx.algorithms.components),
374 245
tree_data() (in module net- weakly_connected_components() (in module
workx.readwrite.json_graph), 646 networkx.algorithms.components), 245
tree_graph() (in module net- weighted_choice() (in module net-
workx.readwrite.json_graph), 647 workx.utils.random_sequence), 689
treewidth_min_degree() (in module net- weighted_projected_graph() (in module net-
workx.algorithms.approximation.treewidth), workx.algorithms.bipartite.projection), 160
139 wheel_graph() (in module net-
treewidth_min_fill_in() (in module net- workx.generators.classic), 518
workx.algorithms.approximation.treewidth), wiener_index() (in module net-
139 workx.algorithms.wiener), 489
triad_graph() (in module net- windmill_graph() (in module net-
workx.generators.triads), 574 workx.generators.community), 569
triadic_census() (in module net- within_inter_cluster() (in module net-
workx.algorithms.triads), 486 workx.algorithms.link_prediction), 372
triangles() (in module net- write_adjlist() (in module net-
workx.algorithms.cluster), 218 workx.readwrite.adjlist), 618
triangular_lattice_graph() (in module net- write_dot() (in module net-
workx.generators.lattice), 522 workx.drawing.nx_agraph), 671
trivial_graph() (in module net- write_dot() (in module networkx.drawing.nx_pydot),
workx.generators.classic), 518 674
truncated_cube_graph() (in module net- write_edgelist() (in module net-
workx.generators.small), 526 workx.readwrite.edgelist), 626
truncated_tetrahedron_graph() (in module write_gexf() (in module networkx.readwrite.gexf ),
networkx.generators.small), 526 631
turan_graph() (in module net- write_gml() (in module networkx.readwrite.gml),
workx.generators.classic), 518 634
tutte_graph() (in module net- write_gpickle() (in module net-
workx.generators.small), 526 workx.readwrite.gpickle), 639
write_graph6() (in module net-
U workx.readwrite.graph6), 653
uniform_random_intersection_graph() (in write_graphml() (in module net-
module networkx.generators.intersection), 561 workx.readwrite.graphml), 641
union() (in module net- write_multiline_adjlist() (in module net-
workx.algorithms.operators.binary), 387 workx.readwrite.multiline_adjlist), 622
union() (UnionFind method), 687 write_pajek() (in module net-
union_all() (in module net- workx.readwrite.pajek), 658
workx.algorithms.operators.all), 390 write_shp() (in module networkx.readwrite.nx_shp),
update() (DiGraph method), 44 660
update() (Graph method), 17 write_sparse6() (in module net-
update() (MultiDiGraph method), 105 workx.readwrite.sparse6), 656
update() (MultiGraph method), 76 write_weighted_edgelist() (in module net-
workx.readwrite.edgelist), 627
V write_yaml() (in module net-
volume() (in module networkx.algorithms.cuts), 294 workx.readwrite.nx_yaml), 650
voronoi_cells() (in module net-
workx.algorithms.voronoi), 488
Index 733
NetworkX Reference, Release 2.3rc1.dev20190222214247
Z
zipf_rv() (in module net-
workx.utils.random_sequence), 688
734 Index