NetworKit User Guide

About NetworKit

NetworKit is an open-source toolkit for high-performance network analysis. Its aim is to provide tools for the analysis of large networks in the size range from thousands to billions of edges. For this purpose, it implements efficient graph algorithms, many of them parallel to utilize multicore architectures. These are meant to compute standard measures of network analysis, such as degree sequences, clustering coefficients and centrality. In this respect, NetworKit is comparable to packages such as NetworkX, albeit with a focus on parallelism and scalability. NetworKit is also a testbed for algorithm engineering and contains a few novel algorithms from recently published research, especially in the area of community detection.

Introduction

This notebook provides an interactive introduction to the features of NetworKit, consisting of text and executable code. We assume that you have read the Readme and successfully built the core library and the Python module. Code cells can be run one by one (e.g. by selecting the cell and pressing shift+enter), or all at once (via the Cell->Run All command). Try running all cells now to verify that NetworKit has been properly built and installed.

Preparation

This notebook creates some plots. To show them in the notebook, matplotlib must be imported and we need to activate matplotlib's inline mode:


In [1]:
%matplotlib inline
import matplotlib.pyplot as plt

NetworKit is a hybrid built from C++ and Python code: Its core functionality is implemented in C++ for performance reasons, and then wrapped for Python using the Cython toolchain. This allows us to expose high-performance parallel code as a normal Python module. On the surface, NetworKit is just that and can be imported accordingly:


In [2]:
from networkit import *


Update to Python >=3.4 recommended - support for < 3.4 may be discontinued in the future
 WARNING: module 'sklearn' not found, supervised link prediction won't be available 

IPython lets us use familiar shell commands in a Python interpreter. Use one of them now to change into the directory of your NetworKit download:


In [3]:
cd ../../


/amd.home/home/maxv/workspace/hiwi/NetworKit

Reading and Writing Graphs

Let us start by reading a network from a file on disk: PGPgiantcompo.graph. In the course of this tutorial, we are going to work on the PGPgiantcompo network, a social network/web of trust in which nodes are PGP keys and an edge represents a signature from one key on another. It is distributed with NetworKit as a good starting point.

There is a convenient function in the top namespace which tries to guess the input format and select the appropriate reader:


In [4]:
G = readGraph("input/PGPgiantcompo.graph", Format.METIS)

There is a large variety of formats for storing graph data in files. For NetworKit, the currently best supported format is the METIS adjacency format. Various example graphs in this format can be found here. The readGraph function tries to be an intelligent wrapper for various reader classes. In this example, it uses the METISGraphReader which is located in the graphio submodule, alongside other readers. These classes can also be used explicitly:


In [5]:
graphio.METISGraphReader().read("input/PGPgiantcompo.graph")
# is the same as: readGraph("input/PGPgiantcompo.graph", Format.METIS)


Out[5]:
<_NetworKit.Graph at 0x7f3ce9890738>

It is also possible to specify the format for readGraph() and writeGraph(). Supported formats can be found via [graphio.]Format. However, graph formats are most likely only supported as far as the NetworKit::Graph can hold and use the data. Please note, that not all graph formats are supported for reading and writing.

Thus, it is possible to use NetworKit to convert graphs between formats. Let's say I need the previously read PGP graph in the Graphviz format:


In [6]:
graphio.writeGraph(G,"output/PGPgiantcompo.graphviz", Format.GraphViz)

NetworKit also provides a function to convert graphs directly:


In [7]:
graphio.convertGraph(Format.LFR, Format.GML, "input/example.edgelist", "output/example.gml")


converted input/example.edgelist to output/example.gml

The Graph Object

Graph is the central class of NetworKit. An object of this type represents an undirected, optionally weighted network. Let us inspect several of the methods which the class provides.


In [8]:
n = G.numberOfNodes()
m = G.numberOfEdges()
print(n, m)


10680 24316

In [9]:
G.toString()


Out[9]:
b'Graph(name=PGPgiantcompo, n=10680, m=24316)'

Nodes are simply integer indices, and edges are pairs of such indices.


In [10]:
V = G.nodes()
print(V[:10])
E = G.edges()
print(E[:10])


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[(42, 11), (101, 28), (111, 92), (128, 87), (141, 0), (165, 125), (169, 111), (176, 143), (187, 38), (192, 105)]

In [11]:
G.hasEdge(42,11)


Out[11]:
True

This network is unweighted, meaning that each edge has the default weight of 1.


In [12]:
G.weight(42,11)


Out[12]:
1.0

Connected Components

A connected component is a set of nodes in which each pair of nodes is connected by a path. The following function determines the connected components of a graph:


