networkit-rs 0.1.0

Rust bindings for Networkit
Documentation
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# NetworKit Graph Tutorial"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this notebook we will cover the main functionalities of `networkit.Graph`, the central class in NetworKit. The first step is to import NetworKit."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import networkit as nk"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We start by creating the core object, a `networkit.Graph`. The [networkit.Graph](https://networkit.github.io/dev-docs/python_api/networkit.html?highlight=graph#networkit.Graph) constructor expects the `number of nodes` as an integer, a boolean value stating if the graph is weighted or not followed by another boolean value stating whether the graph is directed or not. The latter two are set to false by default. If the graph is unweighted, all edge weights are set to `1.0`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G = nk.Graph(5)\n",
    "print(G.numberOfNodes(), G.numberOfEdges())\n",
    "print(G.isWeighted(), G.isDirected())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`G` has 5 nodes, but no edges yet. Using the [addEdge(node u, node v)](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=addedge#networkit.graph.Graph.addEdge) method, we can add edges between the nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.addEdge(1, 3)\n",
    "G.addEdge(2, 4)\n",
    "G.addEdge(1, 2)\n",
    "G.addEdge(3, 4)\n",
    "G.addEdge(2, 3)\n",
    "G.addEdge(4, 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Node IDs in NetworKit are integer indices that start at 0 through to `G.upperNodeIdBound() - 1`. Hence, for this graph `G.addEdge(1,5)` would an illegal operation as node `5` does not exist. The same goes for edge IDs. If we need to add an edge between node 0 and node 5, we first need to add a sixth node to the graph using `G.addNode()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.addNode()\n",
    "print(G.numberOfNodes())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can add the new edge."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.addEdge(0,5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using the method [overview(G)](https://networkit.github.io/dev-docs/python_api/networkit.html?highlight=overview#networkit.overview), we can take a look at the main properties of the graph we have created."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nk.overview(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have created a graph we can start to play around with it. Say we want to remove the node with the node ID 2, so the third node. We can easily do so using [Graph.removeNode(node u)](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=remove%20node#networkit.graph.Graph.removeNode). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.removeNode(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2 has been deleted\n",
    "print(G.hasNode(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The node has been remove from the graph, however, the node IDs are not adjusted to the match the new number of nodes. Hence, if we want to restore the node we previously removed from G, we can do so using [Graph.restoreNode(node u)](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=restore#networkit.graph.Graph.restoreNode) using the original node ID."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Restore node with ID 2\n",
    "G.restoreNode(2)\n",
    "\n",
    "# Check if it is back in G\n",
    "print(G.hasNode(2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that in default mode NetworKit allows you to add an edge multiple times, most algorithms (and also io-functions) do not support it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.addNode()\n",
    "G.addEdge(0, 6)\n",
    "print(G.numberOfEdges())\n",
    "# NetworKit does not complain when inserting the same edge a second time \n",
    "G.addEdge(0, 6)\n",
    "print(G.numberOfEdges())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If wanted, this behavior can be changed. This increases the running time of adding an edge by the degree of the involved nodes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Remove one of the multiple edges\n",
    "G.removeEdge(0, 6)\n",
    "print(G.numberOfEdges())\n",
    "# The multi-edge is not added to the graph. \n",
    "G.addEdge(0, 6, checkMultiEdge = True)\n",
    "print(G.numberOfEdges())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NetworKit provides iterators that enable iterating over all nodes or edges in a simple manner. There are two kinds of iterators: one is based on ranges, the other one accepts callback a function.\n",
    "The easiest to use are the range-based iterators, they can be used in a simple for loop:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Iterate over the nodes of G\n",
    "for u in G.iterNodes():\n",
    "    print(u)\n",
    "    if u > 4:\n",
    "        print('...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Iterate over the edges of G\n",
    "for u, v in G.iterEdges():\n",
    "    print(u, v)\n",
    "    if u > 2:\n",
    "        print('...')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Iterate over the edges of G1 and include weights\n",
    "G1 = nk.graphtools.toWeighted(G)\n",
    "G1.setWeight(0, 4, 2)\n",
    "G1.setWeight(1, 3, 3)\n",
    "for u, v, w in G1.iterEdgesWeights():\n",
    "    print(u, v, w)\n",
    "    if u > 2:\n",
    "        print('...')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Callback-based iterators accept a callback function passed to the iterators as input parameter.\n",
    "Those functions can also be lambda functions.\n",
    "More information can be found in the NetworKit documentation [here](https://networkit.github.io/dev-docs/python_api/graph.html). Let's start by using the [forNodes](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=fornodes#networkit.graph.Graph.forNodes) iterator. It expects a callback function which accepts one parameter, i.e., a node. First, we define such a function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def nodeFunc(u):\n",
    "    print(\"Node \", u, \" passed to nodeFunc()\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We then pass `nodeFunc` to the iterator. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.forNodes(nodeFunc)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.forNodes(lambda u: print(\"Node \", u, \" passed to lambda\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Similarly, we can iterate over the edges of `G`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# First define callback function\n",
    "# that accepts exactly 4 parameters:\n",
    "def edgeFunc(u, v, weight, edgeId):\n",
    "    print(\"Edge from {} to {} has weight {} and id {}\".format(u, v, weight, edgeId))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now call the [forEdges](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=foredges#networkit.graph.Graph.forEdges) iterator, and pass `edgeFunc` to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Using iterator with callback function.\n",
    "G.forEdges(edgeFunc)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Although we did not add any indexes to our edges, our edges all have indexes of 0. This is because NetworKit by default indexes all edges with 0. However, sometimes it makes sense to have indexed edges. If you decide to index the edges of your graph after creating it, you can use the [Graph.indexEdges(bool force = False)](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=indexedges#networkit.graph.Graph.indexEdges) method. The `force` parameter forces re-indexing of edges if they had already been indexed."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we did not index the edges of our graph initially, we can use the default value. Indexing the edges of `G` can then be done as simply as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.indexEdges()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes you also need to iterate over specific edges, for example the ones connecting a node `u` to its neighbors. Using the [forNodes](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=foredges#networkit.graph.Graph.forNodes) iterator and the [forEdgesOf](https://networkit.github.io/dev-docs/python_api/graph.html?highlight=foredges#networkit.graph.Graph.forEdges) iterator we can do so."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.forNodes(lambda u: G.forEdgesOf(u, edgeFunc))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note, in an undirected graph, like we have here, the [forEdgesOf](https://networkit.github.io/dev-docs/python_api/networkit.html?highlight=foredgesof#networkit.Graph.forEdgesOf) iterator returns all edges of a node. When dealing with a directed graph only the out edges are returned. The rest of the edges can be accessed using the [forInEdgesOf](https://networkit.github.io/dev-docs/python_api/networkit.html?highlight=forinedges#networkit.Graph.forInEdgesOf) iterator."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Node Attributes\n",
    "\n",
    "It is possible to attach attributes to the nodes of a NetworKit graph with `attachNodeAttribute`. Attributes can be of type `str`, `float`, or `int`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a new attribute named 'myAtt' of type 'str'\n",
    "att = G.attachNodeAttribute(\"myAtt\", str)\n",
    "\n",
    "# Set attribute values\n",
    "att[0] = \"foo\" # Attribute of node 0\n",
    "att[1] = \"bar\" # Attribute of node 1\n",
    "\n",
    "# Get attribute value\n",
    "for u in G.iterNodes():\n",
    "    try:\n",
    "        print(f\"Attribute of node {u} is {att[u]}\")\n",
    "    except ValueError:\n",
    "        print(f\"Node {u} has no attribute\")\n",
    "        break    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## GraphTools"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`networkit.graphtools` implements some useful functions to get information or modify graphs. The following section shows some of the GraphTools functionalities."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`toWeighted(G)` takes an unweighted graph `G` as input, and returns a weighted copy of `G`. All the edge weights are set to a default value of 1.0."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "weightedG = nk.graphtools.toWeighted(G)\n",
    "assert(weightedG.numberOfNodes() == G.numberOfNodes())\n",
    "assert(weightedG.numberOfEdges() == G.numberOfEdges())\n",
    "assert(weightedG.isWeighted())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`toUnweighted(G)` does the inverse of the one above: it takes a weighted graph `G` as input, and returns an unweighted copy of `G` as output."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`randomNode(G)` returns a node of `G` selected uniformly at random."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nk.graphtools.randomNode(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`randomNeighbor(G, u)` returns a random (out) neighbor of node `u` in the graph `G`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nk.graphtools.randomNeighbor(G, 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`randomEdge(G, uniformDistribution=False)` returns a random edge of graph `G`. If `uniformDistribution` is set to `True`, the edge is selected uniformly at random."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nk.graphtools.randomEdge(G, True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes it makes sense to compact the graph, e.g., after deleting nodes. The method `getCompactedGraph(G, nodeIdMap)` does just that by designating continuous node ids. `nodeIdMap` maps each node id of graph `G` to their new ids.\n",
    "\n",
    "First, we delete a node from `G`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "G.removeNode(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, we use `getContinuousNodeIds(G)` to get a map from the original nodes ids of G, to their new ids."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nodeIdMap = nk.graphtools.getContinuousNodeIds(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we get a new graph with compacted node ids."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "compGraph = nk.graphtools.getCompactedGraph(G, nodeIdMap)\n",
    "assert(compGraph.numberOfNodes() == G.numberOfNodes())\n",
    "assert(compGraph.numberOfEdges() == G.numberOfEdges())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`maxDegree(G)` returns the highest (out) degree of `G`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nk.graphtools.maxDegree(G)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`maxInDegree(G)` returns the highest in-degree of a directed graph `G`. `maxWeightedDegree(G)` returns the highest sum of the (out) edge weights of `G`, while `maxWeightedInDegree(G)` returns the highest sum of the in-edge weights of a directed graph `G`."
   ]
  }
 ],
 "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.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}