summaryrefslogtreecommitdiff
path: root/_downloads
diff options
context:
space:
mode:
Diffstat (limited to '_downloads')
-rw-r--r--_downloads/07fcc19ba03226cd3d83d4e40ec44385/auto_examples_python.zipbin131275 -> 132315 bytes
-rw-r--r--_downloads/097285ee56b831e03a1cf029dd432ed7/plot_multipartite_graph.ipynb2
-rw-r--r--_downloads/0a756ab7ea4b899fa151e327a4dce8d2/plot_snap.py26
-rw-r--r--_downloads/0adfc212f7d48fa789c0e2d6038bd947/plot_maximum_independent_set.ipynb54
-rw-r--r--_downloads/1ec7b0dc32695fec6a38afb4f6eb4b16/plot_dedensification.ipynb2
-rw-r--r--_downloads/213697eef7dec7ebca6ee2e064eb9c24/plot_unix_email.py4
-rw-r--r--_downloads/23bd8a075fec100ee75fd165948aad05/plot_chess_masters.ipynb2
-rw-r--r--_downloads/27102b9986eea2f742603c5d8496d2f8/plot_degree_sequence.py4
-rw-r--r--_downloads/2a66ab839d29e0e6b9e6c0db64e50f74/plot_triad_types.ipynb2
-rw-r--r--_downloads/388158421a67216f605c1bbf9aa310bf/plot_chess_masters.py6
-rw-r--r--_downloads/3a5de2178f4d4bb1892ea7036709f1bb/plot_morse_trie.ipynb2
-rw-r--r--_downloads/3adca49f1b673454c4138bf3eea6d2c5/plot_blockmodel.ipynb2
-rw-r--r--_downloads/461dfe5db4853b4fe245b7ec677c3f2e/plot_words.ipynb2
-rw-r--r--_downloads/4aba8bc455260708046bf8ed7dcf62c6/plot_unix_email.ipynb2
-rw-r--r--_downloads/60379a4283563d425090aaae07ab115a/plot_morse_trie.py1
-rw-r--r--_downloads/6a1e333663010969e61d07b33c7845f0/plot_davis_club.py2
-rw-r--r--_downloads/6cb4bf689cf53c849bce13cbab13eaec/plot_multipartite_graph.py2
-rw-r--r--_downloads/6e2f41828cdc6170bb3c4517097bdfc8/plot_snap.ipynb2
-rw-r--r--_downloads/6f1e7a639e0699d6164445b55e6c116d/auto_examples_jupyter.zipbin207163 -> 209225 bytes
-rw-r--r--_downloads/73da379af64659b61cf9760ce786a7d4/plot_betweenness_centrality.ipynb4
-rw-r--r--_downloads/75057ffc857a59555c9505a02935679d/plot_degree_sequence.ipynb2
-rw-r--r--_downloads/795910d260da8b0e1d747500a0b724d6/plot_davis_club.ipynb2
-rw-r--r--_downloads/868e28431bab2565b22bfbab847e1153/plot_dedensification.py2
-rw-r--r--_downloads/8a508c78cefb7056d5a2d2af5a610ed4/plot_maximum_independent_set.py44
-rw-r--r--_downloads/b3018a1aab7bffbd1426574de5a8c65a/plot_betweenness_centrality.py10
-rw-r--r--_downloads/b7a826e19c8bd8bafecaae1ae69c7d1d/plot_triad_types.py2
-rw-r--r--_downloads/d071301e92e895067d308e076bb57540/plot_knuth_miles.ipynb2
-rw-r--r--_downloads/e6a489a8b2deb49ed237fac38a28f429/plot_words.py2
-rw-r--r--_downloads/e921c603ea1764485dc9acff178a2f05/plot_knuth_miles.py4
-rw-r--r--_downloads/efbe368eaa1e457c6c03d3f5a636063a/plot_blockmodel.py2
-rw-r--r--_downloads/networkx_reference.pdfbin3533843 -> 3555340 bytes
31 files changed, 147 insertions, 46 deletions
diff --git a/_downloads/07fcc19ba03226cd3d83d4e40ec44385/auto_examples_python.zip b/_downloads/07fcc19ba03226cd3d83d4e40ec44385/auto_examples_python.zip
index fa765043..d08dad65 100644
--- a/_downloads/07fcc19ba03226cd3d83d4e40ec44385/auto_examples_python.zip
+++ b/_downloads/07fcc19ba03226cd3d83d4e40ec44385/auto_examples_python.zip
Binary files differ
diff --git a/_downloads/097285ee56b831e03a1cf029dd432ed7/plot_multipartite_graph.ipynb b/_downloads/097285ee56b831e03a1cf029dd432ed7/plot_multipartite_graph.ipynb
index 4d05ce14..bd43fae2 100644
--- a/_downloads/097285ee56b831e03a1cf029dd432ed7/plot_multipartite_graph.ipynb
+++ b/_downloads/097285ee56b831e03a1cf029dd432ed7/plot_multipartite_graph.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import itertools\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nsubset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]\nsubset_color = [\n \"gold\",\n \"violet\",\n \"violet\",\n \"violet\",\n \"violet\",\n \"limegreen\",\n \"limegreen\",\n \"darkorange\",\n]\n\n\ndef multilayered_graph(*subset_sizes):\n extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))\n layers = [range(start, end) for start, end in extents]\n G = nx.Graph()\n for (i, layer) in enumerate(layers):\n G.add_nodes_from(layer, layer=i)\n for layer1, layer2 in nx.utils.pairwise(layers):\n G.add_edges_from(itertools.product(layer1, layer2))\n return G\n\n\nG = multilayered_graph(*subset_sizes)\ncolor = [subset_color[data[\"layer\"]] for v, data in G.nodes(data=True)]\npos = nx.multipartite_layout(G, subset_key=\"layer\")\nplt.figure(figsize=(8, 8))\nnx.draw(G, pos, node_color=color, with_labels=False)\nplt.axis(\"equal\")\nplt.show()"
+ "import itertools\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\nsubset_sizes = [5, 5, 4, 3, 2, 4, 4, 3]\nsubset_color = [\n \"gold\",\n \"violet\",\n \"violet\",\n \"violet\",\n \"violet\",\n \"limegreen\",\n \"limegreen\",\n \"darkorange\",\n]\n\n\ndef multilayered_graph(*subset_sizes):\n extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))\n layers = [range(start, end) for start, end in extents]\n G = nx.Graph()\n for i, layer in enumerate(layers):\n G.add_nodes_from(layer, layer=i)\n for layer1, layer2 in nx.utils.pairwise(layers):\n G.add_edges_from(itertools.product(layer1, layer2))\n return G\n\n\nG = multilayered_graph(*subset_sizes)\ncolor = [subset_color[data[\"layer\"]] for v, data in G.nodes(data=True)]\npos = nx.multipartite_layout(G, subset_key=\"layer\")\nplt.figure(figsize=(8, 8))\nnx.draw(G, pos, node_color=color, with_labels=False)\nplt.axis(\"equal\")\nplt.show()"
]
}
],
diff --git a/_downloads/0a756ab7ea4b899fa151e327a4dce8d2/plot_snap.py b/_downloads/0a756ab7ea4b899fa151e327a4dce8d2/plot_snap.py
index 85ea71de..221f4f3f 100644
--- a/_downloads/0a756ab7ea4b899fa151e327a4dce8d2/plot_snap.py
+++ b/_downloads/0a756ab7ea4b899fa151e327a4dce8d2/plot_snap.py
@@ -16,18 +16,18 @@ import matplotlib.pyplot as plt
nodes = {
- "A": dict(color="Red"),
- "B": dict(color="Red"),
- "C": dict(color="Red"),
- "D": dict(color="Red"),
- "E": dict(color="Blue"),
- "F": dict(color="Blue"),
- "G": dict(color="Blue"),
- "H": dict(color="Blue"),
- "I": dict(color="Yellow"),
- "J": dict(color="Yellow"),
- "K": dict(color="Yellow"),
- "L": dict(color="Yellow"),
+ "A": {"color": "Red"},
+ "B": {"color": "Red"},
+ "C": {"color": "Red"},
+ "D": {"color": "Red"},
+ "E": {"color": "Blue"},
+ "F": {"color": "Blue"},
+ "G": {"color": "Blue"},
+ "H": {"color": "Blue"},
+ "I": {"color": "Yellow"},
+ "J": {"color": "Yellow"},
+ "K": {"color": "Yellow"},
+ "L": {"color": "Yellow"},
}
edges = [
("A", "B", "Strong"),
@@ -50,7 +50,7 @@ original_graph.add_edges_from((u, v, {"type": label}) for u, v, label in edges)
plt.suptitle("SNAP Summarization")
-base_options = dict(with_labels=True, edgecolors="black", node_size=500)
+base_options = {"with_labels": True, "edgecolors": "black", "node_size": 500}
ax1 = plt.subplot(1, 2, 1)
plt.title(
diff --git a/_downloads/0adfc212f7d48fa789c0e2d6038bd947/plot_maximum_independent_set.ipynb b/_downloads/0adfc212f7d48fa789c0e2d6038bd947/plot_maximum_independent_set.ipynb
new file mode 100644
index 00000000..16e26750
--- /dev/null
+++ b/_downloads/0adfc212f7d48fa789c0e2d6038bd947/plot_maximum_independent_set.ipynb
@@ -0,0 +1,54 @@
+{
+ "cells": [
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "%matplotlib inline"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "\n# Maximum Independent Set\n\nAn independent set is a set of vertices in a graph where no two vertices in the\nset are adjacent. The maximum independent set is the independent set of largest\npossible size for a given graph.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "collapsed": false
+ },
+ "outputs": [],
+ "source": [
+ "import numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom networkx.algorithms import approximation as approx\n\nG = nx.Graph(\n [\n (1, 2),\n (7, 2),\n (3, 9),\n (3, 2),\n (7, 6),\n (5, 2),\n (1, 5),\n (2, 8),\n (10, 2),\n (1, 7),\n (6, 1),\n (6, 9),\n (8, 4),\n (9, 4),\n ]\n)\n\nI = approx.maximum_independent_set(G)\nprint(f\"Maximum independent set of G: {I}\")\n\npos = nx.spring_layout(G, seed=39299899)\nnx.draw(\n G,\n pos=pos,\n with_labels=True,\n node_color=[\"tab:red\" if n in I else \"tab:blue\" for n in G],\n)"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.9.16"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+} \ No newline at end of file
diff --git a/_downloads/1ec7b0dc32695fec6a38afb4f6eb4b16/plot_dedensification.ipynb b/_downloads/1ec7b0dc32695fec6a38afb4f6eb4b16/plot_dedensification.ipynb
index c6b63826..9856be24 100644
--- a/_downloads/1ec7b0dc32695fec6a38afb4f6eb4b16/plot_dedensification.ipynb
+++ b/_downloads/1ec7b0dc32695fec6a38afb4f6eb4b16/plot_dedensification.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import matplotlib.pyplot as plt\nimport networkx as nx\n\nplt.suptitle(\"Dedensification\")\n\noriginal_graph = nx.DiGraph()\nwhite_nodes = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]\nred_nodes = [\"A\", \"B\", \"C\"]\nnode_sizes = [250 for node in white_nodes + red_nodes]\nnode_colors = [\"white\" for n in white_nodes] + [\"red\" for n in red_nodes]\n\noriginal_graph.add_nodes_from(white_nodes + red_nodes)\noriginal_graph.add_edges_from(\n [\n (\"1\", \"C\"),\n (\"1\", \"B\"),\n (\"2\", \"C\"),\n (\"2\", \"B\"),\n (\"2\", \"A\"),\n (\"3\", \"B\"),\n (\"3\", \"A\"),\n (\"3\", \"6\"),\n (\"4\", \"C\"),\n (\"4\", \"B\"),\n (\"4\", \"A\"),\n (\"5\", \"B\"),\n (\"5\", \"A\"),\n (\"6\", \"5\"),\n (\"A\", \"6\"),\n ]\n)\nbase_options = dict(with_labels=True, edgecolors=\"black\")\npos = {\n \"3\": (0, 1),\n \"2\": (0, 2),\n \"1\": (0, 3),\n \"6\": (1, 0),\n \"A\": (1, 1),\n \"B\": (1, 2),\n \"C\": (1, 3),\n \"4\": (2, 3),\n \"5\": (2, 1),\n}\nax1 = plt.subplot(1, 2, 1)\nplt.title(\"Original (%s edges)\" % original_graph.number_of_edges())\nnx.draw_networkx(original_graph, pos=pos, node_color=node_colors, **base_options)\n\nnonexp_graph, compression_nodes = nx.summarization.dedensify(\n original_graph, threshold=2, copy=False\n)\nnonexp_node_colors = list(node_colors)\nnonexp_node_sizes = list(node_sizes)\nfor node in compression_nodes:\n nonexp_node_colors.append(\"yellow\")\n nonexp_node_sizes.append(600)\nplt.subplot(1, 2, 2)\n\nplt.title(\"Dedensified (%s edges)\" % nonexp_graph.number_of_edges())\nnonexp_pos = {\n \"5\": (0, 0),\n \"B\": (0, 2),\n \"1\": (0, 3),\n \"6\": (1, 0.75),\n \"3\": (1.5, 1.5),\n \"A\": (2, 0),\n \"C\": (2, 3),\n \"4\": (3, 1.5),\n \"2\": (3, 2.5),\n}\nc_nodes = list(compression_nodes)\nc_nodes.sort()\nfor spot, node in enumerate(c_nodes):\n nonexp_pos[node] = (2, spot + 2)\nnx.draw_networkx(\n nonexp_graph,\n pos=nonexp_pos,\n node_color=nonexp_node_colors,\n node_size=nonexp_node_sizes,\n **base_options\n)\n\nplt.tight_layout()\nplt.show()"
+ "import matplotlib.pyplot as plt\nimport networkx as nx\n\nplt.suptitle(\"Dedensification\")\n\noriginal_graph = nx.DiGraph()\nwhite_nodes = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]\nred_nodes = [\"A\", \"B\", \"C\"]\nnode_sizes = [250 for node in white_nodes + red_nodes]\nnode_colors = [\"white\" for n in white_nodes] + [\"red\" for n in red_nodes]\n\noriginal_graph.add_nodes_from(white_nodes + red_nodes)\noriginal_graph.add_edges_from(\n [\n (\"1\", \"C\"),\n (\"1\", \"B\"),\n (\"2\", \"C\"),\n (\"2\", \"B\"),\n (\"2\", \"A\"),\n (\"3\", \"B\"),\n (\"3\", \"A\"),\n (\"3\", \"6\"),\n (\"4\", \"C\"),\n (\"4\", \"B\"),\n (\"4\", \"A\"),\n (\"5\", \"B\"),\n (\"5\", \"A\"),\n (\"6\", \"5\"),\n (\"A\", \"6\"),\n ]\n)\nbase_options = {\"with_labels\": True, \"edgecolors\": \"black\"}\npos = {\n \"3\": (0, 1),\n \"2\": (0, 2),\n \"1\": (0, 3),\n \"6\": (1, 0),\n \"A\": (1, 1),\n \"B\": (1, 2),\n \"C\": (1, 3),\n \"4\": (2, 3),\n \"5\": (2, 1),\n}\nax1 = plt.subplot(1, 2, 1)\nplt.title(\"Original (%s edges)\" % original_graph.number_of_edges())\nnx.draw_networkx(original_graph, pos=pos, node_color=node_colors, **base_options)\n\nnonexp_graph, compression_nodes = nx.summarization.dedensify(\n original_graph, threshold=2, copy=False\n)\nnonexp_node_colors = list(node_colors)\nnonexp_node_sizes = list(node_sizes)\nfor node in compression_nodes:\n nonexp_node_colors.append(\"yellow\")\n nonexp_node_sizes.append(600)\nplt.subplot(1, 2, 2)\n\nplt.title(\"Dedensified (%s edges)\" % nonexp_graph.number_of_edges())\nnonexp_pos = {\n \"5\": (0, 0),\n \"B\": (0, 2),\n \"1\": (0, 3),\n \"6\": (1, 0.75),\n \"3\": (1.5, 1.5),\n \"A\": (2, 0),\n \"C\": (2, 3),\n \"4\": (3, 1.5),\n \"2\": (3, 2.5),\n}\nc_nodes = list(compression_nodes)\nc_nodes.sort()\nfor spot, node in enumerate(c_nodes):\n nonexp_pos[node] = (2, spot + 2)\nnx.draw_networkx(\n nonexp_graph,\n pos=nonexp_pos,\n node_color=nonexp_node_colors,\n node_size=nonexp_node_sizes,\n **base_options\n)\n\nplt.tight_layout()\nplt.show()"
]
}
],
diff --git a/_downloads/213697eef7dec7ebca6ee2e064eb9c24/plot_unix_email.py b/_downloads/213697eef7dec7ebca6ee2e064eb9c24/plot_unix_email.py
index 25fce7ae..748b5491 100644
--- a/_downloads/213697eef7dec7ebca6ee2e064eb9c24/plot_unix_email.py
+++ b/_downloads/213697eef7dec7ebca6ee2e064eb9c24/plot_unix_email.py
@@ -43,7 +43,7 @@ def mbox_graph():
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:
+ for target_name, target_addr in all_recipients:
G.add_edge(source_addr, target_addr, message=msg)
return G
@@ -52,7 +52,7 @@ def mbox_graph():
G = mbox_graph()
# print edges with message subject
-for (u, v, d) in G.edges(data=True):
+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, seed=227)
diff --git a/_downloads/23bd8a075fec100ee75fd165948aad05/plot_chess_masters.ipynb b/_downloads/23bd8a075fec100ee75fd165948aad05/plot_chess_masters.ipynb
index 13bd1f7c..c28c7b10 100644
--- a/_downloads/23bd8a075fec100ee75fd165948aad05/plot_chess_masters.ipynb
+++ b/_downloads/23bd8a075fec100ee75fd165948aad05/plot_chess_masters.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import matplotlib.pyplot as plt\nimport networkx as nx\n\n# tag names specifying what game info should be\n# stored in the dict on each digraph edge\ngame_details = [\"Event\", \"Date\", \"Result\", \"ECO\", \"Site\"]\n\n\ndef chess_pgn_graph(pgn_file=\"chess_masters_WCC.pgn.bz2\"):\n \"\"\"Read chess games in pgn format in pgn_file.\n\n Filenames ending in .bz2 will be uncompressed.\n\n Return the MultiDiGraph of players connected by a chess game.\n Edges contain game data in a dict.\n\n \"\"\"\n import bz2\n\n G = nx.MultiDiGraph()\n game = {}\n with bz2.BZ2File(pgn_file) as datafile:\n lines = [line.decode().rstrip(\"\\r\\n\") for line in datafile]\n for line in lines:\n if line.startswith(\"[\"):\n tag, value = line[1:-1].split(\" \", 1)\n game[str(tag)] = value.strip('\"')\n else:\n # empty line after tag set indicates\n # we finished reading game info\n if game:\n white = game.pop(\"White\")\n black = game.pop(\"Black\")\n G.add_edge(white, black, **game)\n game = {}\n return G\n\n\nG = chess_pgn_graph()\n\nprint(\n f\"Loaded {G.number_of_edges()} chess games between {G.number_of_nodes()} players\\n\"\n)\n\n# identify connected components of the undirected version\nH = G.to_undirected()\nGcc = [H.subgraph(c) for c in nx.connected_components(H)]\nif len(Gcc) > 1:\n print(f\"Note the disconnected component consisting of:\\n{Gcc[1].nodes()}\")\n\n# find all games with B97 opening (as described in ECO)\nopenings = {game_info[\"ECO\"] for (white, black, game_info) in G.edges(data=True)}\nprint(f\"\\nFrom a total of {len(openings)} different openings,\")\nprint(\"the following games used the Sicilian opening\")\nprint('with the Najdorff 7...Qb6 \"Poisoned Pawn\" variation.\\n')\n\nfor (white, black, game_info) in G.edges(data=True):\n if game_info[\"ECO\"] == \"B97\":\n summary = f\"{white} vs {black}\\n\"\n for k, v in game_info.items():\n summary += f\" {k}: {v}\\n\"\n summary += \"\\n\"\n print(summary)\n\n# make new undirected graph H without multi-edges\nH = nx.Graph(G)\n\n# edge width is proportional number of games played\nedgewidth = [len(G.get_edge_data(u, v)) for u, v in H.edges()]\n\n# node size is proportional to number of games won\nwins = dict.fromkeys(G.nodes(), 0.0)\nfor (u, v, d) in G.edges(data=True):\n r = d[\"Result\"].split(\"-\")\n if r[0] == \"1\":\n wins[u] += 1.0\n elif r[0] == \"1/2\":\n wins[u] += 0.5\n wins[v] += 0.5\n else:\n wins[v] += 1.0\nnodesize = [wins[v] * 50 for v in H]\n\n# Generate layout for visualization\npos = nx.kamada_kawai_layout(H)\n# Manual tweaking to limit node label overlap in the visualization\npos[\"Reshevsky, Samuel H\"] += (0.05, -0.10)\npos[\"Botvinnik, Mikhail M\"] += (0.03, -0.06)\npos[\"Smyslov, Vassily V\"] += (0.05, -0.03)\n\nfig, ax = plt.subplots(figsize=(12, 12))\n# Visualize graph components\nnx.draw_networkx_edges(H, pos, alpha=0.3, width=edgewidth, edge_color=\"m\")\nnx.draw_networkx_nodes(H, pos, node_size=nodesize, node_color=\"#210070\", alpha=0.9)\nlabel_options = {\"ec\": \"k\", \"fc\": \"white\", \"alpha\": 0.7}\nnx.draw_networkx_labels(H, pos, font_size=14, bbox=label_options)\n\n# Title/legend\nfont = {\"fontname\": \"Helvetica\", \"color\": \"k\", \"fontweight\": \"bold\", \"fontsize\": 14}\nax.set_title(\"World Chess Championship Games: 1886 - 1985\", font)\n# Change font color for legend\nfont[\"color\"] = \"r\"\n\nax.text(\n 0.80,\n 0.10,\n \"edge width = # games played\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\nax.text(\n 0.80,\n 0.06,\n \"node size = # games won\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\n\n# Resize figure for label readibility\nax.margins(0.1, 0.05)\nfig.tight_layout()\nplt.axis(\"off\")\nplt.show()"
+ "import matplotlib.pyplot as plt\nimport networkx as nx\n\n# tag names specifying what game info should be\n# stored in the dict on each digraph edge\ngame_details = [\"Event\", \"Date\", \"Result\", \"ECO\", \"Site\"]\n\n\ndef chess_pgn_graph(pgn_file=\"chess_masters_WCC.pgn.bz2\"):\n \"\"\"Read chess games in pgn format in pgn_file.\n\n Filenames ending in .bz2 will be uncompressed.\n\n Return the MultiDiGraph of players connected by a chess game.\n Edges contain game data in a dict.\n\n \"\"\"\n import bz2\n\n G = nx.MultiDiGraph()\n game = {}\n with bz2.BZ2File(pgn_file) as datafile:\n lines = [line.decode().rstrip(\"\\r\\n\") for line in datafile]\n for line in lines:\n if line.startswith(\"[\"):\n tag, value = line[1:-1].split(\" \", 1)\n game[str(tag)] = value.strip('\"')\n else:\n # empty line after tag set indicates\n # we finished reading game info\n if game:\n white = game.pop(\"White\")\n black = game.pop(\"Black\")\n G.add_edge(white, black, **game)\n game = {}\n return G\n\n\nG = chess_pgn_graph()\n\nprint(\n f\"Loaded {G.number_of_edges()} chess games between {G.number_of_nodes()} players\\n\"\n)\n\n# identify connected components of the undirected version\nH = G.to_undirected()\nGcc = [H.subgraph(c) for c in nx.connected_components(H)]\nif len(Gcc) > 1:\n print(f\"Note the disconnected component consisting of:\\n{Gcc[1].nodes()}\")\n\n# find all games with B97 opening (as described in ECO)\nopenings = {game_info[\"ECO\"] for (white, black, game_info) in G.edges(data=True)}\nprint(f\"\\nFrom a total of {len(openings)} different openings,\")\nprint(\"the following games used the Sicilian opening\")\nprint('with the Najdorff 7...Qb6 \"Poisoned Pawn\" variation.\\n')\n\nfor white, black, game_info in G.edges(data=True):\n if game_info[\"ECO\"] == \"B97\":\n summary = f\"{white} vs {black}\\n\"\n for k, v in game_info.items():\n summary += f\" {k}: {v}\\n\"\n summary += \"\\n\"\n print(summary)\n\n# make new undirected graph H without multi-edges\nH = nx.Graph(G)\n\n# edge width is proportional number of games played\nedgewidth = [len(G.get_edge_data(u, v)) for u, v in H.edges()]\n\n# node size is proportional to number of games won\nwins = dict.fromkeys(G.nodes(), 0.0)\nfor u, v, d in G.edges(data=True):\n r = d[\"Result\"].split(\"-\")\n if r[0] == \"1\":\n wins[u] += 1.0\n elif r[0] == \"1/2\":\n wins[u] += 0.5\n wins[v] += 0.5\n else:\n wins[v] += 1.0\nnodesize = [wins[v] * 50 for v in H]\n\n# Generate layout for visualization\npos = nx.kamada_kawai_layout(H)\n# Manual tweaking to limit node label overlap in the visualization\npos[\"Reshevsky, Samuel H\"] += (0.05, -0.10)\npos[\"Botvinnik, Mikhail M\"] += (0.03, -0.06)\npos[\"Smyslov, Vassily V\"] += (0.05, -0.03)\n\nfig, ax = plt.subplots(figsize=(12, 12))\n# Visualize graph components\nnx.draw_networkx_edges(H, pos, alpha=0.3, width=edgewidth, edge_color=\"m\")\nnx.draw_networkx_nodes(H, pos, node_size=nodesize, node_color=\"#210070\", alpha=0.9)\nlabel_options = {\"ec\": \"k\", \"fc\": \"white\", \"alpha\": 0.7}\nnx.draw_networkx_labels(H, pos, font_size=14, bbox=label_options)\n\n# Title/legend\nfont = {\"fontname\": \"Helvetica\", \"color\": \"k\", \"fontweight\": \"bold\", \"fontsize\": 14}\nax.set_title(\"World Chess Championship Games: 1886 - 1985\", font)\n# Change font color for legend\nfont[\"color\"] = \"r\"\n\nax.text(\n 0.80,\n 0.10,\n \"edge width = # games played\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\nax.text(\n 0.80,\n 0.06,\n \"node size = # games won\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\n\n# Resize figure for label readability\nax.margins(0.1, 0.05)\nfig.tight_layout()\nplt.axis(\"off\")\nplt.show()"
]
}
],
diff --git a/_downloads/27102b9986eea2f742603c5d8496d2f8/plot_degree_sequence.py b/_downloads/27102b9986eea2f742603c5d8496d2f8/plot_degree_sequence.py
index 0d32091c..87abb647 100644
--- a/_downloads/27102b9986eea2f742603c5d8496d2f8/plot_degree_sequence.py
+++ b/_downloads/27102b9986eea2f742603c5d8496d2f8/plot_degree_sequence.py
@@ -15,7 +15,9 @@ 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, seed=seed) # configuration model, seed for reproduciblity
+G = nx.configuration_model(
+ z, seed=seed
+) # configuration model, seed for reproducibility
degree_sequence = [d for n, d in G.degree()] # degree sequence
print(f"Degree sequence {degree_sequence}")
print("Degree histogram")
diff --git a/_downloads/2a66ab839d29e0e6b9e6c0db64e50f74/plot_triad_types.ipynb b/_downloads/2a66ab839d29e0e6b9e6c0db64e50f74/plot_triad_types.ipynb
index 10936eb3..80722584 100644
--- a/_downloads/2a66ab839d29e0e6b9e6c0db64e50f74/plot_triad_types.ipynb
+++ b/_downloads/2a66ab839d29e0e6b9e6c0db64e50f74/plot_triad_types.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import networkx as nx\nimport matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(4, 4, figsize=(10, 10))\ntriads = {\n \"003\": [],\n \"012\": [(1, 2)],\n \"102\": [(1, 2), (2, 1)],\n \"021D\": [(3, 1), (3, 2)],\n \"021U\": [(1, 3), (2, 3)],\n \"021C\": [(1, 3), (3, 2)],\n \"111D\": [(1, 2), (2, 1), (3, 1)],\n \"111U\": [(1, 2), (2, 1), (1, 3)],\n \"030T\": [(1, 2), (3, 2), (1, 3)],\n \"030C\": [(1, 3), (3, 2), (2, 1)],\n \"201\": [(1, 2), (2, 1), (3, 1), (1, 3)],\n \"120D\": [(1, 2), (2, 1), (3, 1), (3, 2)],\n \"120U\": [(1, 2), (2, 1), (1, 3), (2, 3)],\n \"120C\": [(1, 2), (2, 1), (1, 3), (3, 2)],\n \"210\": [(1, 2), (2, 1), (1, 3), (3, 2), (2, 3)],\n \"300\": [(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)],\n}\n\nfor (title, triad), ax in zip(triads.items(), axes.flatten()):\n G = nx.DiGraph()\n G.add_nodes_from([1, 2, 3])\n G.add_edges_from(triad)\n nx.draw_networkx(\n G,\n ax=ax,\n with_labels=False,\n node_color=[\"green\"],\n node_size=200,\n arrowsize=20,\n width=2,\n pos=nx.planar_layout(G),\n )\n ax.set_xlim(val * 1.2 for val in ax.get_xlim())\n ax.set_ylim(val * 1.2 for val in ax.get_ylim())\n ax.text(\n 0,\n 0,\n title,\n fontsize=15,\n fontweight=\"extra bold\",\n horizontalalignment=\"center\",\n bbox=dict(boxstyle=\"square,pad=0.3\", fc=\"none\"),\n )\nfig.tight_layout()\nplt.show()"
+ "import networkx as nx\nimport matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(4, 4, figsize=(10, 10))\ntriads = {\n \"003\": [],\n \"012\": [(1, 2)],\n \"102\": [(1, 2), (2, 1)],\n \"021D\": [(3, 1), (3, 2)],\n \"021U\": [(1, 3), (2, 3)],\n \"021C\": [(1, 3), (3, 2)],\n \"111D\": [(1, 2), (2, 1), (3, 1)],\n \"111U\": [(1, 2), (2, 1), (1, 3)],\n \"030T\": [(1, 2), (3, 2), (1, 3)],\n \"030C\": [(1, 3), (3, 2), (2, 1)],\n \"201\": [(1, 2), (2, 1), (3, 1), (1, 3)],\n \"120D\": [(1, 2), (2, 1), (3, 1), (3, 2)],\n \"120U\": [(1, 2), (2, 1), (1, 3), (2, 3)],\n \"120C\": [(1, 2), (2, 1), (1, 3), (3, 2)],\n \"210\": [(1, 2), (2, 1), (1, 3), (3, 2), (2, 3)],\n \"300\": [(1, 2), (2, 1), (2, 3), (3, 2), (1, 3), (3, 1)],\n}\n\nfor (title, triad), ax in zip(triads.items(), axes.flatten()):\n G = nx.DiGraph()\n G.add_nodes_from([1, 2, 3])\n G.add_edges_from(triad)\n nx.draw_networkx(\n G,\n ax=ax,\n with_labels=False,\n node_color=[\"green\"],\n node_size=200,\n arrowsize=20,\n width=2,\n pos=nx.planar_layout(G),\n )\n ax.set_xlim(val * 1.2 for val in ax.get_xlim())\n ax.set_ylim(val * 1.2 for val in ax.get_ylim())\n ax.text(\n 0,\n 0,\n title,\n fontsize=15,\n fontweight=\"extra bold\",\n horizontalalignment=\"center\",\n bbox={\"boxstyle\": \"square,pad=0.3\", \"fc\": \"none\"},\n )\nfig.tight_layout()\nplt.show()"
]
}
],
diff --git a/_downloads/388158421a67216f605c1bbf9aa310bf/plot_chess_masters.py b/_downloads/388158421a67216f605c1bbf9aa310bf/plot_chess_masters.py
index 52f4cfba..a5f3b5a8 100644
--- a/_downloads/388158421a67216f605c1bbf9aa310bf/plot_chess_masters.py
+++ b/_downloads/388158421a67216f605c1bbf9aa310bf/plot_chess_masters.py
@@ -81,7 +81,7 @@ 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):
+for white, black, game_info in G.edges(data=True):
if game_info["ECO"] == "B97":
summary = f"{white} vs {black}\n"
for k, v in game_info.items():
@@ -97,7 +97,7 @@ edgewidth = [len(G.get_edge_data(u, v)) for u, v in H.edges()]
# 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):
+for u, v, d in G.edges(data=True):
r = d["Result"].split("-")
if r[0] == "1":
wins[u] += 1.0
@@ -145,7 +145,7 @@ ax.text(
fontdict=font,
)
-# Resize figure for label readibility
+# Resize figure for label readability
ax.margins(0.1, 0.05)
fig.tight_layout()
plt.axis("off")
diff --git a/_downloads/3a5de2178f4d4bb1892ea7036709f1bb/plot_morse_trie.ipynb b/_downloads/3a5de2178f4d4bb1892ea7036709f1bb/plot_morse_trie.ipynb
index 944198b3..bde5d9d2 100644
--- a/_downloads/3a5de2178f4d4bb1892ea7036709f1bb/plot_morse_trie.ipynb
+++ b/_downloads/3a5de2178f4d4bb1892ea7036709f1bb/plot_morse_trie.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import networkx as nx\n\n# Unicode characters to represent the dots/dashes (or dits/dahs) of Morse code\ndot = \"\u2022\"\ndash = \"\u2014\"\n\n# Start with the direct mapping of letter -> code\nmorse_direct_mapping = {\n \"a\": dot + dash,\n \"b\": dash + dot * 3,\n \"c\": dash + dot + dash + dot,\n \"d\": dash + dot * 2,\n \"e\": dot,\n \"f\": dot * 2 + dash + dot,\n \"g\": dash * 2 + dot,\n \"h\": dot * 4,\n \"i\": dot * 2,\n \"j\": dot + dash * 3,\n \"k\": dash + dot + dash,\n \"l\": dot + dash + dot * 2,\n \"m\": dash * 2,\n \"n\": dash + dot,\n \"o\": dash * 3,\n \"p\": dot + dash * 2 + dot,\n \"q\": dash * 2 + dot + dash,\n \"r\": dot + dash + dot,\n \"s\": dot * 3,\n \"t\": dash,\n \"u\": dot * 2 + dash,\n \"v\": dot * 3 + dash,\n \"w\": dot + dash * 2,\n \"x\": dash + dot * 2 + dash,\n \"y\": dash + dot + dash * 2,\n \"z\": dash * 2 + dot * 2,\n}\n\n### Manually construct the prefix tree from this mapping\n\n# Some preprocessing: sort the original mapping by code length and character\n# value\nmorse_mapping_sorted = dict(\n sorted(morse_direct_mapping.items(), key=lambda item: (len(item[1]), item[1]))\n)\n\n# More preprocessing: create the reverse mapping to simplify lookup\nreverse_mapping = {v: k for k, v in morse_direct_mapping.items()}\nreverse_mapping[\"\"] = \"\" # Represent the \"root\" node with an empty string\n\n# Construct the prefix tree from the sorted mapping\nG = nx.DiGraph()\nfor node, char in morse_mapping_sorted.items():\n pred = char[:-1]\n # Store the dot/dash relating the two letters as an edge attribute \"char\"\n G.add_edge(reverse_mapping[pred], node, char=char[-1])\n\n# For visualization purposes, layout the nodes in topological order\nfor i, layer in enumerate(nx.topological_generations(G)):\n for n in layer:\n G.nodes[n][\"layer\"] = i\npos = nx.multipartite_layout(G, subset_key=\"layer\", align=\"horizontal\")\n# Flip the layout so the root node is on top\nfor k in pos:\n pos[k][-1] *= -1\n\n# Visualize the trie\nnx.draw(G, pos=pos, with_labels=True)\nelabels = {(u, v): l for u, v, l in G.edges(data=\"char\")}\nnx.draw_networkx_edge_labels(G, pos, edge_labels=elabels)\n\n# A letter can be encoded by following the path from the given letter (node) to\n# the root node\ndef morse_encode(letter):\n pred = next(G.predecessors(letter)) # Each letter has only 1 predecessor\n symbol = G[pred][letter][\"char\"]\n if pred != \"\":\n return morse_encode(pred) + symbol # Traversing the trie in reverse\n return symbol\n\n\n# Verify that the trie encoding is correct\nimport string\n\nfor letter in string.ascii_lowercase:\n assert morse_encode(letter) == morse_direct_mapping[letter]\n\nprint(\" \".join([morse_encode(ltr) for ltr in \"ilovenetworkx\"]))"
+ "import networkx as nx\n\n# Unicode characters to represent the dots/dashes (or dits/dahs) of Morse code\ndot = \"\u2022\"\ndash = \"\u2014\"\n\n# Start with the direct mapping of letter -> code\nmorse_direct_mapping = {\n \"a\": dot + dash,\n \"b\": dash + dot * 3,\n \"c\": dash + dot + dash + dot,\n \"d\": dash + dot * 2,\n \"e\": dot,\n \"f\": dot * 2 + dash + dot,\n \"g\": dash * 2 + dot,\n \"h\": dot * 4,\n \"i\": dot * 2,\n \"j\": dot + dash * 3,\n \"k\": dash + dot + dash,\n \"l\": dot + dash + dot * 2,\n \"m\": dash * 2,\n \"n\": dash + dot,\n \"o\": dash * 3,\n \"p\": dot + dash * 2 + dot,\n \"q\": dash * 2 + dot + dash,\n \"r\": dot + dash + dot,\n \"s\": dot * 3,\n \"t\": dash,\n \"u\": dot * 2 + dash,\n \"v\": dot * 3 + dash,\n \"w\": dot + dash * 2,\n \"x\": dash + dot * 2 + dash,\n \"y\": dash + dot + dash * 2,\n \"z\": dash * 2 + dot * 2,\n}\n\n### Manually construct the prefix tree from this mapping\n\n# Some preprocessing: sort the original mapping by code length and character\n# value\nmorse_mapping_sorted = dict(\n sorted(morse_direct_mapping.items(), key=lambda item: (len(item[1]), item[1]))\n)\n\n# More preprocessing: create the reverse mapping to simplify lookup\nreverse_mapping = {v: k for k, v in morse_direct_mapping.items()}\nreverse_mapping[\"\"] = \"\" # Represent the \"root\" node with an empty string\n\n# Construct the prefix tree from the sorted mapping\nG = nx.DiGraph()\nfor node, char in morse_mapping_sorted.items():\n pred = char[:-1]\n # Store the dot/dash relating the two letters as an edge attribute \"char\"\n G.add_edge(reverse_mapping[pred], node, char=char[-1])\n\n# For visualization purposes, layout the nodes in topological order\nfor i, layer in enumerate(nx.topological_generations(G)):\n for n in layer:\n G.nodes[n][\"layer\"] = i\npos = nx.multipartite_layout(G, subset_key=\"layer\", align=\"horizontal\")\n# Flip the layout so the root node is on top\nfor k in pos:\n pos[k][-1] *= -1\n\n# Visualize the trie\nnx.draw(G, pos=pos, with_labels=True)\nelabels = {(u, v): l for u, v, l in G.edges(data=\"char\")}\nnx.draw_networkx_edge_labels(G, pos, edge_labels=elabels)\n\n\n# A letter can be encoded by following the path from the given letter (node) to\n# the root node\ndef morse_encode(letter):\n pred = next(G.predecessors(letter)) # Each letter has only 1 predecessor\n symbol = G[pred][letter][\"char\"]\n if pred != \"\":\n return morse_encode(pred) + symbol # Traversing the trie in reverse\n return symbol\n\n\n# Verify that the trie encoding is correct\nimport string\n\nfor letter in string.ascii_lowercase:\n assert morse_encode(letter) == morse_direct_mapping[letter]\n\nprint(\" \".join([morse_encode(ltr) for ltr in \"ilovenetworkx\"]))"
]
}
],
diff --git a/_downloads/3adca49f1b673454c4138bf3eea6d2c5/plot_blockmodel.ipynb b/_downloads/3adca49f1b673454c4138bf3eea6d2c5/plot_blockmodel.ipynb
index ccc5304d..662a0c48 100644
--- a/_downloads/3adca49f1b673454c4138bf3eea6d2c5/plot_blockmodel.ipynb
+++ b/_downloads/3adca49f1b673454c4138bf3eea6d2c5/plot_blockmodel.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "from collections import defaultdict\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nfrom scipy.cluster import hierarchy\nfrom scipy.spatial import distance\n\n\ndef create_hc(G):\n \"\"\"Creates hierarchical cluster of graph G from distance matrix\"\"\"\n path_length = nx.all_pairs_shortest_path_length(G)\n distances = np.zeros((len(G), len(G)))\n for u, p in path_length:\n for v, d in p.items():\n distances[u][v] = d\n # Create hierarchical cluster\n Y = distance.squareform(distances)\n Z = hierarchy.complete(Y) # Creates HC using farthest point linkage\n # This partition selection is arbitrary, for illustrive purposes\n membership = list(hierarchy.fcluster(Z, t=1.15))\n # Create collection of lists for blockmodel\n partition = defaultdict(list)\n for n, p in zip(list(range(len(G))), membership):\n partition[p].append(n)\n return list(partition.values())\n\n\nG = nx.read_edgelist(\"hartford_drug.edgelist\")\n\n# Extract largest connected component into graph H\nH = G.subgraph(next(nx.connected_components(G)))\n# Makes life easier to have consecutively labeled integer nodes\nH = nx.convert_node_labels_to_integers(H)\n# Create parititions with hierarchical clustering\npartitions = create_hc(H)\n# Build blockmodel graph\nBM = nx.quotient_graph(H, partitions, relabel=True)\n\n# Draw original graph\npos = nx.spring_layout(H, iterations=100, seed=83) # Seed for reproducibility\nplt.subplot(211)\nnx.draw(H, pos, with_labels=False, node_size=10)\n\n# Draw block model with weighted edges and nodes sized by number of internal nodes\nnode_size = [BM.nodes[x][\"nnodes\"] * 10 for x in BM.nodes()]\nedge_width = [(2 * d[\"weight\"]) for (u, v, d) in BM.edges(data=True)]\n# Set positions to mean of positions of internal nodes from original graph\nposBM = {}\nfor n in BM:\n xy = np.array([pos[u] for u in BM.nodes[n][\"graph\"]])\n posBM[n] = xy.mean(axis=0)\nplt.subplot(212)\nnx.draw(BM, posBM, node_size=node_size, width=edge_width, with_labels=False)\nplt.axis(\"off\")\nplt.show()"
+ "from collections import defaultdict\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nfrom scipy.cluster import hierarchy\nfrom scipy.spatial import distance\n\n\ndef create_hc(G):\n \"\"\"Creates hierarchical cluster of graph G from distance matrix\"\"\"\n path_length = nx.all_pairs_shortest_path_length(G)\n distances = np.zeros((len(G), len(G)))\n for u, p in path_length:\n for v, d in p.items():\n distances[u][v] = d\n # Create hierarchical cluster\n Y = distance.squareform(distances)\n Z = hierarchy.complete(Y) # Creates HC using farthest point linkage\n # This partition selection is arbitrary, for illustrive purposes\n membership = list(hierarchy.fcluster(Z, t=1.15))\n # Create collection of lists for blockmodel\n partition = defaultdict(list)\n for n, p in zip(list(range(len(G))), membership):\n partition[p].append(n)\n return list(partition.values())\n\n\nG = nx.read_edgelist(\"hartford_drug.edgelist\")\n\n# Extract largest connected component into graph H\nH = G.subgraph(next(nx.connected_components(G)))\n# Makes life easier to have consecutively labeled integer nodes\nH = nx.convert_node_labels_to_integers(H)\n# Create partitions with hierarchical clustering\npartitions = create_hc(H)\n# Build blockmodel graph\nBM = nx.quotient_graph(H, partitions, relabel=True)\n\n# Draw original graph\npos = nx.spring_layout(H, iterations=100, seed=83) # Seed for reproducibility\nplt.subplot(211)\nnx.draw(H, pos, with_labels=False, node_size=10)\n\n# Draw block model with weighted edges and nodes sized by number of internal nodes\nnode_size = [BM.nodes[x][\"nnodes\"] * 10 for x in BM.nodes()]\nedge_width = [(2 * d[\"weight\"]) for (u, v, d) in BM.edges(data=True)]\n# Set positions to mean of positions of internal nodes from original graph\nposBM = {}\nfor n in BM:\n xy = np.array([pos[u] for u in BM.nodes[n][\"graph\"]])\n posBM[n] = xy.mean(axis=0)\nplt.subplot(212)\nnx.draw(BM, posBM, node_size=node_size, width=edge_width, with_labels=False)\nplt.axis(\"off\")\nplt.show()"
]
}
],
diff --git a/_downloads/461dfe5db4853b4fe245b7ec677c3f2e/plot_words.ipynb b/_downloads/461dfe5db4853b4fe245b7ec677c3f2e/plot_words.ipynb
index afd359ae..b6378e48 100644
--- a/_downloads/461dfe5db4853b4fe245b7ec677c3f2e/plot_words.ipynb
+++ b/_downloads/461dfe5db4853b4fe245b7ec677c3f2e/plot_words.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import gzip\nfrom string import ascii_lowercase as lowercase\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef generate_graph(words):\n G = nx.Graph(name=\"words\")\n lookup = {c: lowercase.index(c) for c in lowercase}\n\n def edit_distance_one(word):\n for i in range(len(word)):\n left, c, right = word[0:i], word[i], word[i + 1 :]\n j = lookup[c] # lowercase.index(c)\n for cc in lowercase[j + 1 :]:\n yield left + cc + right\n\n candgen = (\n (word, cand)\n for word in sorted(words)\n for cand in edit_distance_one(word)\n if cand in words\n )\n G.add_nodes_from(words)\n for word, cand in candgen:\n G.add_edge(word, cand)\n return G\n\n\ndef words_graph():\n \"\"\"Return the words example graph from the Stanford GraphBase\"\"\"\n fh = gzip.open(\"words_dat.txt.gz\", \"r\")\n words = set()\n for line in fh.readlines():\n line = line.decode()\n if line.startswith(\"*\"):\n continue\n w = str(line[0:5])\n words.add(w)\n return generate_graph(words)\n\n\nG = words_graph()\nprint(\"Loaded words_dat.txt containing 5757 five-letter English words.\")\nprint(\"Two words are connected if they differ in one letter.\")\nprint(G)\nprint(f\"{nx.number_connected_components(G)} connected components\")\n\nfor (source, target) in [(\"chaos\", \"order\"), (\"nodes\", \"graph\"), (\"pound\", \"marks\")]:\n print(f\"Shortest path between {source} and {target} is\")\n try:\n shortest_path = nx.shortest_path(G, source, target)\n for n in shortest_path:\n print(n)\n except nx.NetworkXNoPath:\n print(\"None\")\n\n\n# draw a subset of the graph\nboundary = list(nx.node_boundary(G, shortest_path))\nG.add_nodes_from(shortest_path, color=\"red\")\nG.add_nodes_from(boundary, color=\"blue\")\nH = G.subgraph(shortest_path + boundary)\ncolors = nx.get_node_attributes(H, \"color\")\noptions = {\"node_size\": 1500, \"alpha\": 0.3, \"node_color\": colors.values()}\npos = nx.kamada_kawai_layout(H)\nnx.draw(H, pos, **options)\nnx.draw_networkx_labels(H, pos, font_weight=\"bold\")\nplt.show()"
+ "import gzip\nfrom string import ascii_lowercase as lowercase\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef generate_graph(words):\n G = nx.Graph(name=\"words\")\n lookup = {c: lowercase.index(c) for c in lowercase}\n\n def edit_distance_one(word):\n for i in range(len(word)):\n left, c, right = word[0:i], word[i], word[i + 1 :]\n j = lookup[c] # lowercase.index(c)\n for cc in lowercase[j + 1 :]:\n yield left + cc + right\n\n candgen = (\n (word, cand)\n for word in sorted(words)\n for cand in edit_distance_one(word)\n if cand in words\n )\n G.add_nodes_from(words)\n for word, cand in candgen:\n G.add_edge(word, cand)\n return G\n\n\ndef words_graph():\n \"\"\"Return the words example graph from the Stanford GraphBase\"\"\"\n fh = gzip.open(\"words_dat.txt.gz\", \"r\")\n words = set()\n for line in fh.readlines():\n line = line.decode()\n if line.startswith(\"*\"):\n continue\n w = str(line[0:5])\n words.add(w)\n return generate_graph(words)\n\n\nG = words_graph()\nprint(\"Loaded words_dat.txt containing 5757 five-letter English words.\")\nprint(\"Two words are connected if they differ in one letter.\")\nprint(G)\nprint(f\"{nx.number_connected_components(G)} connected components\")\n\nfor source, target in [(\"chaos\", \"order\"), (\"nodes\", \"graph\"), (\"pound\", \"marks\")]:\n print(f\"Shortest path between {source} and {target} is\")\n try:\n shortest_path = nx.shortest_path(G, source, target)\n for n in shortest_path:\n print(n)\n except nx.NetworkXNoPath:\n print(\"None\")\n\n\n# draw a subset of the graph\nboundary = list(nx.node_boundary(G, shortest_path))\nG.add_nodes_from(shortest_path, color=\"red\")\nG.add_nodes_from(boundary, color=\"blue\")\nH = G.subgraph(shortest_path + boundary)\ncolors = nx.get_node_attributes(H, \"color\")\noptions = {\"node_size\": 1500, \"alpha\": 0.3, \"node_color\": colors.values()}\npos = nx.kamada_kawai_layout(H)\nnx.draw(H, pos, **options)\nnx.draw_networkx_labels(H, pos, font_weight=\"bold\")\nplt.show()"
]
}
],
diff --git a/_downloads/4aba8bc455260708046bf8ed7dcf62c6/plot_unix_email.ipynb b/_downloads/4aba8bc455260708046bf8ed7dcf62c6/plot_unix_email.ipynb
index c065eb9f..677764b9 100644
--- a/_downloads/4aba8bc455260708046bf8ed7dcf62c6/plot_unix_email.ipynb
+++ b/_downloads/4aba8bc455260708046bf8ed7dcf62c6/plot_unix_email.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "from email.utils import getaddresses, parseaddr\nimport mailbox\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# unix mailbox recipe\n# see https://docs.python.org/3/library/mailbox.html\n\n\ndef mbox_graph():\n mbox = mailbox.mbox(\"unix_email.mbox\") # parse unix mailbox\n\n G = nx.MultiDiGraph() # create empty graph\n\n # parse each messages and build graph\n for msg in mbox: # msg is python email.Message.Message object\n (source_name, source_addr) = parseaddr(msg[\"From\"]) # sender\n # get all recipients\n # see https://docs.python.org/3/library/email.html\n tos = msg.get_all(\"to\", [])\n ccs = msg.get_all(\"cc\", [])\n resent_tos = msg.get_all(\"resent-to\", [])\n resent_ccs = msg.get_all(\"resent-cc\", [])\n all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)\n # now add the edges for this mail message\n for (target_name, target_addr) in all_recipients:\n G.add_edge(source_addr, target_addr, message=msg)\n\n return G\n\n\nG = mbox_graph()\n\n# print edges with message subject\nfor (u, v, d) in G.edges(data=True):\n print(f\"From: {u} To: {v} Subject: {d['message']['Subject']}\")\n\npos = nx.spring_layout(G, iterations=10, seed=227)\nnx.draw(G, pos, node_size=0, alpha=0.4, edge_color=\"r\", font_size=16, with_labels=True)\nax = plt.gca()\nax.margins(0.08)\nplt.show()"
+ "from email.utils import getaddresses, parseaddr\nimport mailbox\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# unix mailbox recipe\n# see https://docs.python.org/3/library/mailbox.html\n\n\ndef mbox_graph():\n mbox = mailbox.mbox(\"unix_email.mbox\") # parse unix mailbox\n\n G = nx.MultiDiGraph() # create empty graph\n\n # parse each messages and build graph\n for msg in mbox: # msg is python email.Message.Message object\n (source_name, source_addr) = parseaddr(msg[\"From\"]) # sender\n # get all recipients\n # see https://docs.python.org/3/library/email.html\n tos = msg.get_all(\"to\", [])\n ccs = msg.get_all(\"cc\", [])\n resent_tos = msg.get_all(\"resent-to\", [])\n resent_ccs = msg.get_all(\"resent-cc\", [])\n all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)\n # now add the edges for this mail message\n for target_name, target_addr in all_recipients:\n G.add_edge(source_addr, target_addr, message=msg)\n\n return G\n\n\nG = mbox_graph()\n\n# print edges with message subject\nfor u, v, d in G.edges(data=True):\n print(f\"From: {u} To: {v} Subject: {d['message']['Subject']}\")\n\npos = nx.spring_layout(G, iterations=10, seed=227)\nnx.draw(G, pos, node_size=0, alpha=0.4, edge_color=\"r\", font_size=16, with_labels=True)\nax = plt.gca()\nax.margins(0.08)\nplt.show()"
]
}
],
diff --git a/_downloads/60379a4283563d425090aaae07ab115a/plot_morse_trie.py b/_downloads/60379a4283563d425090aaae07ab115a/plot_morse_trie.py
index 88b424ce..22c1b998 100644
--- a/_downloads/60379a4283563d425090aaae07ab115a/plot_morse_trie.py
+++ b/_downloads/60379a4283563d425090aaae07ab115a/plot_morse_trie.py
@@ -77,6 +77,7 @@ nx.draw(G, pos=pos, with_labels=True)
elabels = {(u, v): l for u, v, l in G.edges(data="char")}
nx.draw_networkx_edge_labels(G, pos, edge_labels=elabels)
+
# A letter can be encoded by following the path from the given letter (node) to
# the root node
def morse_encode(letter):
diff --git a/_downloads/6a1e333663010969e61d07b33c7845f0/plot_davis_club.py b/_downloads/6a1e333663010969e61d07b33c7845f0/plot_davis_club.py
index 517d5238..0029d55c 100644
--- a/_downloads/6a1e333663010969e61d07b33c7845f0/plot_davis_club.py
+++ b/_downloads/6a1e333663010969e61d07b33c7845f0/plot_davis_club.py
@@ -14,7 +14,7 @@ The graph is bipartite (clubs, women).
"""
import matplotlib.pyplot as plt
import networkx as nx
-import networkx.algorithms.bipartite as bipartite
+from networkx.algorithms import bipartite
G = nx.davis_southern_women_graph()
women = G.graph["top"]
diff --git a/_downloads/6cb4bf689cf53c849bce13cbab13eaec/plot_multipartite_graph.py b/_downloads/6cb4bf689cf53c849bce13cbab13eaec/plot_multipartite_graph.py
index 15c4d82c..a941bddc 100644
--- a/_downloads/6cb4bf689cf53c849bce13cbab13eaec/plot_multipartite_graph.py
+++ b/_downloads/6cb4bf689cf53c849bce13cbab13eaec/plot_multipartite_graph.py
@@ -25,7 +25,7 @@ def multilayered_graph(*subset_sizes):
extents = nx.utils.pairwise(itertools.accumulate((0,) + subset_sizes))
layers = [range(start, end) for start, end in extents]
G = nx.Graph()
- for (i, layer) in enumerate(layers):
+ for i, layer in enumerate(layers):
G.add_nodes_from(layer, layer=i)
for layer1, layer2 in nx.utils.pairwise(layers):
G.add_edges_from(itertools.product(layer1, layer2))
diff --git a/_downloads/6e2f41828cdc6170bb3c4517097bdfc8/plot_snap.ipynb b/_downloads/6e2f41828cdc6170bb3c4517097bdfc8/plot_snap.ipynb
index acb22f24..6c615e71 100644
--- a/_downloads/6e2f41828cdc6170bb3c4517097bdfc8/plot_snap.ipynb
+++ b/_downloads/6e2f41828cdc6170bb3c4517097bdfc8/plot_snap.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import networkx as nx\nimport matplotlib.pyplot as plt\n\n\nnodes = {\n \"A\": dict(color=\"Red\"),\n \"B\": dict(color=\"Red\"),\n \"C\": dict(color=\"Red\"),\n \"D\": dict(color=\"Red\"),\n \"E\": dict(color=\"Blue\"),\n \"F\": dict(color=\"Blue\"),\n \"G\": dict(color=\"Blue\"),\n \"H\": dict(color=\"Blue\"),\n \"I\": dict(color=\"Yellow\"),\n \"J\": dict(color=\"Yellow\"),\n \"K\": dict(color=\"Yellow\"),\n \"L\": dict(color=\"Yellow\"),\n}\nedges = [\n (\"A\", \"B\", \"Strong\"),\n (\"A\", \"C\", \"Weak\"),\n (\"A\", \"E\", \"Strong\"),\n (\"A\", \"I\", \"Weak\"),\n (\"B\", \"D\", \"Weak\"),\n (\"B\", \"J\", \"Weak\"),\n (\"B\", \"F\", \"Strong\"),\n (\"C\", \"G\", \"Weak\"),\n (\"D\", \"H\", \"Weak\"),\n (\"I\", \"J\", \"Strong\"),\n (\"J\", \"K\", \"Strong\"),\n (\"I\", \"L\", \"Strong\"),\n]\noriginal_graph = nx.Graph()\noriginal_graph.add_nodes_from(n for n in nodes.items())\noriginal_graph.add_edges_from((u, v, {\"type\": label}) for u, v, label in edges)\n\n\nplt.suptitle(\"SNAP Summarization\")\n\nbase_options = dict(with_labels=True, edgecolors=\"black\", node_size=500)\n\nax1 = plt.subplot(1, 2, 1)\nplt.title(\n \"Original (%s nodes, %s edges)\"\n % (original_graph.number_of_nodes(), original_graph.number_of_edges())\n)\npos = nx.spring_layout(original_graph, seed=7482934)\nnode_colors = [d[\"color\"] for _, d in original_graph.nodes(data=True)]\n\nedge_type_visual_weight_lookup = {\"Weak\": 1.0, \"Strong\": 3.0}\nedge_weights = [\n edge_type_visual_weight_lookup[d[\"type\"]]\n for _, _, d in original_graph.edges(data=True)\n]\n\nnx.draw_networkx(\n original_graph, pos=pos, node_color=node_colors, width=edge_weights, **base_options\n)\n\nnode_attributes = (\"color\",)\nedge_attributes = (\"type\",)\nsummary_graph = nx.snap_aggregation(\n original_graph, node_attributes, edge_attributes, prefix=\"S-\"\n)\n\nplt.subplot(1, 2, 2)\n\nplt.title(\n \"SNAP Aggregation (%s nodes, %s edges)\"\n % (summary_graph.number_of_nodes(), summary_graph.number_of_edges())\n)\nsummary_pos = nx.spring_layout(summary_graph, seed=8375428)\nnode_colors = []\nfor node in summary_graph:\n color = summary_graph.nodes[node][\"color\"]\n node_colors.append(color)\n\nedge_weights = []\nfor edge in summary_graph.edges():\n edge_types = summary_graph.get_edge_data(*edge)[\"types\"]\n edge_weight = 0.0\n for edge_type in edge_types:\n edge_weight += edge_type_visual_weight_lookup[edge_type[\"type\"]]\n edge_weights.append(edge_weight)\n\nnx.draw_networkx(\n summary_graph,\n pos=summary_pos,\n node_color=node_colors,\n width=edge_weights,\n **base_options\n)\n\nplt.tight_layout()\nplt.show()"
+ "import networkx as nx\nimport matplotlib.pyplot as plt\n\n\nnodes = {\n \"A\": {\"color\": \"Red\"},\n \"B\": {\"color\": \"Red\"},\n \"C\": {\"color\": \"Red\"},\n \"D\": {\"color\": \"Red\"},\n \"E\": {\"color\": \"Blue\"},\n \"F\": {\"color\": \"Blue\"},\n \"G\": {\"color\": \"Blue\"},\n \"H\": {\"color\": \"Blue\"},\n \"I\": {\"color\": \"Yellow\"},\n \"J\": {\"color\": \"Yellow\"},\n \"K\": {\"color\": \"Yellow\"},\n \"L\": {\"color\": \"Yellow\"},\n}\nedges = [\n (\"A\", \"B\", \"Strong\"),\n (\"A\", \"C\", \"Weak\"),\n (\"A\", \"E\", \"Strong\"),\n (\"A\", \"I\", \"Weak\"),\n (\"B\", \"D\", \"Weak\"),\n (\"B\", \"J\", \"Weak\"),\n (\"B\", \"F\", \"Strong\"),\n (\"C\", \"G\", \"Weak\"),\n (\"D\", \"H\", \"Weak\"),\n (\"I\", \"J\", \"Strong\"),\n (\"J\", \"K\", \"Strong\"),\n (\"I\", \"L\", \"Strong\"),\n]\noriginal_graph = nx.Graph()\noriginal_graph.add_nodes_from(n for n in nodes.items())\noriginal_graph.add_edges_from((u, v, {\"type\": label}) for u, v, label in edges)\n\n\nplt.suptitle(\"SNAP Summarization\")\n\nbase_options = {\"with_labels\": True, \"edgecolors\": \"black\", \"node_size\": 500}\n\nax1 = plt.subplot(1, 2, 1)\nplt.title(\n \"Original (%s nodes, %s edges)\"\n % (original_graph.number_of_nodes(), original_graph.number_of_edges())\n)\npos = nx.spring_layout(original_graph, seed=7482934)\nnode_colors = [d[\"color\"] for _, d in original_graph.nodes(data=True)]\n\nedge_type_visual_weight_lookup = {\"Weak\": 1.0, \"Strong\": 3.0}\nedge_weights = [\n edge_type_visual_weight_lookup[d[\"type\"]]\n for _, _, d in original_graph.edges(data=True)\n]\n\nnx.draw_networkx(\n original_graph, pos=pos, node_color=node_colors, width=edge_weights, **base_options\n)\n\nnode_attributes = (\"color\",)\nedge_attributes = (\"type\",)\nsummary_graph = nx.snap_aggregation(\n original_graph, node_attributes, edge_attributes, prefix=\"S-\"\n)\n\nplt.subplot(1, 2, 2)\n\nplt.title(\n \"SNAP Aggregation (%s nodes, %s edges)\"\n % (summary_graph.number_of_nodes(), summary_graph.number_of_edges())\n)\nsummary_pos = nx.spring_layout(summary_graph, seed=8375428)\nnode_colors = []\nfor node in summary_graph:\n color = summary_graph.nodes[node][\"color\"]\n node_colors.append(color)\n\nedge_weights = []\nfor edge in summary_graph.edges():\n edge_types = summary_graph.get_edge_data(*edge)[\"types\"]\n edge_weight = 0.0\n for edge_type in edge_types:\n edge_weight += edge_type_visual_weight_lookup[edge_type[\"type\"]]\n edge_weights.append(edge_weight)\n\nnx.draw_networkx(\n summary_graph,\n pos=summary_pos,\n node_color=node_colors,\n width=edge_weights,\n **base_options\n)\n\nplt.tight_layout()\nplt.show()"
]
}
],
diff --git a/_downloads/6f1e7a639e0699d6164445b55e6c116d/auto_examples_jupyter.zip b/_downloads/6f1e7a639e0699d6164445b55e6c116d/auto_examples_jupyter.zip
index 002f0683..1674ae5b 100644
--- a/_downloads/6f1e7a639e0699d6164445b55e6c116d/auto_examples_jupyter.zip
+++ b/_downloads/6f1e7a639e0699d6164445b55e6c116d/auto_examples_jupyter.zip
Binary files differ
diff --git a/_downloads/73da379af64659b61cf9760ce786a7d4/plot_betweenness_centrality.ipynb b/_downloads/73da379af64659b61cf9760ce786a7d4/plot_betweenness_centrality.ipynb
index ed2bde3b..d7bc471f 100644
--- a/_downloads/73da379af64659b61cf9760ce786a7d4/plot_betweenness_centrality.ipynb
+++ b/_downloads/73da379af64659b61cf9760ce786a7d4/plot_betweenness_centrality.ipynb
@@ -15,7 +15,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "\n# Betweeness Centrality\n\nBetweenness centrality measures of positive gene functional associations\nusing WormNet v.3-GS.\n\nData from: https://www.inetbio.org/wormnet/downloadnetwork.php\n"
+ "\n# Betweenness Centrality\n\nBetweenness centrality measures of positive gene functional associations\nusing WormNet v.3-GS.\n\nData from: https://www.inetbio.org/wormnet/downloadnetwork.php\n"
]
},
{
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "from random import sample\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# Gold standard data of positive gene functional associations\n# from https://www.inetbio.org/wormnet/downloadnetwork.php\nG = nx.read_edgelist(\"WormNet.v3.benchmark.txt\")\n\n# remove randomly selected nodes (to make example fast)\nnum_to_remove = int(len(G) / 1.5)\nnodes = sample(list(G.nodes), num_to_remove)\nG.remove_nodes_from(nodes)\n\n# remove low-degree nodes\nlow_degree = [n for n, d in G.degree() if d < 10]\nG.remove_nodes_from(low_degree)\n\n# largest connected component\ncomponents = nx.connected_components(G)\nlargest_component = max(components, key=len)\nH = G.subgraph(largest_component)\n\n# compute centrality\ncentrality = nx.betweenness_centrality(H, k=10, endpoints=True)\n\n# compute community structure\nlpc = nx.community.label_propagation_communities(H)\ncommunity_index = {n: i for i, com in enumerate(lpc) for n in com}\n\n#### draw graph ####\nfig, ax = plt.subplots(figsize=(20, 15))\npos = nx.spring_layout(H, k=0.15, seed=4572321)\nnode_color = [community_index[n] for n in H]\nnode_size = [v * 20000 for v in centrality.values()]\nnx.draw_networkx(\n H,\n pos=pos,\n with_labels=False,\n node_color=node_color,\n node_size=node_size,\n edge_color=\"gainsboro\",\n alpha=0.4,\n)\n\n# Title/legend\nfont = {\"color\": \"k\", \"fontweight\": \"bold\", \"fontsize\": 20}\nax.set_title(\"Gene functional association network (C. elegans)\", font)\n# Change font color for legend\nfont[\"color\"] = \"r\"\n\nax.text(\n 0.80,\n 0.10,\n \"node color = community structure\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\nax.text(\n 0.80,\n 0.06,\n \"node size = betweeness centrality\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\n\n# Resize figure for label readibility\nax.margins(0.1, 0.05)\nfig.tight_layout()\nplt.axis(\"off\")\nplt.show()"
+ "from random import sample\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n# Gold standard data of positive gene functional associations\n# from https://www.inetbio.org/wormnet/downloadnetwork.php\nG = nx.read_edgelist(\"WormNet.v3.benchmark.txt\")\n\n# remove randomly selected nodes (to make example fast)\nnum_to_remove = int(len(G) / 1.5)\nnodes = sample(list(G.nodes), num_to_remove)\nG.remove_nodes_from(nodes)\n\n# remove low-degree nodes\nlow_degree = [n for n, d in G.degree() if d < 10]\nG.remove_nodes_from(low_degree)\n\n# largest connected component\ncomponents = nx.connected_components(G)\nlargest_component = max(components, key=len)\nH = G.subgraph(largest_component)\n\n# compute centrality\ncentrality = nx.betweenness_centrality(H, k=10, endpoints=True)\n\n# compute community structure\nlpc = nx.community.label_propagation_communities(H)\ncommunity_index = {n: i for i, com in enumerate(lpc) for n in com}\n\n#### draw graph ####\nfig, ax = plt.subplots(figsize=(20, 15))\npos = nx.spring_layout(H, k=0.15, seed=4572321)\nnode_color = [community_index[n] for n in H]\nnode_size = [v * 20000 for v in centrality.values()]\nnx.draw_networkx(\n H,\n pos=pos,\n with_labels=False,\n node_color=node_color,\n node_size=node_size,\n edge_color=\"gainsboro\",\n alpha=0.4,\n)\n\n# Title/legend\nfont = {\"color\": \"k\", \"fontweight\": \"bold\", \"fontsize\": 20}\nax.set_title(\"Gene functional association network (C. elegans)\", font)\n# Change font color for legend\nfont[\"color\"] = \"r\"\n\nax.text(\n 0.80,\n 0.10,\n \"node color = community structure\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\nax.text(\n 0.80,\n 0.06,\n \"node size = betweenness centrality\",\n horizontalalignment=\"center\",\n transform=ax.transAxes,\n fontdict=font,\n)\n\n# Resize figure for label readability\nax.margins(0.1, 0.05)\nfig.tight_layout()\nplt.axis(\"off\")\nplt.show()"
]
}
],
diff --git a/_downloads/75057ffc857a59555c9505a02935679d/plot_degree_sequence.ipynb b/_downloads/75057ffc857a59555c9505a02935679d/plot_degree_sequence.ipynb
index 34925332..78d5a5a4 100644
--- a/_downloads/75057ffc857a59555c9505a02935679d/plot_degree_sequence.ipynb
+++ b/_downloads/75057ffc857a59555c9505a02935679d/plot_degree_sequence.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import matplotlib.pyplot as plt\nimport networkx as nx\n\n# Specify seed for reproducibility\nseed = 668273\n\nz = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]\nprint(nx.is_graphical(z))\n\nprint(\"Configuration model\")\nG = nx.configuration_model(z, seed=seed) # configuration model, seed for reproduciblity\ndegree_sequence = [d for n, d in G.degree()] # degree sequence\nprint(f\"Degree sequence {degree_sequence}\")\nprint(\"Degree histogram\")\nhist = {}\nfor d in degree_sequence:\n if d in hist:\n hist[d] += 1\n else:\n hist[d] = 1\nprint(\"degree #nodes\")\nfor d in hist:\n print(f\"{d:4} {hist[d]:6}\")\n\npos = nx.spring_layout(G, seed=seed) # Seed layout for reproducibility\nnx.draw(G, pos=pos)\nplt.show()"
+ "import matplotlib.pyplot as plt\nimport networkx as nx\n\n# Specify seed for reproducibility\nseed = 668273\n\nz = [5, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1]\nprint(nx.is_graphical(z))\n\nprint(\"Configuration model\")\nG = nx.configuration_model(\n z, seed=seed\n) # configuration model, seed for reproducibility\ndegree_sequence = [d for n, d in G.degree()] # degree sequence\nprint(f\"Degree sequence {degree_sequence}\")\nprint(\"Degree histogram\")\nhist = {}\nfor d in degree_sequence:\n if d in hist:\n hist[d] += 1\n else:\n hist[d] = 1\nprint(\"degree #nodes\")\nfor d in hist:\n print(f\"{d:4} {hist[d]:6}\")\n\npos = nx.spring_layout(G, seed=seed) # Seed layout for reproducibility\nnx.draw(G, pos=pos)\nplt.show()"
]
}
],
diff --git a/_downloads/795910d260da8b0e1d747500a0b724d6/plot_davis_club.ipynb b/_downloads/795910d260da8b0e1d747500a0b724d6/plot_davis_club.ipynb
index 6bba3cca..5a4bc4b0 100644
--- a/_downloads/795910d260da8b0e1d747500a0b724d6/plot_davis_club.ipynb
+++ b/_downloads/795910d260da8b0e1d747500a0b724d6/plot_davis_club.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import matplotlib.pyplot as plt\nimport networkx as nx\nimport networkx.algorithms.bipartite as bipartite\n\nG = nx.davis_southern_women_graph()\nwomen = G.graph[\"top\"]\nclubs = G.graph[\"bottom\"]\n\nprint(\"Biadjacency matrix\")\nprint(bipartite.biadjacency_matrix(G, women, clubs))\n\n# project bipartite graph onto women nodes\nW = bipartite.projected_graph(G, women)\nprint()\nprint(\"#Friends, Member\")\nfor w in women:\n print(f\"{W.degree(w)} {w}\")\n\n# project bipartite graph onto women nodes keeping number of co-occurence\n# the degree computed is weighted and counts the total number of shared contacts\nW = bipartite.weighted_projected_graph(G, women)\nprint()\nprint(\"#Friend meetings, Member\")\nfor w in women:\n print(f\"{W.degree(w, weight='weight')} {w}\")\n\npos = nx.spring_layout(G, seed=648) # Seed layout for reproducible node positions\nnx.draw(G, pos)\nplt.show()"
+ "import matplotlib.pyplot as plt\nimport networkx as nx\nfrom networkx.algorithms import bipartite\n\nG = nx.davis_southern_women_graph()\nwomen = G.graph[\"top\"]\nclubs = G.graph[\"bottom\"]\n\nprint(\"Biadjacency matrix\")\nprint(bipartite.biadjacency_matrix(G, women, clubs))\n\n# project bipartite graph onto women nodes\nW = bipartite.projected_graph(G, women)\nprint()\nprint(\"#Friends, Member\")\nfor w in women:\n print(f\"{W.degree(w)} {w}\")\n\n# project bipartite graph onto women nodes keeping number of co-occurence\n# the degree computed is weighted and counts the total number of shared contacts\nW = bipartite.weighted_projected_graph(G, women)\nprint()\nprint(\"#Friend meetings, Member\")\nfor w in women:\n print(f\"{W.degree(w, weight='weight')} {w}\")\n\npos = nx.spring_layout(G, seed=648) # Seed layout for reproducible node positions\nnx.draw(G, pos)\nplt.show()"
]
}
],
diff --git a/_downloads/868e28431bab2565b22bfbab847e1153/plot_dedensification.py b/_downloads/868e28431bab2565b22bfbab847e1153/plot_dedensification.py
index 9104d546..6fbbb687 100644
--- a/_downloads/868e28431bab2565b22bfbab847e1153/plot_dedensification.py
+++ b/_downloads/868e28431bab2565b22bfbab847e1153/plot_dedensification.py
@@ -38,7 +38,7 @@ original_graph.add_edges_from(
("A", "6"),
]
)
-base_options = dict(with_labels=True, edgecolors="black")
+base_options = {"with_labels": True, "edgecolors": "black"}
pos = {
"3": (0, 1),
"2": (0, 2),
diff --git a/_downloads/8a508c78cefb7056d5a2d2af5a610ed4/plot_maximum_independent_set.py b/_downloads/8a508c78cefb7056d5a2d2af5a610ed4/plot_maximum_independent_set.py
new file mode 100644
index 00000000..670edf96
--- /dev/null
+++ b/_downloads/8a508c78cefb7056d5a2d2af5a610ed4/plot_maximum_independent_set.py
@@ -0,0 +1,44 @@
+"""
+=======================
+Maximum Independent Set
+=======================
+
+An independent set is a set of vertices in a graph where no two vertices in the
+set are adjacent. The maximum independent set is the independent set of largest
+possible size for a given graph.
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+import networkx as nx
+from networkx.algorithms import approximation as approx
+
+G = nx.Graph(
+ [
+ (1, 2),
+ (7, 2),
+ (3, 9),
+ (3, 2),
+ (7, 6),
+ (5, 2),
+ (1, 5),
+ (2, 8),
+ (10, 2),
+ (1, 7),
+ (6, 1),
+ (6, 9),
+ (8, 4),
+ (9, 4),
+ ]
+)
+
+I = approx.maximum_independent_set(G)
+print(f"Maximum independent set of G: {I}")
+
+pos = nx.spring_layout(G, seed=39299899)
+nx.draw(
+ G,
+ pos=pos,
+ with_labels=True,
+ node_color=["tab:red" if n in I else "tab:blue" for n in G],
+)
diff --git a/_downloads/b3018a1aab7bffbd1426574de5a8c65a/plot_betweenness_centrality.py b/_downloads/b3018a1aab7bffbd1426574de5a8c65a/plot_betweenness_centrality.py
index e8354c66..eb1fe21a 100644
--- a/_downloads/b3018a1aab7bffbd1426574de5a8c65a/plot_betweenness_centrality.py
+++ b/_downloads/b3018a1aab7bffbd1426574de5a8c65a/plot_betweenness_centrality.py
@@ -1,7 +1,7 @@
"""
-=====================
-Betweeness Centrality
-=====================
+======================
+Betweenness Centrality
+======================
Betweenness centrality measures of positive gene functional associations
using WormNet v.3-GS.
@@ -70,13 +70,13 @@ ax.text(
ax.text(
0.80,
0.06,
- "node size = betweeness centrality",
+ "node size = betweenness centrality",
horizontalalignment="center",
transform=ax.transAxes,
fontdict=font,
)
-# Resize figure for label readibility
+# Resize figure for label readability
ax.margins(0.1, 0.05)
fig.tight_layout()
plt.axis("off")
diff --git a/_downloads/b7a826e19c8bd8bafecaae1ae69c7d1d/plot_triad_types.py b/_downloads/b7a826e19c8bd8bafecaae1ae69c7d1d/plot_triad_types.py
index eacbc6e8..a04c9303 100644
--- a/_downloads/b7a826e19c8bd8bafecaae1ae69c7d1d/plot_triad_types.py
+++ b/_downloads/b7a826e19c8bd8bafecaae1ae69c7d1d/plot_triad_types.py
@@ -57,7 +57,7 @@ for (title, triad), ax in zip(triads.items(), axes.flatten()):
fontsize=15,
fontweight="extra bold",
horizontalalignment="center",
- bbox=dict(boxstyle="square,pad=0.3", fc="none"),
+ bbox={"boxstyle": "square,pad=0.3", "fc": "none"},
)
fig.tight_layout()
plt.show()
diff --git a/_downloads/d071301e92e895067d308e076bb57540/plot_knuth_miles.ipynb b/_downloads/d071301e92e895067d308e076bb57540/plot_knuth_miles.ipynb
index eeff6586..45362fcd 100644
--- a/_downloads/d071301e92e895067d308e076bb57540/plot_knuth_miles.ipynb
+++ b/_downloads/d071301e92e895067d308e076bb57540/plot_knuth_miles.ipynb
@@ -26,7 +26,7 @@
},
"outputs": [],
"source": [
- "import gzip\nimport re\n\n# Ignore any warnings related to downloading shpfiles with cartopy\nimport warnings\n\nwarnings.simplefilter(\"ignore\")\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef miles_graph():\n \"\"\"Return the cites example graph in miles_dat.txt\n from the Stanford GraphBase.\n \"\"\"\n # open file miles_dat.txt.gz (or miles_dat.txt)\n\n fh = gzip.open(\"knuth_miles.txt.gz\", \"r\")\n\n G = nx.Graph()\n G.position = {}\n G.population = {}\n\n cities = []\n for line in fh.readlines():\n line = line.decode()\n if line.startswith(\"*\"): # skip comments\n continue\n\n numfind = re.compile(r\"^\\d+\")\n\n if numfind.match(line): # this line is distances\n dist = line.split()\n for d in dist:\n G.add_edge(city, cities[i], weight=int(d))\n i = i + 1\n else: # this line is a city, position, population\n i = 1\n (city, coordpop) = line.split(\"[\")\n cities.insert(0, city)\n (coord, pop) = coordpop.split(\"]\")\n (y, x) = coord.split(\",\")\n\n G.add_node(city)\n # assign position - Convert string to lat/long\n G.position[city] = (-float(x) / 100, float(y) / 100)\n G.population[city] = float(pop) / 1000\n return G\n\n\nG = miles_graph()\n\nprint(\"Loaded miles_dat.txt containing 128 cities.\")\nprint(G)\n\n# make new graph of cites, edge if less then 300 miles between them\nH = nx.Graph()\nfor v in G:\n H.add_node(v)\nfor (u, v, d) in G.edges(data=True):\n if d[\"weight\"] < 300:\n H.add_edge(u, v)\n\n# draw with matplotlib/pylab\nfig = plt.figure(figsize=(8, 6))\n\n# nodes colored by degree sized by population\nnode_color = [float(H.degree(v)) for v in H]\n\n# Use cartopy to provide a backdrop for the visualization\ntry:\n import cartopy.crs as ccrs\n import cartopy.io.shapereader as shpreader\n\n ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal(), frameon=False)\n ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())\n # Add map of countries & US states as a backdrop\n for shapename in (\"admin_1_states_provinces_lakes_shp\", \"admin_0_countries\"):\n shp = shpreader.natural_earth(\n resolution=\"110m\", category=\"cultural\", name=shapename\n )\n ax.add_geometries(\n shpreader.Reader(shp).geometries(),\n ccrs.PlateCarree(),\n facecolor=\"none\",\n edgecolor=\"k\",\n )\n # NOTE: When using cartopy, use matplotlib directly rather than nx.draw\n # to take advantage of the cartopy transforms\n ax.scatter(\n *np.array([v for v in G.position.values()]).T,\n s=[G.population[v] for v in H],\n c=node_color,\n transform=ccrs.PlateCarree(),\n zorder=100 # Ensure nodes lie on top of edges/state lines\n )\n # Plot edges between the cities\n for edge in H.edges():\n edge_coords = np.array([G.position[v] for v in edge])\n ax.plot(\n edge_coords[:, 0],\n edge_coords[:, 1],\n transform=ccrs.PlateCarree(),\n linewidth=0.75,\n color=\"k\",\n )\n\nexcept ImportError:\n # If cartopy is unavailable, the backdrop for the plot will be blank;\n # though you should still be able to discern the general shape of the US\n # from graph nodes and edges!\n nx.draw(\n H,\n G.position,\n node_size=[G.population[v] for v in H],\n node_color=node_color,\n with_labels=False,\n )\n\nplt.show()"
+ "import gzip\nimport re\n\n# Ignore any warnings related to downloading shpfiles with cartopy\nimport warnings\n\nwarnings.simplefilter(\"ignore\")\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef miles_graph():\n \"\"\"Return the cites example graph in miles_dat.txt\n from the Stanford GraphBase.\n \"\"\"\n # open file miles_dat.txt.gz (or miles_dat.txt)\n\n fh = gzip.open(\"knuth_miles.txt.gz\", \"r\")\n\n G = nx.Graph()\n G.position = {}\n G.population = {}\n\n cities = []\n for line in fh.readlines():\n line = line.decode()\n if line.startswith(\"*\"): # skip comments\n continue\n\n numfind = re.compile(r\"^\\d+\")\n\n if numfind.match(line): # this line is distances\n dist = line.split()\n for d in dist:\n G.add_edge(city, cities[i], weight=int(d))\n i = i + 1\n else: # this line is a city, position, population\n i = 1\n (city, coordpop) = line.split(\"[\")\n cities.insert(0, city)\n (coord, pop) = coordpop.split(\"]\")\n (y, x) = coord.split(\",\")\n\n G.add_node(city)\n # assign position - Convert string to lat/long\n G.position[city] = (-float(x) / 100, float(y) / 100)\n G.population[city] = float(pop) / 1000\n return G\n\n\nG = miles_graph()\n\nprint(\"Loaded miles_dat.txt containing 128 cities.\")\nprint(G)\n\n# make new graph of cites, edge if less then 300 miles between them\nH = nx.Graph()\nfor v in G:\n H.add_node(v)\nfor u, v, d in G.edges(data=True):\n if d[\"weight\"] < 300:\n H.add_edge(u, v)\n\n# draw with matplotlib/pylab\nfig = plt.figure(figsize=(8, 6))\n\n# nodes colored by degree sized by population\nnode_color = [float(H.degree(v)) for v in H]\n\n# Use cartopy to provide a backdrop for the visualization\ntry:\n import cartopy.crs as ccrs\n import cartopy.io.shapereader as shpreader\n\n ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal(), frameon=False)\n ax.set_extent([-125, -66.5, 20, 50], ccrs.Geodetic())\n # Add map of countries & US states as a backdrop\n for shapename in (\"admin_1_states_provinces_lakes_shp\", \"admin_0_countries\"):\n shp = shpreader.natural_earth(\n resolution=\"110m\", category=\"cultural\", name=shapename\n )\n ax.add_geometries(\n shpreader.Reader(shp).geometries(),\n ccrs.PlateCarree(),\n facecolor=\"none\",\n edgecolor=\"k\",\n )\n # NOTE: When using cartopy, use matplotlib directly rather than nx.draw\n # to take advantage of the cartopy transforms\n ax.scatter(\n *np.array(list(G.position.values())).T,\n s=[G.population[v] for v in H],\n c=node_color,\n transform=ccrs.PlateCarree(),\n zorder=100 # Ensure nodes lie on top of edges/state lines\n )\n # Plot edges between the cities\n for edge in H.edges():\n edge_coords = np.array([G.position[v] for v in edge])\n ax.plot(\n edge_coords[:, 0],\n edge_coords[:, 1],\n transform=ccrs.PlateCarree(),\n linewidth=0.75,\n color=\"k\",\n )\n\nexcept ImportError:\n # If cartopy is unavailable, the backdrop for the plot will be blank;\n # though you should still be able to discern the general shape of the US\n # from graph nodes and edges!\n nx.draw(\n H,\n G.position,\n node_size=[G.population[v] for v in H],\n node_color=node_color,\n with_labels=False,\n )\n\nplt.show()"
]
}
],
diff --git a/_downloads/e6a489a8b2deb49ed237fac38a28f429/plot_words.py b/_downloads/e6a489a8b2deb49ed237fac38a28f429/plot_words.py
index e5211f59..19a49eb8 100644
--- a/_downloads/e6a489a8b2deb49ed237fac38a28f429/plot_words.py
+++ b/_downloads/e6a489a8b2deb49ed237fac38a28f429/plot_words.py
@@ -65,7 +65,7 @@ print("Two words are connected if they differ in one letter.")
print(G)
print(f"{nx.number_connected_components(G)} connected components")
-for (source, target) in [("chaos", "order"), ("nodes", "graph"), ("pound", "marks")]:
+for source, target in [("chaos", "order"), ("nodes", "graph"), ("pound", "marks")]:
print(f"Shortest path between {source} and {target} is")
try:
shortest_path = nx.shortest_path(G, source, target)
diff --git a/_downloads/e921c603ea1764485dc9acff178a2f05/plot_knuth_miles.py b/_downloads/e921c603ea1764485dc9acff178a2f05/plot_knuth_miles.py
index e0ebea87..4d09684d 100644
--- a/_downloads/e921c603ea1764485dc9acff178a2f05/plot_knuth_miles.py
+++ b/_downloads/e921c603ea1764485dc9acff178a2f05/plot_knuth_miles.py
@@ -79,7 +79,7 @@ print(G)
H = nx.Graph()
for v in G:
H.add_node(v)
-for (u, v, d) in G.edges(data=True):
+for u, v, d in G.edges(data=True):
if d["weight"] < 300:
H.add_edge(u, v)
@@ -110,7 +110,7 @@ try:
# NOTE: When using cartopy, use matplotlib directly rather than nx.draw
# to take advantage of the cartopy transforms
ax.scatter(
- *np.array([v for v in G.position.values()]).T,
+ *np.array(list(G.position.values())).T,
s=[G.population[v] for v in H],
c=node_color,
transform=ccrs.PlateCarree(),
diff --git a/_downloads/efbe368eaa1e457c6c03d3f5a636063a/plot_blockmodel.py b/_downloads/efbe368eaa1e457c6c03d3f5a636063a/plot_blockmodel.py
index e3fec60b..b41f0c30 100644
--- a/_downloads/efbe368eaa1e457c6c03d3f5a636063a/plot_blockmodel.py
+++ b/_downloads/efbe368eaa1e457c6c03d3f5a636063a/plot_blockmodel.py
@@ -55,7 +55,7 @@ G = nx.read_edgelist("hartford_drug.edgelist")
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
+# Create partitions with hierarchical clustering
partitions = create_hc(H)
# Build blockmodel graph
BM = nx.quotient_graph(H, partitions, relabel=True)
diff --git a/_downloads/networkx_reference.pdf b/_downloads/networkx_reference.pdf
index ed802dfe..157f81de 100644
--- a/_downloads/networkx_reference.pdf
+++ b/_downloads/networkx_reference.pdf
Binary files differ