In [13]:
cc = components.ConnectedComponents(G)
cc.run()
print("number of components ", cc.numberOfComponents())
v = 0
print("component of node ", v , ": " , cc.componentOfNode(0))
#print("map of component sizes: ", cc.getComponentSizes())


number of components  1
component of node  0 :  0

Degree Distribution

Node degree, the number of edges connected to a node, is one of the most studied properties of networks. Types of networks are often characterized in terms of their distribution of node degrees. We obtain and visualize the degree distribution of our example network as follows.


In [14]:
dd = sorted(centrality.DegreeCentrality(G).run().scores(), reverse=True)
plt.xscale("log")
plt.xlabel("degree")
plt.yscale("log")
plt.ylabel("number of nodes")
plt.plot(dd)


Out[14]:
[<matplotlib.lines.Line2D at 0x7f3ce9989410>]

Search and Shortest Paths

A simple breadth-first search from a starting node can be performed as follows:


In [15]:
v = 0
bfs = graph.BFS(G, v)
bfs.run()

bfsdist = bfs.getDistances()

The return value is a list of distances from v to other nodes - indexed by node id. For example, we can now calculate the mean distance from the starting node to all other nodes:


In [16]:
sum(bfsdist) / len(bfsdist)


Out[16]:
11.339044943820225

Similarly, Dijkstra's algorithm yields shortest path distances from a starting node to all other nodes in a weighted graph. Because PGPgiantcompo is an unweighted graph, the result is the same here:


In [17]:
dijkstra = graph.Dijkstra(G, v)
dijkstra.run()
spdist = dijkstra.getDistances()
sum(spdist) / len(spdist)


Out[17]:
11.339044943820225

Core Decomposition

A $k$-core decomposition of a graph is performed by successicely peeling away nodes with degree less than $k$. The remaining nodes form the $k$-core of the graph.


In [18]:
K = readGraph("input/karate.graph",Format.METIS)
coreDec = centrality.CoreDecomposition(K)
coreDec.run()


Out[18]:
<_NetworKit.CoreDecomposition at 0x7f3d0498b4d0>

Core decomposition assigns a core number to each node, being the maximum $k$ for which a node is contained in the $k$-core. For this small graph, core numbers have the following range:


In [19]:
set(coreDec.scores())


Out[19]:
{1.0, 2.0, 3.0, 4.0}

In [20]:
viztasks.drawGraph(K, nodeSizes=[(k**2)*20 for k in coreDec.scores()])


Community Detection

This section demonstrates the community detection capabilities of NetworKit. Community detection is concerned with identifying groups of nodes which are significantly more densely connected to eachother than to the rest of the network.

Code for community detection is contained in the community module. The module provides a top-level function to quickly perform community detection with a suitable algorithm and print some stats about the result.


In [21]:
community.detectCommunities(G)


PLM(balanced,pc) detected communities in 0.23692846298217773 [s]
solution properties:
-------------------  ----------
# communities        105
min community size     4
max community size   654
avg. community size  101.714
modularity             0.883963
-------------------  ----------
Out[21]:
<_NetworKit.Partition at 0x7f3cd99baa08>

The function prints some statistics and returns the partition object representing the communities in the network as an assignment of node to community label. Let's capture this result of the last function call.


In [22]:
communities = community.detectCommunities(G)


PLM(balanced,pc) detected communities in 0.2949557304382324 [s]
solution properties:
-------------------  ----------
# communities         74
min community size     6
max community size   662
avg. community size  144.324
modularity             0.882631
-------------------  ----------

Modularity is the primary measure for the quality of a community detection solution. The value is in the range [-0.5,1] and usually depends both on the performance of the algorithm and the presence of distinctive community structures in the network.


In [23]:
community.Modularity().getQuality(communities, G)


Out[23]:
0.882631010977874

The Partition Data Structure

The result of community detection is a partition of the node set into disjoint subsets. It is represented by the Partition data strucure, which provides several methods for inspecting and manipulating a partition of a set of elements (which need not be the nodes of a graph).


In [24]:
type(communities)


Out[24]:
_NetworKit.Partition

In [25]:
print("{0} elements assigned to {1} subsets".format(communities.numberOfElements(), communities.numberOfSubsets()))


10680 elements assigned to 74 subsets

In [26]:
print("the biggest subset has size {0}".format(max(communities.subsetSizes())))


the biggest subset has size 662

The contents of a partition object can be written to file in a simple format, in which each line i contains the subset id of node i.


In [27]:
community.writeCommunities(communities, "output/communties.partition")


wrote communities to: output/communties.partition

Choice of Algorithm

