Fixed database typo and removed unnecessary class identifier.

This commit is contained in:
Batuhan Berk Başoğlu 2020-10-14 10:10:37 -04:00
parent 00ad49a143
commit 45fb349a7d
5098 changed files with 952558 additions and 85 deletions

View file

@ -0,0 +1,40 @@
License
=======
NetworkX is distributed with the 3-clause BSD license.
::
Copyright (C) 2004-2020, NetworkX Developers
Aric Hagberg <hagberg@lanl.gov>
Dan Schult <dschult@colgate.edu>
Pieter Swart <swart@lanl.gov>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NetworkX Developers nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View file

@ -0,0 +1,2 @@
3D Drawing
----------

View file

@ -0,0 +1,41 @@
"""
=======
Mayavi2
=======
"""
import networkx as nx
import numpy as np
from mayavi import mlab
# some graphs to try
# H=nx.krackhardt_kite_graph()
# H=nx.Graph();H.add_edge('a','b');H.add_edge('a','c');H.add_edge('a','d')
# H=nx.grid_2d_graph(4,5)
H = nx.cycle_graph(20)
# reorder nodes from 0,len(G)-1
G = nx.convert_node_labels_to_integers(H)
# 3d spring layout
pos = nx.spring_layout(G, dim=3)
# numpy array of x,y,z positions in sorted node order
xyz = np.array([pos[v] for v in sorted(G)])
# scalar colors
scalars = np.array(list(G.nodes())) + 5
pts = mlab.points3d(
xyz[:, 0],
xyz[:, 1],
xyz[:, 2],
scalars,
scale_factor=0.1,
scale_mode="none",
colormap="Blues",
resolution=20,
)
pts.mlab_source.dataset.lines = np.array(list(G.edges()))
tube = mlab.pipeline.tube(pts, tube_radius=0.01)
mlab.pipeline.surface(tube, color=(0.8, 0.8, 0.8))
mlab.show()

View file

@ -0,0 +1,8 @@
.. _examples_gallery:
Gallery
=======
General-purpose and introductory examples for NetworkX.
The `tutorial <../tutorial.html>`_ introduces conventions and basic graph
manipulations.

View file

@ -0,0 +1,2 @@
Advanced
--------

View file

