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.

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.

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
```

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 [2]:

```
cd ../../
```

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 [3]:

```
from networkit import *
```

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]:

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")
```

`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)
```

In [9]:

```
G.toString()
```

Out[9]:

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])
```

In [11]:

```
G.hasEdge(42,11)
```

Out[11]:

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

In [12]:

```
G.weight(42,11)
```

Out[12]:

Sometimes it be may interesting to take a glance at a visualization of a graph. As this is not the scope of NetworKit, the `viztasks`

-module provides two convenience functions to draw graphs via NetworkX. If you have it installed, you will see usage examples throughout this guide.

It also possible to load a graph and the results of our analytic kernels directly into Gephi, a software package for interactive graph visualization, via its streaming plugin. You may want to take a look at the GephiStreaming notebook.

The `profiling`

-module introduced with version 4.0 of NetworKit is the successor of the `properties`

-module. It provides a convenient way to run a selection of NetworKit's analytic kernels. The results are further processed to show all kinds of statistics. A very brief example follows. First, let's load a different graph:

In [13]:

```
astro = readGraph("input/astro-ph.graph", Format.METIS)
```

One simple function call is enough to run and evaluate several kernels. The `preset`

-parameter is a convenient way to choose a set of algorithms. Currently, `minimal`

, `default`

and `complete`

can be passed.

In [14]:

```
pf = profiling.Profile.create(astro, preset="minimal")
```

When running inside a notebook, the `show`

-function can be used to display the profile. Depending on the selection of kernels, it may take a while to produce all the plots.

In [15]:

```
pf.show()
```

It is also possible to save the profile in a file with the following command. Two formats are available: `HTML`

and `LaTeX`

.

In [16]:

```
pf.output("HTML",".")
```

For a more customized selection of kernels, a `Config`

-object can be created and passed to `Profile.create`

. Take a look at the specific Profiling notebook for more detailed instructions.

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 [17]:

```
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())
```

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 [18]:

```
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)
plt.show()
```

We choose a logarithmic scale on both axes because a *powerlaw degree distribution*, a characteristic feature of complex networks, would show up as a straight line from the top left to the bottom right on such a plot. As we see, the degree distribution of the `PGPgiantcompo`

network is definitely skewed, with few high-degree nodes and many low-degree nodes. But does the distribution actually obey a power law? In order to study this, we need to apply the powerlaw module. Call the following function:

In [19]:

```
import powerlaw
fit = powerlaw.Fit(dd)
```

The powerlaw coefficient can then be retrieved via:

In [20]:

```
fit.alpha
```

Out[20]:

If you further want to know how "good" it fits the power law distribution, you can use the the `distribution_compare`

-function. From the documentation of the function:

R : float

Loglikelihood ratio of the two distributions' fit to the data. If greater than 0, the first distribution is preferred. If less than 0, the second distribution is preferred.

p : float

Significance of R

In [21]:

```
fit.distribution_compare('power_law','exponential')
```

Out[21]:

In the most general sense, transitivity measures quantify how likely it is that the relations out of which the network is built are transitive. The clustering coefficient is the most prominent of such measures. We need to distinguish between global and local clustering coefficient: The global clustering coefficient for a network gives the fraction of closed triads. The local clustering coefficient focuses on a single node and counts how many of the possible edges between neighbors of the node exist. The average of this value over all nodes is a good indicator for the degreee of transitivity and the presence of community structures in a network, and this is what the following function returns:

In [22]:

```
globals.clustering(G)
```

Out[22]:

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

In [23]:

```
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 [24]:

```
sum(bfsdist) / len(bfsdist)
```

Out[24]:

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 [25]:

```
dijkstra = graph.Dijkstra(G, v)
dijkstra.run()
spdist = dijkstra.getDistances()
sum(spdist) / len(spdist)
```

Out[25]:

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 [26]:

```
K = readGraph("input/karate.graph",Format.METIS)
coreDec = centrality.CoreDecomposition(K)
coreDec.run()
```

Out[26]:

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 [27]:

```
set(coreDec.scores())
```

Out[27]:

In [28]:

```
viztasks.drawGraph(K, nodeSizes=[(k**2)*20 for k in coreDec.scores()])
plt.show()
```

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 [29]:

```
community.detectCommunities(G)
```

Out[29]:

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 [30]:

```
communities = community.detectCommunities(G)
```

*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 [31]:

```
community.Modularity().getQuality(communities, G)
```

Out[31]:

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 [32]:

```
type(communities)
```

Out[32]:

In [33]:

```
print("{0} elements assigned to {1} subsets".format(communities.numberOfElements(), communities.numberOfSubsets()))
```

In [34]:

```
print("the biggest subset has size {0}".format(max(communities.subsetSizes())))
```

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 [35]:

```
community.writeCommunities(communities, "output/communties.partition")
```

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 [36]:

```
community.detectCommunities(G, algo=community.PLM(G, True))
```

Out[36]:

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.

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 [37]:

```
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)
plt.show()
```

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 [38]:

```
c2 = communities.getMembers(2)
g2 = G.subgraphFromNodes(c2)
```

In [39]:

```
communities.subsetSizeMap()[2]
```

Out[39]:

In [40]:

```
g2.numberOfNodes()
```

Out[40]:

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 [41]:

```
communities2 = community.detectCommunities(g2)
```

In [42]:

```
viztasks.drawCommunityGraph(g2,communities2)
plt.show()
```

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

module.

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 [43]:

```
K = readGraph("input/karate.graph", Format.METIS)
```

In [44]:

```
bc = centrality.Betweenness(K)
bc.run()
```

Out[44]:

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 [45]:

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

Out[45]:

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 [46]:

```
abc = centrality.ApproxBetweenness(G, epsilon=0.1)
abc.run()
```

Out[46]:

The 10 most central nodes according to betweenness are then

In [47]:

```
abc.ranking()[:10]
```

Out[47]:

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 [48]:

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

Out[48]:

In [49]:

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

Out[49]:

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 [50]:

```
import networkx as nx
nxG = nxadapter.nk2nx(G) # convert from NetworKit.Graph to networkx.Graph
print(nx.degree_assortativity_coefficient(nxG))
```

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 [51]:

```
ERG = generators.ErdosRenyiGenerator(1000, 0.1).generate()
profiling.Profile.create(ERG, preset="minimal").show()
```