The community detection function used a good default choice for an algorithm: PLM, our parallel implementation of the well-known Louvain method. It yields a high-quality solution at reasonably fast running times. Let us now apply a variation of this algorithm.


In [28]:
community.detectCommunities(G, algo=community.PLP(G))


PLP detected communities in 0.03409552574157715 [s]
solution properties:
-------------------  --------
# communities        965
min community size     2
max community size   311
avg. community size   11.0674
modularity             0.7992
-------------------  --------
Out[28]:
<_NetworKit.Partition at 0x7f3cd98487c8>

We have switched on refinement, and we can see how modularity is slightly improved. For a small network like this, this takes only marginally longer.

Visualizing the Result

We can easily plot the distribution of community sizes as follows. While the distribution is skewed, it does not seem to fit a power-law, as shown by a log-log plot.


In [29]:
sizes = communities.subsetSizes()
sizes.sort(reverse=True)
ax1 = plt.subplot(2,1,1)
ax1.set_ylabel("size")
ax1.plot(sizes)

ax2 = plt.subplot(2,1,2)
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_ylabel("size")
ax2.plot(sizes)


Out[29]:
[<matplotlib.lines.Line2D at 0x7f3cd87a5710>]

Subgraph

NetworKit supports the creation of Subgraphs depending on an original graph and a set of nodes. This might be useful in case you want to analyze certain communities of a graph. Let's say that community 2 of the above result is of further interest, so we want a new graph that consists of nodes and intra cluster edges of community 2.


In [30]:
from networkit.graph import Subgraph
c2 = communities.getMembers(2)
sg = Subgraph()
g2 = sg.fromNodes(G,c2)

In [31]:
communities.subsetSizeMap()[2]


Out[31]:
165

In [32]:
g2.numberOfNodes()


Out[32]:
165

As we can see, the number of nodes in our subgraph matches the number of nodes of community 2. The subgraph can be used like any other graph object, e.g. further community analysis:


In [33]:
communities2 = community.detectCommunities(g2)


PLM(balanced,pc) detected communities in 0.136918306350708 [s]
solution properties:
-------------------  ---------
# communities        10
min community size    5
max community size   34
avg. community size  16.5
modularity            0.742036
-------------------  ---------

Centrality

Centrality measures the relative importance of a node within a graph. Code for centrality analysis is grouped into the centrality module.

Betweenness Centrality

We implement Brandes' algorithm for the exact calculation of betweenness centrality. While the algorithm is efficient, it still needs to calculate shortest paths between all pairs of nodes, so its scalability is limited. We demonstrate it here on the small Karate club graph.


In [34]:
K = readGraph("input/karate.graph", Format.METIS)

In [35]:
bc = centrality.Betweenness(K)
bc.run()


Out[35]:
<_NetworKit.Betweenness at 0x7f3cd864e450>

We have now calculated centrality values for the given graph, and can retrieve them either as an ordered ranking of nodes or as a list of values indexed by node id.


In [36]:
bc.ranking()[:10] # the 10 most central nodes


Out[36]:
[(0, 462.14285714285717),
 (33, 321.10317460317447),
 (32, 153.38095238095235),
 (2, 151.70158730158732),
 (31, 146.01904761904763),
 (8, 59.05873015873016),
 (1, 56.957142857142856),
 (13, 48.43174603174602),
 (19, 34.2936507936508),
 (6, 31.666666666666664)]

Approximation of Betweenness

Since exact calculation of betweenness scores is often out of reach, NetworKit provides an approximation algorithm based on path sampling. Here we estimate betweenness centrality in PGPgiantcompo, with a probabilistic guarantee that the error is no larger than an additive constant $\epsilon$.


In [37]:
abc = centrality.ApproxBetweenness(G, epsilon=0.1)
abc.run()


Out[37]:
<_NetworKit.ApproxBetweenness at 0x7f3cd864e7d0>

The 10 most central nodes according to betweenness are then


In [38]:
abc.ranking()[:10]


Out[38]:
[(1143, 0.1514423076923077),
 (6655, 0.09134615384615384),
 (7297, 0.08653846153846158),
 (6932, 0.08653846153846156),
 (6555, 0.0817307692307692),
 (3156, 0.06971153846153845),
 (6744, 0.06009615384615385),
 (5165, 0.06009615384615384),
 (4466, 0.050480769230769225),
 (5121, 0.04807692307692307)]

Eigenvector Centrality and PageRank

Eigenvector centrality and its variant PageRank assign relative importance to nodes according to their connections, incorporating the idea that edges to high-scoring nodes contribute more. PageRank is a version of eigenvector centrality which introduces a damping factor, modeling a random web surfer which at some point stops following links and jumps to a random page. In PageRank theory, centrality is understood as the probability of such a web surfer to arrive on a certain page. Our implementation of both measures is based on parallel power iteration, a relatively simple eigensolver.