@ -0,0 +1,22 @@
"""
===========
Eigenvalues
===========
Create an G{n,m} random graph and compute the eigenvalues.
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy.linalg
n = 1000 # 1000 nodes
m = 5000 # 5000 edges
G = nx.gnm_random_graph(n, m)
L = nx.normalized_laplacian_matrix(G)
e = numpy.linalg.eigvals(L.A)
print("Largest eigenvalue:", max(e))
print("Smallest eigenvalue:", min(e))
plt.hist(e, bins=100) # histogram with 100 bins
plt.xlim(0, 2) # eigenvalues between 0 and 2
plt.show()

View file

@ -0,0 +1,52 @@
"""
==================
Heavy Metal Umlaut
==================
Example using unicode strings as graph labels.
Also shows creative use of the Heavy Metal Umlaut:
https://en.wikipedia.org/wiki/Heavy_metal_umlaut
"""
import matplotlib.pyplot as plt
import networkx as nx
hd = "H" + chr(252) + "sker D" + chr(252)
mh = "Mot" + chr(246) + "rhead"
mc = "M" + chr(246) + "tley Cr" + chr(252) + "e"
st = "Sp" + chr(305) + "n" + chr(776) + "al Tap"
q = "Queensr" + chr(255) + "che"
boc = "Blue " + chr(214) + "yster Cult"
dt = "Deatht" + chr(246) + "ngue"
G = nx.Graph()
G.add_edge(hd, mh)
G.add_edge(mc, st)
G.add_edge(boc, mc)
G.add_edge(boc, dt)
G.add_edge(st, dt)
G.add_edge(q, st)
G.add_edge(dt, mh)
G.add_edge(st, mh)
# write in UTF-8 encoding
fh = open("edgelist.utf-8", "wb")
nx.write_multiline_adjlist(G, fh, delimiter="\t", encoding="utf-8")
# read and store in UTF-8
fh = open("edgelist.utf-8", "rb")
H = nx.read_multiline_adjlist(fh, delimiter="\t", encoding="utf-8")
for n in G.nodes():
if n not in H:
print(False)
print(list(G.nodes()))
pos = nx.spring_layout(G)
nx.draw(G, pos, font_size=16, with_labels=False)
for p in pos: # raise text positions
pos[p][1] += 0.07
nx.draw_networkx_labels(G, pos)
plt.show()

View file

@ -0,0 +1,210 @@
"""
==========================
Iterated Dynamical Systems
==========================
Digraphs from Integer-valued Iterated Functions
Sums of cubes on 3N
-------------------
The number 153 has a curious property.
Let 3N={3,6,9,12,...} be the set of positive multiples of 3. Define an
iterative process f:3N->3N as follows: for a given n, take each digit
of n (in base 10), cube it and then sum the cubes to obtain f(n).
When this process is repeated, the resulting series n, f(n), f(f(n)),...
terminate in 153 after a finite number of iterations (the process ends
because 153 = 1**3 + 5**3 + 3**3).
In the language of discrete dynamical systems, 153 is the global
attractor for the iterated map f restricted to the set 3N.
For example: take the number 108
f(108) = 1**3 + 0**3 + 8**3 = 513
and
f(513) = 5**3 + 1**3 + 3**3 = 153
So, starting at 108 we reach 153 in two iterations,
represented as:
108->513->153
Computing all orbits of 3N up to 10**5 reveals that the attractor
153 is reached in a maximum of 14 iterations. In this code we
show that 13 cycles is the maximum required for all integers (in 3N)
less than 10,000.
The smallest number that requires 13 iterations to reach 153, is 177, i.e.,
177->687->1071->345->216->225->141->66->432->99->1458->702->351->153
The resulting large digraphs are useful for testing network software.
The general problem
-------------------
Given numbers n, a power p and base b, define F(n; p, b) as the sum of
the digits of n (in base b) raised to the power p. The above example
corresponds to f(n)=F(n; 3,10), and below F(n; p, b) is implemented as
the function powersum(n,p,b). The iterative dynamical system defined by
the mapping n:->f(n) above (over 3N) converges to a single fixed point;
153. Applying the map to all positive integers N, leads to a discrete
dynamical process with 5 fixed points: 1, 153, 370, 371, 407. Modulo 3
those numbers are 1, 0, 1, 2, 2. The function f above has the added
property that it maps a multiple of 3 to another multiple of 3; i.e. it
is invariant on the subset 3N.
The squaring of digits (in base 10) result in cycles and the
single fixed point 1. I.e., from a certain point on, the process
starts repeating itself.
keywords: "Recurring Digital Invariant", "Narcissistic Number",
"Happy Number"
The 3n+1 problem
----------------
There is a rich history of mathematical recreations
associated with discrete dynamical systems. The most famous
is the Collatz 3n+1 problem. See the function
collatz_problem_digraph below. The Collatz conjecture
--- that every orbit returns to the fixed point 1 in finite time
--- is still unproven. Even the great Paul Erdos said "Mathematics
is not yet ready for such problems", and offered $500
for its solution.
keywords: "3n+1", "3x+1", "Collatz problem", "Thwaite's conjecture"
"""
import networkx as nx
nmax = 10000
p = 3
def digitsrep(n, b=10):
"""Return list of digits comprising n represented in base b.
n must be a nonnegative integer"""
if n <= 0:
return [0]
dlist = []
while n > 0:
# Prepend next least-significant digit
dlist = [n % b] + dlist
# Floor-division
n = n // b
return dlist
def powersum(n, p, b=10):
"""Return sum of digits of n (in base b) raised to the power p."""
dlist = digitsrep(n, b)
sum = 0
for k in dlist:
sum += k ** p
return sum
def attractor153_graph(n, p, multiple=3, b=10):
"""Return digraph of iterations of powersum(n,3,10)."""
G = nx.DiGraph()
for k in range(1, n + 1):
if k % multiple == 0 and k not in G:
k1 = k
knext = powersum(k1, p, b)
while k1 != knext:
G.add_edge(k1, knext)
k1 = knext
knext = powersum(k1, p, b)
return G
def squaring_cycle_graph_old(n, b=10):
"""Return digraph of iterations of powersum(n,2,10)."""
G = nx.DiGraph()
for k in range(1, n + 1):
k1 = k
G.add_node(k1) # case k1==knext, at least add node
knext = powersum(k1, 2, b)
G.add_edge(k1, knext)
while k1 != knext: # stop if fixed point
k1 = knext
knext = powersum(k1, 2, b)
G.add_edge(k1, knext)
if G.out_degree(knext) >= 1:
# knext has already been iterated in and out
break
return G
def sum_of_digits_graph(nmax, b=10):
def f(n):
return powersum(n, 1, b)
return discrete_dynamics_digraph(nmax, f)
def squaring_cycle_digraph(nmax, b=10):
def f(n):
return powersum(n, 2, b)
return discrete_dynamics_digraph(nmax, f)
def cubing_153_digraph(nmax):
def f(n):
return powersum(n, 3, 10)
return discrete_dynamics_digraph(nmax, f)
def discrete_dynamics_digraph(nmax, f, itermax=50000):
G = nx.DiGraph()
for k in range(1, nmax + 1):
kold = k
G.add_node(kold)
knew = f(kold)
G.add_edge(kold, knew)
while kold != knew and kold << itermax:
# iterate until fixed point reached or itermax is exceeded
kold = knew
knew = f(kold)
G.add_edge(kold, knew)
if G.out_degree(knew) >= 1:
# knew has already been iterated in and out
break
return G
def collatz_problem_digraph(nmax):
def f(n):
if n % 2 == 0:
return n // 2
else:
return 3 * n + 1
return discrete_dynamics_digraph(nmax, f)
def fixed_points(G):
"""Return a list of fixed points for the discrete dynamical
system represented by the digraph G.
"""
return [n for n in G if G.out_degree(n) == 0]
nmax = 10000
print(f"Building cubing_153_digraph({nmax})")
G = cubing_153_digraph(nmax)
print("Resulting digraph has", len(G), "nodes and", G.size(), " edges")
print("Shortest path from 177 to 153 is:")
print(nx.shortest_path(G, 177, 153))
print(f"fixed points are {fixed_points(G)}")

View file

@ -0,0 +1,78 @@
"""
====================
Parallel Betweenness
====================
Example of parallel implementation of betweenness centrality using the
multiprocessing module from Python Standard Library.
The function betweenness centrality accepts a bunch of nodes and computes
the contribution of those nodes to the betweenness centrality of the whole
network. Here we divide the network in chunks of nodes and we compute their
contribution to the betweenness centrality of the whole network.
"""
from multiprocessing import Pool
import time
import itertools
import matplotlib.pyplot as plt
import networkx as nx
def chunks(l, n):
"""Divide a list of nodes `l` in `n` chunks"""
l_c = iter(l)
while 1:
x = tuple(itertools.islice(l_c, n))
if not x:
return
yield x
def betweenness_centrality_parallel(G, processes=None):
"""Parallel betweenness centrality function"""
p = Pool(processes=processes)
node_divisor = len(p._pool) * 4
node_chunks = list(chunks(G.nodes(), int(G.order() / node_divisor)))
num_chunks = len(node_chunks)
bt_sc = p.starmap(
nx.betweenness_centrality_subset,
zip(
[G] * num_chunks,
node_chunks,
[list(G)] * num_chunks,
[True] * num_chunks,
[None] * num_chunks,
),
)
# Reduce the partial solutions
bt_c = bt_sc[0]
for bt in bt_sc[1:]:
for n in bt:
bt_c[n] += bt[n]
return bt_c
G_ba = nx.barabasi_albert_graph(1000, 3)
G_er = nx.gnp_random_graph(1000, 0.01)
G_ws = nx.connected_watts_strogatz_graph(1000, 4, 0.1)
for G in [G_ba, G_er, G_ws]:
print("")
print("Computing betweenness centrality for:")
print(nx.info(G))
print("\tParallel version")
start = time.time()
bt = betweenness_centrality_parallel(G)
print(f"\t\tTime: {(time.time() - start):.4F} seconds")
print(f"\t\tBetweenness centrality for node 0: {bt[0]:.5f}")
print("\tNon-Parallel version")
start = time.time()
bt = nx.betweenness_centrality(G)
print(f"\t\tTime: {(time.time() - start):.4F} seconds")
print(f"\t\tBetweenness centrality for node 0: {bt[0]:.5f}")
print("")
nx.draw(G_ba, node_size=100)
plt.show()

View file

@ -0,0 +1,2 @@
Algorithms
----------

View file

@ -0,0 +1,338 @@
# source target
1 2
1 10
2 1
2 10
3 7
4 7
4 209
5 132
6 150
7 3
7 4
7 9
8 106
8 115
9 1
9 2
9 7
10 1
10 2
11 133
11 218
12 88
13 214
14 24
14 52
16 10
16 19
17 64
17 78
18 55
18 103
18 163
19 18
20 64
20 180
21 16
21 22
22 21
22 64
22 106
23 20
23 22
23 64
24 14
24 31
24 122
27 115
28 29
29 28
30 19
31 24
31 32
31 122
31 147
31 233
32 31
32 86
34 35
34 37
35 34
35 43
36 132
36 187
37 38
37 90
37 282
38 42
38 43
38 210
40 20
42 15
42 38
43 34
43 35
43 38
45 107
46 61
46 72
48 23
49 30
49 64
49 108
49 115
49 243
50 30
50 47
50 55
50 125
50 163
52 218
52 224
54 111
54 210
55 65
55 67
55 105
55 108
55 222
56 18
56 64
57 65
57 125
58 20
58 30
58 50
58 103
58 180
59 164
63 125
64 8
64 50
64 70
64 256
66 20
66 84
66 106
66 125
67 22
67 50
67 113
68 50
70 50
70 64
71 72
74 29
74 75
74 215
75 74
75 215
76 58
76 104
77 103
78 64
78 68
80 207
80 210
82 8
82 77
82 83
82 97
82 163
83 82
83 226
83 243
84 29
84 154
87 101
87 189
89 90
90 89
90 94
91 86
92 19
92 30
92 106
94 72
94 89
94 90
95 30
96 75
96 256
97 80
97 128
98 86
100 86
101 87
103 77
103 104
104 58
104 77
104 103
106 22
107 38
107 114
107 122
108 49
108 55
111 121
111 128
111 210
113 253
114 107
116 30
116 140
118 129
118 138
120 88
121 128
122 31
123 32
124 244
125 132
126 163
126 180
128 38
128 111
129 118
132 29
132 30
133 30
134 135
134 150
135 134
137 144
138 118
138 129
139 142
141 157
141 163
142 139
143 2
144 137
145 151
146 137
146 165
146 169
146 171
147 31
147 128
148 146
148 169
148 171
148 282
149 128
149 148
149 172
150 86
151 145
152 4
153 134
154 155
156 161
157 141
161 156
165 144
165 148
167 149
169 15
169 148
169 171
170 115
170 173
170 183
170 202
171 72
171 148
171 169
173 170
175 100
176 10
178 181
181 178
182 38
182 171
183 96
185 50
186 127
187 50
187 65
188 30
188 50
189 87
189 89
190 35
190 38
190 122
190 182
191 54
191 118
191 129
191 172
192 149
192 167
195 75
197 50
197 188
198 218
198 221
198 222
200 65
200 220
201 113
202 156
203 232
204 194
207 38
207 122
207 124
208 30
208 50
210 38
210 207
211 37
213 35
213 38
214 13
214 14
214 171
214 213
215 75
217 39
218 68
218 222
221 198
222 198
222 218
223 39
225 3
226 22
229 65
230 68
231 43
232 95
232 203
233 99
234 68
234 230
237 244
238 145
242 3
242 113
244 237
249 96
250 156
252 65
254 65
258 113
268 4
270 183
272 6
275 96
280 183
280 206
282 37
285 75
290 285
293 290

View file

@ -0,0 +1,109 @@
"""
===========
Beam Search
===========
Beam search with dynamic beam width.
The progressive widening beam search repeatedly executes a beam search
with increasing beam width until the target node is found.
"""
import math
import matplotlib.pyplot as plt
import networkx as nx
def progressive_widening_search(G, source, value, condition, initial_width=1):
"""Progressive widening beam search to find a node.
The progressive widening beam search involves a repeated beam
search, starting with a small beam width then extending to
progressively larger beam widths if the target node is not
found. This implementation simply returns the first node found that
matches the termination condition.
`G` is a NetworkX graph.
`source` is a node in the graph. The search for the node of interest
begins here and extends only to those nodes in the (weakly)
connected component of this node.
`value` is a function that returns a real number indicating how good
a potential neighbor node is when deciding which neighbor nodes to
enqueue in the breadth-first search. Only the best nodes within the
current beam width will be enqueued at each step.
`condition` is the termination condition for the search. This is a
function that takes a node as input and return a Boolean indicating
whether the node is the target. If no node matches the termination
condition, this function raises :exc:`NodeNotFound`.
`initial_width` is the starting beam width for the beam search (the
default is one). If no node matching the `condition` is found with
this beam width, the beam search is restarted from the `source` node
with a beam width that is twice as large (so the beam width
increases exponentially). The search terminates after the beam width
exceeds the number of nodes in the graph.
"""
# Check for the special case in which the source node satisfies the
# termination condition.
if condition(source):
return source
# The largest possible value of `i` in this range yields a width at
# least the number of nodes in the graph, so the final invocation of
# `bfs_beam_edges` is equivalent to a plain old breadth-first
# search. Therefore, all nodes will eventually be visited.
log_m = math.ceil(math.log2(len(G)))
for i in range(log_m):
width = initial_width * pow(2, i)
# Since we are always starting from the same source node, this
# search may visit the same nodes many times (depending on the
# implementation of the `value` function).
for u, v in nx.bfs_beam_edges(G, source, value, width):
if condition(v):
return v
# At this point, since all nodes have been visited, we know that
# none of the nodes satisfied the termination condition.
raise nx.NodeNotFound("no node satisfied the termination condition")
###############################################################################
# Search for a node with high centrality.
# ---------------------------------------
#
# We generate a random graph, compute the centrality of each node, then perform
# the progressive widening search in order to find a node of high centrality.
G = nx.gnp_random_graph(100, 0.5)
centrality = nx.eigenvector_centrality(G)
avg_centrality = sum(centrality.values()) / len(G)
def has_high_centrality(v):
return centrality[v] >= avg_centrality
source = 0
value = centrality.get
condition = has_high_centrality
found_node = progressive_widening_search(G, source, value, condition)
c = centrality[found_node]
print(f"found node {found_node} with centrality {c}")
# Draw graph
pos = nx.spring_layout(G)
options = {
"node_color": "blue",
"node_size": 20,
"edge_color": "grey",
"linewidths": 0,
"width": 0.1,
}
nx.draw(G, pos, **options)
# Draw node with high centrality as large and red
nx.draw_networkx_nodes(G, pos, nodelist=[found_node], node_size=100, node_color="r")
plt.show()

View file

@ -0,0 +1,79 @@
"""
==========
Blockmodel
==========
Example of creating a block model using the quotient_graph function in NX. Data
used is the Hartford, CT drug users network::
@article{weeks2002social,
title={Social networks of drug users in high-risk sites: Finding the connections},
url = {https://doi.org/10.1023/A:1015457400897},
doi = {10.1023/A:1015457400897},
author={Weeks, Margaret R and Clair, Scott and Borgatti, Stephen P and Radda, Kim and Schensul, Jean J},
journal={{AIDS and Behavior}},
volume={6},
number={2},
pages={193--206},
year={2002},
publisher={Springer}
}
"""
from collections import defaultdict
import matplotlib.pyplot as plt
import networkx as nx
import numpy
from scipy.cluster import hierarchy
from scipy.spatial import distance
def create_hc(G):
"""Creates hierarchical cluster of graph G from distance matrix"""
path_length = nx.all_pairs_shortest_path_length(G)
distances = numpy.zeros((len(G), len(G)))
for u, p in path_length:
for v, d in p.items():
distances[u][v] = d
# Create hierarchical cluster
Y = distance.squareform(distances)
Z = hierarchy.complete(Y) # Creates HC using farthest point linkage
# This partition selection is arbitrary, for illustrive purposes
membership = list(hierarchy.fcluster(Z, t=1.15))
# Create collection of lists for blockmodel
partition = defaultdict(list)
for n, p in zip(list(range(len(G))), membership):
partition[p].append(n)
return list(partition.values())
G = nx.read_edgelist("hartford_drug.edgelist")
# Extract largest connected component into graph H
H = G.subgraph(next(nx.connected_components(G)))
# Makes life easier to have consecutively labeled integer nodes
H = nx.convert_node_labels_to_integers(H)
# Create parititions with hierarchical clustering
partitions = create_hc(H)
# Build blockmodel graph
BM = nx.quotient_graph(H, partitions, relabel=True)
# Draw original graph
pos = nx.spring_layout(H, iterations=100)
plt.subplot(211)
nx.draw(H, pos, with_labels=False, node_size=10)
# Draw block model with weighted edges and nodes sized by number of internal nodes
node_size = [BM.nodes[x]["nnodes"] * 10 for x in BM.nodes()]
edge_width = [(2 * d["weight"]) for (u, v, d) in BM.edges(data=True)]
# Set positions to mean of positions of internal nodes from original graph
posBM = {}
for n in BM:
xy = numpy.array([pos[u] for u in BM.nodes[n]["graph"]])
posBM[n] = xy.mean(axis=0)
plt.subplot(212)
nx.draw(BM, posBM, node_size=node_size, width=edge_width, with_labels=False)
plt.axis("off")
plt.show()

View file

@ -0,0 +1,42 @@
"""
==========
Davis Club
==========
Davis Southern Club Women
Shows how to make unipartite projections of the graph and compute the
properties of those graphs.
These data were collected by Davis et al. in the 1930s.
They represent observed attendance at 14 social events by 18 Southern women.
The graph is bipartite (clubs, women).
"""
import matplotlib.pyplot as plt
import networkx as nx
import networkx.algorithms.bipartite as bipartite
G = nx.davis_southern_women_graph()
women = G.graph["top"]
clubs = G.graph["bottom"]
print("Biadjacency matrix")
print(bipartite.biadjacency_matrix(G, women, clubs))
# project bipartite graph onto women nodes
W = bipartite.projected_graph(G, women)
print()
print("#Friends, Member")
for w in women:
print(f"{W.degree(w)} {w}")
# project bipartite graph onto women nodes keeping number of co-occurence
# the degree computed is weighted and counts the total number of shared contacts
W = bipartite.weighted_projected_graph(G, women)
print()
print("#Friend meetings, Member")
for w in women:
print(f"{W.degree(w, weight='weight')} {w}")
nx.draw(G)
plt.show()

View file

@ -0,0 +1,40 @@
"""
=============
Decomposition
=============
Example of creating a junction tree from a directed graph.
"""
import networkx as nx
from networkx.algorithms import moral
from networkx.algorithms.tree.decomposition import junction_tree
from networkx.drawing.nx_agraph import graphviz_layout as layout
import matplotlib.pyplot as plt
B = nx.DiGraph()
B.add_nodes_from(["A", "B", "C", "D", "E", "F"])
B.add_edges_from(
[("A", "B"), ("A", "C"), ("B", "D"), ("B", "F"), ("C", "E"), ("E", "F")]
)
options = {"with_labels": True, "node_color": "white", "edgecolors": "blue"}
bayes_pos = layout(B, prog="neato")
ax1 = plt.subplot(1, 3, 1)
plt.title("Bayesian Network")
nx.draw_networkx(B, pos=bayes_pos, **options)
mg = moral.moral_graph(B)
plt.subplot(1, 3, 2, sharex=ax1, sharey=ax1)
plt.title("Moralized Graph")
nx.draw_networkx(mg, pos=bayes_pos, **options)
jt = junction_tree(B)
plt.subplot(1, 3, 3)
plt.title("Junction Tree")
nsize = [2000 * len(n) for n in list(jt.nodes())]
nx.draw_networkx(jt, pos=layout(jt, prog="neato"), node_size=nsize, **options)
plt.tight_layout()
plt.show()

View file

@ -0,0 +1,30 @@
"""
=====================
Krackhardt Centrality
=====================
Centrality measures of Krackhardt social network.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.krackhardt_kite_graph()
print("Betweenness")
b = nx.betweenness_centrality(G)
for v in G.nodes():
print(f"{v:2} {b[v]:.3f}")
print("Degree centrality")
d = nx.degree_centrality(G)
for v in G.nodes():
print(f"{v:2} {d[v]:.3f}")
print("Closeness centrality")
c = nx.closeness_centrality(G)
for v in G.nodes():
print(f"{v:2} {c[v]:.3f}")
nx.draw(G)
plt.show()

View file

@ -0,0 +1,35 @@
"""
===
Rcm
===
Cuthill-McKee ordering of matrices
The reverse Cuthill-McKee algorithm gives a sparse matrix ordering that
reduces the matrix bandwidth.
"""
import networkx as nx
from networkx.utils import reverse_cuthill_mckee_ordering
import numpy as np
# build low-bandwidth numpy matrix
G = nx.grid_2d_graph(3, 3)
rcm = list(reverse_cuthill_mckee_ordering(G))
print("ordering", rcm)
print("unordered Laplacian matrix")
A = nx.laplacian_matrix(G)
x, y = np.nonzero(A)
# print(f"lower bandwidth: {(y - x).max()}")
# print(f"upper bandwidth: {(x - y).max()}")
print(f"bandwidth: {(y - x).max() + (x - y).max() + 1}")
print(A)
B = nx.laplacian_matrix(G, nodelist=rcm)
print("low-bandwidth Laplacian matrix")
x, y = np.nonzero(B)
# print(f"lower bandwidth: {(y - x).max()}")
# print(f"upper bandwidth: {(x - y).max()}")
print(f"bandwidth: {(y - x).max() + (x - y).max() + 1}")
print(B)

View file

@ -0,0 +1,2 @@
Basic
-----

View file

@ -0,0 +1,48 @@
"""
==========
Properties
==========
Compute some network properties for the lollipop graph.
"""
import matplotlib.pyplot as plt
from networkx import nx
G = nx.lollipop_graph(4, 6)
pathlengths = []
print("source vertex {target:length, }")
for v in G.nodes():
spl = dict(nx.single_source_shortest_path_length(G, v))
print(f"{v} {spl} ")
for p in spl:
pathlengths.append(spl[p])
print()
print(f"average shortest path length {sum(pathlengths) / len(pathlengths)}")
# histogram of path lengths
dist = {}
for p in pathlengths:
if p in dist:
dist[p] += 1
else:
dist[p] = 1
print()
print("length #paths")
verts = dist.keys()
for d in sorted(verts):
print(f"{d} {dist[d]}")
print(f"radius: {nx.radius(G)}")
print(f"diameter: {nx.diameter(G)}")
print(f"eccentricity: {nx.eccentricity(G)}")
print(f"center: {nx.center(G)}")
print(f"periphery: {nx.periphery(G)}")
print(f"density: {nx.density(G)}")
nx.draw(G, with_labels=True)
plt.show()

View file

@ -0,0 +1,23 @@
"""
======================
Read and write graphs.
======================
Read and write graphs.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.grid_2d_graph(5, 5) # 5x5 grid
# print the adjacency list
for line in nx.generate_adjlist(G):
print(line)
# write edgelist to grid.edgelist
nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
# read edgelist from grid.edgelist
H = nx.read_edgelist(path="grid.edgelist", delimiter=":")
nx.draw(H)
plt.show()

View file

@ -0,0 +1,2 @@
Drawing
-------

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,73 @@
"""
=====
Atlas
=====
Atlas of all graphs of 6 nodes or less.
"""
import random
# This example needs Graphviz and either PyGraphviz or pydot.
# from networkx.drawing.nx_pydot import graphviz_layout
from networkx.drawing.nx_agraph import graphviz_layout
import matplotlib.pyplot as plt
import networkx as nx
from networkx.algorithms.isomorphism.isomorph import (
graph_could_be_isomorphic as isomorphic,
)
from networkx.generators.atlas import graph_atlas_g
def atlas6():
""" Return the atlas of all connected graphs of 6 nodes or less.
Attempt to check for isomorphisms and remove.
"""
Atlas = graph_atlas_g()[0:208] # 208
# remove isolated nodes, only connected graphs are left
U = nx.Graph() # graph for union of all graphs in atlas
for G in Atlas:
zerodegree = [n for n in G if G.degree(n) == 0]
for n in zerodegree:
G.remove_node(n)
U = nx.disjoint_union(U, G)
# iterator of graphs of all connected components
C = (U.subgraph(c) for c in nx.connected_components(U))
UU = nx.Graph()
# do quick isomorphic-like check, not a true isomorphism checker
nlist = [] # list of nonisomorphic graphs
for G in C:
# check against all nonisomorphic graphs so far
if not iso(G, nlist):
nlist.append(G)
UU = nx.disjoint_union(UU, G) # union the nonisomorphic graphs
return UU
def iso(G1, glist):
"""Quick and dirty nonisomorphism checker used to check isomorphisms."""
for G2 in glist:
if isomorphic(G1, G2):
return True
return False
G = atlas6()
print(f"graph has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges")
print(nx.number_connected_components(G), "connected components")
plt.figure(1, figsize=(8, 8))
# layout graphs with positions using graphviz neato
pos = graphviz_layout(G, prog="neato")
# color nodes the same in each connected subgraph
C = (G.subgraph(c) for c in nx.connected_components(G))
for g in C:
c = [random.random()] * nx.number_of_nodes(g) # random color...
nx.draw(g, pos, node_size=40, node_color=c, vmin=0.0, vmax=1.0, with_labels=False)
plt.show()

View file

@ -0,0 +1,147 @@
"""
=============
Chess Masters
=============
An example of the MultiDiGraph clas
The function chess_pgn_graph reads a collection of chess matches stored in the
specified PGN file (PGN ="Portable Game Notation"). Here the (compressed)
default file::
chess_masters_WCC.pgn.bz2
contains all 685 World Chess Championship matches from 1886--1985.
(data from http://chessproblem.my-free-games.com/chess/games/Download-PGN.php)
The `chess_pgn_graph()` function returns a `MultiDiGraph` with multiple edges.
Each node is the last name of a chess master. Each edge is directed from white
to black and contains selected game info.
The key statement in `chess_pgn_graph` below is::
G.add_edge(white, black, game_info)
where `game_info` is a `dict` describing each game.
"""
import matplotlib.pyplot as plt
import networkx as nx
# tag names specifying what game info should be
# stored in the dict on each digraph edge
game_details = ["Event", "Date", "Result", "ECO", "Site"]
def chess_pgn_graph(pgn_file="chess_masters_WCC.pgn.bz2"):
"""Read chess games in pgn format in pgn_file.
Filenames ending in .gz or .bz2 will be uncompressed.
Return the MultiDiGraph of players connected by a chess game.
Edges contain game data in a dict.
"""
import bz2
G = nx.MultiDiGraph()
game = {}
datafile = bz2.BZ2File(pgn_file)
lines = (line.decode().rstrip("\r\n") for line in datafile)
for line in lines:
if line.startswith("["):
tag, value = line[1:-1].split(" ", 1)
game[str(tag)] = value.strip('"')
else:
# empty line after tag set indicates
# we finished reading game info
if game:
white = game.pop("White")
black = game.pop("Black")
G.add_edge(white, black, **game)
game = {}
return G
G = chess_pgn_graph()
ngames = G.number_of_edges()
nplayers = G.number_of_nodes()
print(f"Loaded {ngames} chess games between {nplayers} players\n")
# identify connected components
# of the undirected version
H = G.to_undirected()
Gcc = [H.subgraph(c) for c in nx.connected_components(H)]
if len(Gcc) > 1:
print("Note the disconnected component consisting of:")
print(Gcc[1].nodes())
# find all games with B97 opening (as described in ECO)
openings = {game_info["ECO"] for (white, black, game_info) in G.edges(data=True)}
print(f"\nFrom a total of {len(openings)} different openings,")
print("the following games used the Sicilian opening")
print('with the Najdorff 7...Qb6 "Poisoned Pawn" variation.\n')
for (white, black, game_info) in G.edges(data=True):
if game_info["ECO"] == "B97":
print(white, "vs", black)
for k, v in game_info.items():
print(" ", k, ": ", v)
print("\n")
# make new undirected graph H without multi-edges
H = nx.Graph(G)
# edge width is proportional number of games played
edgewidth = []
for (u, v, d) in H.edges(data=True):
edgewidth.append(len(G.get_edge_data(u, v)))
# node size is proportional to number of games won
wins = dict.fromkeys(G.nodes(), 0.0)
for (u, v, d) in G.edges(data=True):
r = d["Result"].split("-")
if r[0] == "1":
wins[u] += 1.0
elif r[0] == "1/2":
wins[u] += 0.5
wins[v] += 0.5
else:
wins[v] += 1.0
try:
pos = nx.nx_agraph.graphviz_layout(H)
except ImportError:
pos = nx.spring_layout(H, iterations=20)
plt.rcParams["text.usetex"] = False
plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(H, pos, alpha=0.3, width=edgewidth, edge_color="m")
nodesize = [wins[v] * 50 for v in H]
nx.draw_networkx_nodes(H, pos, node_size=nodesize, node_color="w", alpha=0.4)
nx.draw_networkx_edges(H, pos, alpha=0.4, node_size=0, width=1, edge_color="k")
nx.draw_networkx_labels(H, pos, font_size=14)
font = {"fontname": "Helvetica", "color": "k", "fontweight": "bold", "fontsize": 14}
plt.title("World Chess Championship Games: 1886 - 1985", font)
# change font and write text (using data coordinates)
font = {"fontname": "Helvetica", "color": "r", "fontweight": "bold", "fontsize": 14}
plt.text(
0.5,
0.97,
"edge width = # games played",
horizontalalignment="center",
transform=plt.gca().transAxes,
)
plt.text(
0.5,
0.94,
"node size = # games won",
horizontalalignment="center",
transform=plt.gca().transAxes,
)
plt.axis("off")
plt.show()

View file

@ -0,0 +1,20 @@
"""
=============
Circular Tree
=============
"""
import matplotlib.pyplot as plt
import networkx as nx
# This example needs Graphviz and either PyGraphviz or pydot
# from networkx.drawing.nx_pydot import graphviz_layout
from networkx.drawing.nx_agraph import graphviz_layout
G = nx.balanced_tree(3, 5)
pos = graphviz_layout(G, prog="twopi", args="")
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
plt.axis("equal")
plt.show()

View file

@ -0,0 +1,35 @@
"""
================
Degree histogram
================
Draw degree histogram with matplotlib.
Random graph shown as inset
"""
import collections
import matplotlib.pyplot as plt
import networkx as nx
G = nx.gnp_random_graph(100, 0.02)
degree_sequence = sorted([d for n, d in G.degree()], reverse=True) # degree sequence
degreeCount = collections.Counter(degree_sequence)
deg, cnt = zip(*degreeCount.items())
fig, ax = plt.subplots()
plt.bar(deg, cnt, width=0.80, color="b")
plt.title("Degree Histogram")
plt.ylabel("Count")
plt.xlabel("Degree")
ax.set_xticks([d + 0.4 for d in deg])
ax.set_xticklabels(deg)
# draw graph in inset
plt.axes([0.4, 0.4, 0.5, 0.5])
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
pos = nx.spring_layout(G)
plt.axis("off")
nx.draw_networkx_nodes(G, pos, node_size=20)
nx.draw_networkx_edges(G, pos, alpha=0.4)
plt.show()

View file

@ -0,0 +1,29 @@
"""
===========
Degree Rank
===========
Random graph from given degree sequence.
Draw degree rank plot and graph with matplotlib.
"""
import networkx as nx
import matplotlib.pyplot as plt
G = nx.gnp_random_graph(100, 0.02)
degree_sequence = sorted([d for n, d in G.degree()], reverse=True)
dmax = max(degree_sequence)
plt.loglog(degree_sequence, "b-", marker="o")
plt.title("Degree rank plot")
plt.ylabel("degree")
plt.xlabel("rank")
# draw graph in inset
plt.axes([0.45, 0.45, 0.45, 0.45])
Gcc = G.subgraph(sorted(nx.connected_components(G), key=len, reverse=True)[0])
pos = nx.spring_layout(Gcc)
plt.axis("off")
nx.draw_networkx_nodes(Gcc, pos, node_size=20)
nx.draw_networkx_edges(Gcc, pos, alpha=0.4)
plt.show()

View file

@ -0,0 +1,44 @@
"""
==============
Directed Graph
==============
Draw a graph with directed edges using a colormap and different node sizes.
Edges have different colors and alphas (opacity). Drawn using matplotlib.
"""
import matplotlib as mpl
import matplotlib.pyplot as plt
import networkx as nx
G = nx.generators.directed.random_k_out_graph(10, 3, 0.5)
pos = nx.layout.spring_layout(G)
node_sizes = [3 + 10 * i for i in range(len(G))]
M = G.number_of_edges()
edge_colors = range(2, M + 2)
edge_alphas = [(5 + i) / (M + 4) for i in range(M)]
nodes = nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color="blue")
edges = nx.draw_networkx_edges(
G,
pos,
node_size=node_sizes,
arrowstyle="->",
arrowsize=10,
edge_color=edge_colors,
edge_cmap=plt.cm.Blues,
width=2,
)
# set alpha value for each edge
for i in range(M):
edges[i].set_alpha(edge_alphas[i])
pc = mpl.collections.PatchCollection(edges, cmap=plt.cm.Blues)
pc.set_array(edge_colors)
plt.colorbar(pc)
ax = plt.gca()
ax.set_axis_off()
plt.show()

View file

@ -0,0 +1,23 @@
"""
=============
Edge Colormap
=============
Draw a graph with matplotlib, color edges.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.star_graph(20)
pos = nx.spring_layout(G)
colors = range(20)
options = {
"node_color": "#A0CBE2",
"edge_color": colors,
"width": 4,
"edge_cmap": plt.cm.Blues,
"with_labels": False,
}
nx.draw(G, pos, **options)
plt.show()

View file

@ -0,0 +1,34 @@
"""
=========
Ego Graph
=========
Example using the NetworkX ego_graph() function to return the main egonet of
the largest hub in a Barabási-Albert network.
"""
from operator import itemgetter
import matplotlib.pyplot as plt
import networkx as nx
# Create a BA model graph
n = 1000
m = 2
G = nx.generators.barabasi_albert_graph(n, m)
# find node with largest degree
node_and_degree = G.degree()
(largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[-1]
# Create ego graph of main hub
hub_ego = nx.ego_graph(G, largest_hub)
# Draw graph
pos = nx.spring_layout(hub_ego)
nx.draw(hub_ego, pos, node_color="b", node_size=50, with_labels=False)
# Draw ego as large and red
options = {"node_size": 300, "node_color": "r"}
nx.draw_networkx_nodes(hub_ego, pos, nodelist=[largest_hub], **options)
plt.show()

View file

@ -0,0 +1,29 @@
"""
==========
Four Grids
==========
Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.grid_2d_graph(4, 4) # 4x4 grid
pos = nx.spring_layout(G, iterations=100)
plt.subplot(221)
nx.draw(G, pos, font_size=8)
plt.subplot(222)
nx.draw(G, pos, node_color="k", node_size=0, with_labels=False)
plt.subplot(223)
nx.draw(G, pos, node_color="g", node_size=250, with_labels=False, width=6)
plt.subplot(224)
H = G.to_directed()
nx.draw(H, pos, node_color="b", node_size=20, with_labels=False)
plt.show()

View file

@ -0,0 +1,51 @@
"""
===============
Giant Component
===============
This example illustrates the sudden appearance of a
giant connected component in a binomial random graph.
"""
import math
import matplotlib.pyplot as plt
import networkx as nx
# This example needs Graphviz and either PyGraphviz or pydot.
# from networkx.drawing.nx_pydot import graphviz_layout as layout
from networkx.drawing.nx_agraph import graphviz_layout as layout
# If you don't have pygraphviz or pydot, you can do this
# layout = nx.spring_layout
n = 150 # 150 nodes
# p value at which giant component (of size log(n) nodes) is expected
p_giant = 1.0 / (n - 1)
# p value at which graph is expected to become completely connected
p_conn = math.log(n) / float(n)
# the following range of p values should be close to the threshold
pvals = [0.003, 0.006, 0.008, 0.015]
region = 220 # for pylab 2x2 subplot layout
plt.subplots_adjust(left=0, right=1, bottom=0, top=0.95, wspace=0.01, hspace=0.01)
for p in pvals:
G = nx.binomial_graph(n, p)
pos = layout(G)
region += 1
plt.subplot(region)
plt.title(f"p = {p:.3f}")
nx.draw(G, pos, with_labels=False, node_size=10)
# identify largest connected component
Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
G0 = G.subgraph(Gcc[0])
nx.draw_networkx_edges(G0, pos, edge_color="r", width=6.0)
# show other connected components
for Gi in Gcc[1:]:
if len(Gi) > 1:
nx.draw_networkx_edges(
G.subgraph(Gi), pos, edge_color="r", alpha=0.3, width=5.0,
)
plt.show()

View file

@ -0,0 +1,19 @@
"""
=================
House With Colors
=================
Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.house_graph()
# explicitly set positions
pos = {0: (0, 0), 1: (1, 0), 2: (0, 1), 3: (1, 1), 4: (0.5, 2.0)}
nx.draw_networkx_nodes(G, pos, node_size=2000, nodelist=[4])
nx.draw_networkx_nodes(G, pos, node_size=3000, nodelist=[0, 1, 2, 3], node_color="b")
nx.draw_networkx_edges(G, pos, alpha=0.5, width=6)
plt.axis("off")
plt.show()

View file

@ -0,0 +1,96 @@
"""
===========
Knuth Miles
===========
`miles_graph()` returns an undirected graph over the 128 US cities from. The
cities each have location and population data. The edges are labeled with the
distance between the two cities.
This example is described in Section 1.1 of
Donald E. Knuth, "The Stanford GraphBase: A Platform for Combinatorial
Computing", ACM Press, New York, 1993.
http://www-cs-faculty.stanford.edu/~knuth/sgb.html
The data file can be found at:
- https://github.com/networkx/networkx/blob/master/examples/drawing/knuth_miles.txt.gz
"""
import gzip
import re
import matplotlib.pyplot as plt
import networkx as nx
def miles_graph():
""" Return the cites example graph in miles_dat.txt
from the Stanford GraphBase.
"""
# open file miles_dat.txt.gz (or miles_dat.txt)
fh = gzip.open("knuth_miles.txt.gz", "r")
G = nx.Graph()
G.position = {}
G.population = {}
cities = []
for line in fh.readlines():
line = line.decode()
if line.startswith("*"): # skip comments
continue
numfind = re.compile(r"^\d+")
if numfind.match(line): # this line is distances
dist = line.split()
for d in dist:
G.add_edge(city, cities[i], weight=int(d))
i = i + 1
else: # this line is a city, position, population
i = 1
(city, coordpop) = line.split("[")
cities.insert(0, city)
(coord, pop) = coordpop.split("]")
(y, x) = coord.split(",")
G.add_node(city)
# assign position - flip x axis for matplotlib, shift origin
G.position[city] = (-int(x) + 7500, int(y) - 3000)
G.population[city] = float(pop) / 1000.0
return G
G = miles_graph()
print("Loaded miles_dat.txt containing 128 cities.")
print(f"digraph has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges")
# make new graph of cites, edge if less then 300 miles between them
H = nx.Graph()
for v in G:
H.add_node(v)
for (u, v, d) in G.edges(data=True):
if d["weight"] < 300:
H.add_edge(u, v)
# draw with matplotlib/pylab
plt.figure(figsize=(8, 8))
# with nodes colored by degree sized by population
node_color = [float(H.degree(v)) for v in H]
nx.draw(
H,
G.position,
node_size=[G.population[v] for v in H],
node_color=node_color,
with_labels=False,
)
# scale the axes equally
plt.xlim(-5000, 500)
plt.ylim(-2000, 3500)
plt.show()

View file

@ -0,0 +1,52 @@
"""
=================
Labels And Colors
=================
Draw a graph with matplotlib, color by degree.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cubical_graph()
pos = nx.spring_layout(G) # positions for all nodes
# nodes
options = {"node_size": 500, "alpha": 0.8}
nx.draw_networkx_nodes(G, pos, nodelist=[0, 1, 2, 3], node_color="r", **options)
nx.draw_networkx_nodes(G, pos, nodelist=[4, 5, 6, 7], node_color="b", **options)
# edges
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(0, 1), (1, 2), (2, 3), (3, 0)],
width=8,
alpha=0.5,
edge_color="r",
)
nx.draw_networkx_edges(
G,
pos,
edgelist=[(4, 5), (5, 6), (6, 7), (7, 4)],
width=8,
alpha=0.5,
edge_color="b",
)
# some math labels
labels = {}
labels[0] = r"$a$"
labels[1] = r"$b$"
labels[2] = r"$c$"
labels[3] = r"$d$"
labels[4] = r"$\alpha$"
labels[5] = r"$\beta$"
labels[6] = r"$\gamma$"
labels[7] = r"$\delta$"
nx.draw_networkx_labels(G, pos, labels, font_size=16)
plt.axis("off")
plt.show()

View file

@ -0,0 +1,65 @@
"""
===========
Lanl Routes
===========
Routes to LANL from 186 sites on the Internet.
The data file can be found at:
- https://github.com/networkx/networkx/blob/master/examples/drawing/lanl_routes.edgelist
"""
import matplotlib.pyplot as plt
import networkx as nx
# This example needs Graphviz and either PyGraphviz or pydot
# from networkx.drawing.nx_pydot import graphviz_layout
from networkx.drawing.nx_agraph import graphviz_layout
def lanl_graph():
""" Return the lanl internet view graph from lanl.edges
"""
try:
fh = open("lanl_routes.edgelist")
except OSError:
print("lanl.edges not found")
raise
G = nx.Graph()
time = {}
time[0] = 0 # assign 0 to center node
for line in fh.readlines():
(head, tail, rtt) = line.split()
G.add_edge(int(head), int(tail))
time[int(head)] = float(rtt)
# get largest component and assign ping times to G0time dictionary
Gcc = sorted(nx.connected_components(G), key=len, reverse=True)[0]
G0 = G.subgraph(Gcc)
G0.rtt = {}
for n in G0:
G0.rtt[n] = time[n]
return G0
G = lanl_graph()
print(f"graph has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges")
print(nx.number_connected_components(G), "connected components")
plt.figure(figsize=(8, 8))
# use graphviz to find radial layout
pos = graphviz_layout(G, prog="twopi", root=0)
# draw nodes, coloring by rtt ping time
options = {"with_labels": False, "alpha": 0.5, "node_size": 15}
nx.draw(G, pos, node_color=[G.rtt[v] for v in G], **options)
# adjust the plot limits
xmax = 1.02 * max(xx for xx, yy in pos.values())
ymax = 1.02 * max(yy for xx, yy in pos.values())
plt.xlim(0, xmax)
plt.ylim(0, ymax)
plt.show()

View file

@ -0,0 +1,43 @@
"""
===================
Multipartite Layout
===================
"""
import itertools
import matplotlib.pyplot as plt
import networkx as nx
from networkx.utils import pairwise
subset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]
subset_color = [
"gold",
"violet",
"violet",
"violet",
"violet",
"limegreen",
"limegreen",
"darkorange",
]
def multilayered_graph(*subset_sizes):
extents = pairwise(itertools.accumulate((0,) + subset_sizes))
layers = [range(start, end) for start, end in extents]
G = nx.Graph()
for (i, layer) in enumerate(layers):
G.add_nodes_from(layer, layer=i)
for layer1, layer2 in pairwise(layers):
G.add_edges_from(itertools.product(layer1, layer2))
return G
G = multilayered_graph(*subset_sizes)
color = [subset_color[data["layer"]] for v, data in G.nodes(data=True)]
pos = nx.multipartite_layout(G, subset_key="layer")
plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_color=color, with_labels=False)
plt.axis("equal")
plt.show()

View file

@ -0,0 +1,15 @@
"""
=============
Node Colormap
=============
Draw a graph with matplotlib, color by degree.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.cycle_graph(24)
pos = nx.spring_layout(G, iterations=200)
nx.draw(G, pos, node_color=range(24), node_size=800, cmap=plt.cm.Blues)
plt.show()

View file

@ -0,0 +1,43 @@
"""
======================
Random Geometric Graph
======================
Example
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.random_geometric_graph(200, 0.125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, "pos")
# find node near center (0.5,0.5)
dmin = 1
ncenter = 0
for n in pos:
x, y = pos[n]
d = (x - 0.5) ** 2 + (y - 0.5) ** 2
if d < dmin:
ncenter = n
dmin = d
# color by path length from node near center
p = dict(nx.single_source_shortest_path_length(G, ncenter))
plt.figure(figsize=(8, 8))
nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(
G,
pos,
nodelist=list(p.keys()),
node_size=80,
node_color=list(p.values()),
cmap=plt.cm.Reds_r,
)
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)
plt.axis("off")
plt.show()

View file

@ -0,0 +1,46 @@
"""
=======
Sampson
=======
Sampson's monastery data.
Shows how to read data from a zip file and plot multiple frames.
The data file can be found at:
- https://github.com/networkx/networkx/blob/master/examples/drawing/sampson_data.zip
"""
import zipfile
from io import BytesIO as StringIO
import matplotlib.pyplot as plt
import networkx as nx
with zipfile.ZipFile("sampson_data.zip") as zf:
e1 = StringIO(zf.read("samplike1.txt"))
e2 = StringIO(zf.read("samplike2.txt"))
e3 = StringIO(zf.read("samplike3.txt"))
G1 = nx.read_edgelist(e1, delimiter="\t")
G2 = nx.read_edgelist(e2, delimiter="\t")
G3 = nx.read_edgelist(e3, delimiter="\t")
pos = nx.spring_layout(G3, iterations=100)
plt.clf()
plt.subplot(221)
plt.title("samplike1")
nx.draw(G1, pos, node_size=50, with_labels=False)
plt.subplot(222)
plt.title("samplike2")
nx.draw(G2, pos, node_size=50, with_labels=False)
plt.subplot(223)
plt.title("samplike3")
nx.draw(G3, pos, node_size=50, with_labels=False)
plt.subplot(224)
plt.title("samplike1,2,3")
nx.draw(G3, pos, edgelist=list(G3.edges()), node_size=50, with_labels=False)
nx.draw_networkx_edges(G1, pos, alpha=0.25)
nx.draw_networkx_edges(G2, pos, alpha=0.25)
plt.show()

View file

@ -0,0 +1,13 @@
"""
===========
Simple Path
===========
Draw a graph with matplotlib.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.path_graph(8)
nx.draw(G)
plt.show()

View file

@ -0,0 +1,58 @@
"""
==================
Spectral Embedding
==================
The spectral layout positions the nodes of the graph based on the
eigenvectors of the graph Laplacian $L = D - A$, where $A$ is the
adjacency matrix and $D$ is the degree matrix of the graph.
By default, the spectral layout will embed the graph in two
dimensions (you can embed your graph in other dimensions using the
``dim`` argument to either :func:`~drawing.nx_pylab.draw_spectral` or
:func:`~drawing.layout.spectral_layout`).
When the edges of the graph represent similarity between the incident
nodes, the spectral embedding will place highly similar nodes closer
to one another than nodes which are less similar.
This is particularly striking when you spectrally embed a grid
graph. In the full grid graph, the nodes in the center of the
graph are pulled apart more than nodes on the periphery.
As you remove internal nodes, this effect increases.
"""
import matplotlib.pyplot as plt
import networkx as nx
options = {"node_color": "C0", "node_size": 100}
G = nx.grid_2d_graph(6, 6)
plt.subplot(332)
nx.draw_spectral(G, **options)
G.remove_edge((2, 2), (2, 3))
plt.subplot(334)
nx.draw_spectral(G, **options)
G.remove_edge((3, 2), (3, 3))
plt.subplot(335)
nx.draw_spectral(G, **options)
G.remove_edge((2, 2), (3, 2))
plt.subplot(336)
nx.draw_spectral(G, **options)
G.remove_edge((2, 3), (3, 3))
plt.subplot(337)
nx.draw_spectral(G, **options)
G.remove_edge((1, 2), (1, 3))
plt.subplot(338)
nx.draw_spectral(G, **options)
G.remove_edge((4, 2), (4, 3))
plt.subplot(339)
nx.draw_spectral(G, **options)
plt.show()

View file

@ -0,0 +1,60 @@
"""
==========
Unix Email
==========
Create a directed graph, allowing multiple edges and self loops, from a unix
mailbox. The nodes are email addresses with links that point from the sender
to the receivers. The edge data is a Python email.Message object which
contains all of the email message data.
This example shows the power of `DiGraph` to hold edge data of arbitrary Python
objects (in this case a list of email messages).
The sample unix email mailbox called "unix_email.mbox" may be found here:
- https://github.com/networkx/networkx/blob/master/examples/drawing/unix_email.mbox
"""
from email.utils import getaddresses, parseaddr
import mailbox
import matplotlib.pyplot as plt
import networkx as nx
# unix mailbox recipe
# see https://docs.python.org/3/library/mailbox.html
def mbox_graph():
mbox = mailbox.mbox("unix_email.mbox") # parse unix mailbox
G = nx.MultiDiGraph() # create empty graph
# parse each messages and build graph
for msg in mbox: # msg is python email.Message.Message object
(source_name, source_addr) = parseaddr(msg["From"]) # sender
# get all recipients
# see https://docs.python.org/3/library/email.html
tos = msg.get_all("to", [])
ccs = msg.get_all("cc", [])
resent_tos = msg.get_all("resent-to", [])
resent_ccs = msg.get_all("resent-cc", [])
all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
# now add the edges for this mail message
for (target_name, target_addr) in all_recipients:
G.add_edge(source_addr, target_addr, message=msg)
return G
G = mbox_graph()
# print edges with message subject
for (u, v, d) in G.edges(data=True):
print(f"From: {u} To: {v} Subject: {d['message']['Subject']}")
pos = nx.spring_layout(G, iterations=10)
nx.draw(G, pos, node_size=0, alpha=0.4, edge_color="r", font_size=16, with_labels=True)
plt.show()

View file

@ -0,0 +1,38 @@
"""
==============
Weighted Graph
==============
An example using Graph as a weighted network.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge("a", "b", weight=0.6)
G.add_edge("a", "c", weight=0.2)
G.add_edge("c", "d", weight=0.1)
G.add_edge("c", "e", weight=0.7)
G.add_edge("c", "f", weight=0.9)
G.add_edge("a", "d", weight=0.3)
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
pos = nx.spring_layout(G) # positions for all nodes
# nodes
nx.draw_networkx_nodes(G, pos, node_size=700)
# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=6)
nx.draw_networkx_edges(
G, pos, edgelist=esmall, width=6, alpha=0.5, edge_color="b", style="dashed"
)
# labels
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")
plt.axis("off")
plt.show()

View file

@ -0,0 +1,84 @@
From alice@edu Thu Jun 16 16:12:12 2005
From: Alice <alice@edu>
Subject: NetworkX
Date: Thu, 16 Jun 2005 16:12:13 -0700
To: Bob <bob@gov>
Status: RO
Content-Length: 86
Lines: 5
Bob, check out the new networkx release - you and
Carol might really like it.
Alice
From bob@gov Thu Jun 16 18:13:12 2005
Return-Path: <bob@gov>
Subject: Re: NetworkX
From: Bob <bob@gov>
To: Alice <alice@edu>
Content-Type: text/plain
Date: Thu, 16 Jun 2005 18:13:12 -0700
Status: RO
Content-Length: 26
Lines: 4
Thanks for the tip.
Bob
From ted@com Thu Jul 28 09:53:31 2005
Return-Path: <ted@com>
Subject: Graph package in Python?
From: Ted <ted@com>
To: Bob <bob@gov>
Content-Type: text/plain
Date: Thu, 28 Jul 2005 09:47:03 -0700
Status: RO
Content-Length: 90
Lines: 3
Hey Ted - I'm looking for a Python package for
graphs and networks. Do you know of any?
From bob@gov Thu Jul 28 09:59:31 2005
Return-Path: <bob@gov>
Subject: Re: Graph package in Python?
From: Bob <bob@gov>
To: Ted <ted@com>
Content-Type: text/plain
Date: Thu, 28 Jul 2005 09:59:03 -0700
Status: RO
Content-Length: 180
Lines: 9
Check out the NetworkX package - Alice sent me the tip!
Bob
>> bob@gov scrawled:
>> Hey Ted - I'm looking for a Python package for
>> graphs and networks. Do you know of any?
From ted@com Thu Jul 28 15:53:31 2005
Return-Path: <ted@com>
Subject: get together for lunch to discuss Networks?
From: Ted <ted@com>
To: Bob <bob@gov>, Carol <carol@gov>, Alice <alice@edu>
Content-Type: text/plain
Date: Thu, 28 Jul 2005 15:47:03 -0700
Status: RO
Content-Length: 139
Lines: 5
Hey everyrone! Want to meet at that restaurant on the
island in Konigsburg tonight? Bring your laptops
and we can install NetworkX.
Ted

View file

@ -0,0 +1,2 @@
Graph
-----

View file

@ -0,0 +1,25 @@
"""
======
Atlas2
======
Write first 20 graphs from the graph atlas as graphviz dot files
Gn.dot where n=0,19.
"""
import networkx as nx
from networkx.generators.atlas import graph_atlas_g
atlas = graph_atlas_g()[0:20]
for G in atlas:
print(
f"{G.name} has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges"
)
A = nx.nx_agraph.to_agraph(G)
A.graph_attr["label"] = G.name
# set default node attributes
A.node_attr["color"] = "red"
A.node_attr["style"] = "filled"
A.node_attr["shape"] = "circle"
A.write(G.name + ".dot")

View file

@ -0,0 +1,30 @@
"""
===============
Degree Sequence
===============
Random graph from given degree sequence.
"""
import matplotlib.pyplot as plt
from networkx import nx
z = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]
print(nx.is_graphical(z))
print("Configuration model")
G = nx.configuration_model(z) # configuration model
degree_sequence = [d for n, d in G.degree()] # degree sequence
print(f"Degree sequence {degree_sequence}")
print("Degree histogram")
hist = {}
for d in degree_sequence:
if d in hist:
hist[d] += 1
else:
hist[d] = 1
print("degree #nodes")
for d in hist:
print(f"{d:4} {hist[d]:6}")
nx.draw(G)
plt.show()

View file

@ -0,0 +1,33 @@
"""
===========
Erdos Renyi
===========
Create an G{n,m} random graph with n nodes and m edges
and report some properties.
This graph is sometimes called the Erdős-Rényi graph
but is different from G{n,p} or binomial_graph which is also
sometimes called the Erdős-Rényi graph.
"""
import matplotlib.pyplot as plt
from networkx import nx
n = 10 # 10 nodes
m = 20 # 20 edges
G = nx.gnm_random_graph(n, m)
# some properties
print("node degree clustering")
for v in nx.nodes(G):
print(f"{v} {nx.degree(G, v)} {nx.clustering(G, v)}")
print()
print("the adjacency list")
for line in nx.generate_adjlist(G):
print(line)
nx.draw(G)
plt.show()

View file

@ -0,0 +1,21 @@
"""
========================
Expected Degree Sequence
========================
Random graph from given degree sequence.
"""
import networkx as nx
from networkx.generators.degree_seq import expected_degree_graph
# make a random graph of 500 nodes with expected degrees of 50
n = 500 # n nodes
p = 0.1
w = [p * n for i in range(n)] # w = p*n for all nodes
G = expected_degree_graph(w) # configuration model
print("Degree histogram")
print("degree (#nodes) ****")
dh = nx.degree_histogram(G)
for i, d in enumerate(dh):
print(f"{i:2} ({d:2}) {'*'*d}")

View file

@ -0,0 +1,47 @@
"""
========
Football
========
Load football network in GML format and compute some network statistcs.
Shows how to download GML graph in a zipped file, unpack it, and load
into a NetworkX graph.
Requires Internet connection to download the URL
http://www-personal.umich.edu/~mejn/netdata/football.zip
"""
import urllib.request as urllib
import io
import zipfile
import matplotlib.pyplot as plt
import networkx as nx
url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"
sock = urllib.urlopen(url) # open URL
s = io.BytesIO(sock.read()) # read into BytesIO "file"
sock.close()
zf = zipfile.ZipFile(s) # zipfile object
txt = zf.read("football.txt").decode() # read info file
gml = zf.read("football.gml").decode() # read gml data
# throw away bogus first line with # from mejn files
gml = gml.split("\n")[1:]
G = nx.parse_gml(gml) # parse gml data
print(txt)
# print degree for each team - number of games
for n, d in G.degree():
print(f"{n:20} {d:2}")
options = {
"node_color": "black",
"node_size": 50,
"linewidths": 0,
"width": 0.1,
}
nx.draw(G, **options)
plt.show()

View file

@ -0,0 +1,25 @@
"""
===========
Karate Club
===========
Zachary's Karate Club graph
Data file from:
http://vlado.fmf.uni-lj.si/pub/networks/data/Ucinet/UciData.htm
Zachary W. (1977).
An information flow model for conflict and fission in small groups.
Journal of Anthropological Research, 33, 452-473.
"""
import matplotlib.pyplot as plt
import networkx as nx
G = nx.karate_club_graph()
print("Node Degree")
for v in G:
print(f"{v:4} {G.degree(v):6}")
nx.draw_circular(G, with_labels=True)
plt.show()

View file

@ -0,0 +1,134 @@
"""
=========================
Napoleon Russian Campaign
=========================
Minard's data from Napoleon's 1812-1813 Russian Campaign.
http://www.math.yorku.ca/SCS/Gallery/minard/minard.txt
"""
import matplotlib.pyplot as plt
import networkx as nx
def minard_graph():
data1 = """\
24.0,54.9,340000,A,1
24.5,55.0,340000,A,1
25.5,54.5,340000,A,1
26.0,54.7,320000,A,1
27.0,54.8,300000,A,1
28.0,54.9,280000,A,1
28.5,55.0,240000,A,1
29.0,55.1,210000,A,1
30.0,55.2,180000,A,1
30.3,55.3,175000,A,1
32.0,54.8,145000,A,1
33.2,54.9,140000,A,1
34.4,55.5,127100,A,1
35.5,55.4,100000,A,1
36.0,55.5,100000,A,1
37.6,55.8,100000,A,1
37.7,55.7,100000,R,1
37.5,55.7,98000,R,1
37.0,55.0,97000,R,1
36.8,55.0,96000,R,1
35.4,55.3,87000,R,1
34.3,55.2,55000,R,1
33.3,54.8,37000,R,1
32.0,54.6,24000,R,1
30.4,54.4,20000,R,1
29.2,54.3,20000,R,1
28.5,54.2,20000,R,1
28.3,54.3,20000,R,1
27.5,54.5,20000,R,1
26.8,54.3,12000,R,1
26.4,54.4,14000,R,1
25.0,54.4,8000,R,1
24.4,54.4,4000,R,1
24.2,54.4,4000,R,1
24.1,54.4,4000,R,1"""
data2 = """\
24.0,55.1,60000,A,2
24.5,55.2,60000,A,2
25.5,54.7,60000,A,2
26.6,55.7,40000,A,2
27.4,55.6,33000,A,2
28.7,55.5,33000,R,2
29.2,54.2,30000,R,2
28.5,54.1,30000,R,2
28.3,54.2,28000,R,2"""
data3 = """\
24.0,55.2,22000,A,3
24.5,55.3,22000,A,3
24.6,55.8,6000,A,3
24.6,55.8,6000,R,3
24.2,54.4,6000,R,3
24.1,54.4,6000,R,3"""
cities = """\
24.0,55.0,Kowno
25.3,54.7,Wilna
26.4,54.4,Smorgoni
26.8,54.3,Moiodexno
27.7,55.2,Gloubokoe
27.6,53.9,Minsk
28.5,54.3,Studienska
28.7,55.5,Polotzk
29.2,54.4,Bobr
30.2,55.3,Witebsk
30.4,54.5,Orscha
30.4,53.9,Mohilow
32.0,54.8,Smolensk
33.2,54.9,Dorogobouge
34.3,55.2,Wixma
34.4,55.5,Chjat
36.0,55.5,Mojaisk
37.6,55.8,Moscou
36.6,55.3,Tarantino
36.5,55.0,Malo-Jarosewii"""
c = {}
for line in cities.split("\n"):
x, y, name = line.split(",")
c[name] = (float(x), float(y))
g = []
for data in [data1, data2, data3]:
G = nx.Graph()
i = 0
G.pos = {} # location
G.pop = {} # size
last = None
for line in data.split("\n"):
x, y, p, r, n = line.split(",")
G.pos[i] = (float(x), float(y))
G.pop[i] = int(p)
if last is None:
last = i
else:
G.add_edge(i, last, **{r: int(n)})
last = i
i = i + 1
g.append(G)
return g, c
(g, city) = minard_graph()
plt.figure(1, figsize=(11, 5))
plt.clf()
colors = ["b", "g", "r"]
for G in g:
c = colors.pop(0)
node_size = [int(G.pop[n] / 300.0) for n in G]
nx.draw_networkx_edges(G, G.pos, edge_color=c, width=4, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=node_size, node_color=c, alpha=0.5)
nx.draw_networkx_nodes(G, G.pos, node_size=5, node_color="k")
for c in city:
x, y = city[c]
plt.text(x, y + 0.1, c)
plt.show()

View file

@ -0,0 +1,80 @@
"""
=====
Roget
=====
Build a directed graph of 1022 categories and 5075 cross-references as defined
in the 1879 version of Roget's Thesaurus. This example is described in Section
1.2 of
Donald E. Knuth, "The Stanford GraphBase: A Platform for Combinatorial
Computing", ACM Press, New York, 1993.
http://www-cs-faculty.stanford.edu/~knuth/sgb.html
Note that one of the 5075 cross references is a self loop yet it is included in
the graph built here because the standard networkx `DiGraph` class allows self
loops. (cf. 400pungency:400 401 403 405).
The data file can be found at:
- https://github.com/networkx/networkx/blob/master/examples/graph/roget_dat.txt.gz
"""
import gzip
import re
import sys
import matplotlib.pyplot as plt
from networkx import nx
def roget_graph():
""" Return the thesaurus graph from the roget.dat example in
the Stanford Graph Base.
"""
# open file roget_dat.txt.gz
fh = gzip.open("roget_dat.txt.gz", "r")
G = nx.DiGraph()
for line in fh.readlines():
line = line.decode()
if line.startswith("*"): # skip comments
continue
if line.startswith(" "): # this is a continuation line, append
line = oldline + line
if line.endswith("\\\n"): # continuation line, buffer, goto next
oldline = line.strip("\\\n")
continue
(headname, tails) = line.split(":")
# head
numfind = re.compile(r"^\d+") # re to find the number of this word
head = numfind.findall(headname)[0] # get the number
G.add_node(head)
for tail in tails.split():
if head == tail:
print("skipping self loop", head, tail, file=sys.stderr)
G.add_edge(head, tail)
return G
G = roget_graph()
print("Loaded roget_dat.txt containing 1022 categories.")
print(f"digraph has {nx.number_of_nodes(G)} nodes with {nx.number_of_edges(G)} edges")
UG = G.to_undirected()
print(nx.number_connected_components(UG), "connected components")
options = {
"node_color": "black",
"node_size": 1,
"edge_color": "gray",
"linewidths": 0,
"width": 0.1,
}
nx.draw_circular(UG, **options)
plt.show()

Some files were not shown because too many files have changed in this diff Show more