1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Print Graph\n\nExample subclass of the Graph class.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import matplotlib.pyplot as plt\nimport networkx as nx\nfrom networkx import Graph\n\n\nclass PrintGraph(Graph):\n \"\"\"\n Example subclass of the Graph class.\n\n Prints activity log to file or standard output.\n \"\"\"\n\n def __init__(self, data=None, name=\"\", file=None, **attr):\n super().__init__(data=data, name=name, **attr)\n if file is None:\n import sys\n\n self.fh = sys.stdout\n else:\n self.fh = open(file, \"w\")\n\n def add_node(self, n, attr_dict=None, **attr):\n super().add_node(n, attr_dict=attr_dict, **attr)\n self.fh.write(f\"Add node: {n}\\n\")\n\n def add_nodes_from(self, nodes, **attr):\n for n in nodes:\n self.add_node(n, **attr)\n\n def remove_node(self, n):\n super().remove_node(n)\n self.fh.write(f\"Remove node: {n}\\n\")\n\n def remove_nodes_from(self, nodes):\n for n in nodes:\n self.remove_node(n)\n\n def add_edge(self, u, v, attr_dict=None, **attr):\n super().add_edge(u, v, attr_dict=attr_dict, **attr)\n self.fh.write(f\"Add edge: {u}-{v}\\n\")\n\n def add_edges_from(self, ebunch, attr_dict=None, **attr):\n for e in ebunch:\n u, v = e[0:2]\n self.add_edge(u, v, attr_dict=attr_dict, **attr)\n\n def remove_edge(self, u, v):\n super().remove_edge(u, v)\n self.fh.write(f\"Remove edge: {u}-{v}\\n\")\n\n def remove_edges_from(self, ebunch):\n for e in ebunch:\n u, v = e[0:2]\n self.remove_edge(u, v)\n\n def clear(self):\n super().clear()\n self.fh.write(\"Clear graph\\n\")\n\n\nG = PrintGraph()\nG.add_node(\"foo\")\nG.add_nodes_from(\"bar\", weight=8)\nG.remove_node(\"b\")\nG.remove_nodes_from(\"ar\")\nprint(\"Nodes in G: \", G.nodes(data=True))\nG.add_edge(0, 1, weight=10)\nprint(\"Edges in G: \", G.edges(data=True))\nG.remove_edge(0, 1)\nG.add_edges_from(zip(range(0, 3), range(1, 4)), weight=10)\nprint(\"Edges in G: \", G.edges(data=True))\nG.remove_edges_from(zip(range(0, 3), range(1, 4)))\nprint(\"Edges in G: \", G.edges(data=True))\n\nG = PrintGraph()\nnx.add_path(G, range(10))\nnx.add_star(G, range(9, 13))\npos = nx.spring_layout(G, seed=225) # Seed for reproducible layout\nnx.draw(G, pos)\nplt.show()"
]
}
],
"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.15"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|