In [39]:
# Eigenvector centrality
ec = centrality.EigenvectorCentrality(K)
ec.run()
ec.ranking()[:10] # the 10 most central nodes


Out[39]:
[(33, 0.3733586076353844),
 (0, 0.35548796275763045),
 (2, 0.317192121260797),
 (32, 0.3086416999617261),
 (1, 0.26595844854862444),
 (8, 0.22740614524354494),
 (13, 0.2264747568434207),
 (3, 0.21117969605316234),
 (31, 0.19103658572493032),
 (30, 0.1747599501690216)]

In [40]:
# PageRank
pr = centrality.PageRank(K, 1e-6)
pr.run()
pr.ranking()[:10] # the 10 most central nodes


Out[40]:
[(33, 0.029411904901855555),
 (0, 0.029411888071820148),
 (32, 0.029411844867300332),
 (1, 0.029411804779381052),
 (2, 0.029411798733649134),
 (3, 0.0294117712826769),
 (31, 0.02941177072521247),
 (5, 0.029411768995095986),
 (6, 0.029411768995095986),
 (23, 0.02941176398501432)]

NetworkX Compatibility

NetworkX is a popular Python package for network analysis. To let both packages complement eachother, and to enable the adaptation of existing NetworkX-based code, we support the conversion of the respective graph data structures.


In [41]:
import networkx as nx
nxG = nxadapter.nk2nx(G) # convert from NetworKit.Graph to networkx.Graph
print(nx.degree_assortativity_coefficient(nxG))


0.238211371708

Generating Graphs

An important subfield of network science is the design and analysis of generative models. A variety of generative models have been proposed with the aim of reproducing one or several of the properties we find in real-world complex networks. NetworKit includes generator algorithms for several of them.

The Erdös-Renyi model is the most basic random graph model, in which each edge exists with the same uniform probability. NetworKit provides an efficient generator:


In [42]:
ERG = generators.ErdosRenyiGenerator(1000, 0.1).generate()

A simple way to generate a random graph with community structure is to use the ClusteredRandomGraphGenerator. It uses a simple variant of the Erdös-Renyi model: The node set is partitioned into a given number of subsets. Nodes within the same subset have a higher edge probability.


In [43]:
CRG = generators.ClusteredRandomGraphGenerator(200, 4, 0.2, 0.002).generate()

In [44]:
community.detectCommunities(CRG)


PLM(balanced,pc) detected communities in 0.060219526290893555 [s]
solution properties:
-------------------  ---------
# communities         4
min community size   44
max community size   57
avg. community size  50
modularity            0.707399
-------------------  ---------
Out[44]:
<_NetworKit.Partition at 0x7f3cd85f9c00>

The Chung-Lu model (also called configuration model) generates a random graph which corresponds to a given degree sequence, i.e. has the same expected degree sequence. It can therefore be used to replicate some of the properties of a given real networks, while others are not retained, such as high clustering and the specific community structure.


In [45]:
degreeSequence = [G.degree(v) for v in G.nodes()]
clgen = generators.ChungLuGenerator(degreeSequence)

Settings

In this section we discuss global settings.

Logging

When using NetworKit from the command line, the verbosity of console output can be controlled via several loglevels, from least to most verbose: FATAL, ERROR, WARN, INFO, DEBUG and TRACE. (Currently, logging is only available on the console and not visible in the IPython Notebook).


In [46]:
getLogLevel() # the default loglevel


Out[46]:
'ERROR'

In [47]:
setLogLevel("TRACE") # set to most verbose mode
setLogLevel("ERROR") # set back to default

Please note, that the default build setting is optimized (--optimize=Opt) and thus, every LOG statement below INFO is removed. If you need DEBUG and TRACE statements, please build the extension module by appending --optimize=Dbg when calling the setup script.

Parallelism

The degree of parallelism can be controlled and monitored in the following way:


In [48]:
setNumberOfThreads(4) # set the maximum number of available threads

In [49]:
getMaxNumberOfThreads() # see maximum number of available threads


Out[49]:
4

In [50]:
getCurrentNumberOfThreads() # the number of threads currently executing


Out[50]:
1

Support

NetworKit is an open-source project that improves with suggestions and contributions from its users. The email list networkit@ira.uni-karlsruhe.de is the place for general discussion and questions. Also feel free to contact the authors with questions on how NetworKit can be applied to your research.

-- Christian L. Staudt and Henning Meyerhenke


In [ ]: