OOPNET in the middle - Centrality calculations¶
Another graph theoretic example of what you can do together with OOPNET and NetworkX.
In this example, different centrality calculations are shown. NetworkX is again used for the matrix calculations.
First, the necessary packages are imported, a filename is declared and an OOPNET oopnet.Network
is created from the EPANET input file.
import os
import networkx as nx
from matplotlib import pyplot as plt
import pandas as pd
import oopnet as on
filename = os.path.join('data', 'C-town.inp')
net = on.Network.read(filename)
Then a networkx.MultiGraph
is created based on the Network.
G = on.MultiGraph(net)
Next, a Matplotlib figure is instantiated. This object will hold a subplot for all of the four centralities we will calculate:
plt.figure()
Now, the metrics are calculated. We pass the previously created networkx.MultiGraph
to different NetworkX functions to calculate the metrics. Since we want to plot the centrality values per node, we need a pandas Series to pass it to the OOPNET oopnet.Network.plot()
method. We change the series’ names so that it is correctly shown in the plot. Then, we create Matplotlib axes objects and plot the network with these axes objects.
dc = nx.degree_centrality(G)
dc = pd.Series(dc)
dc.name = 'Degree Centrality'
ax = plt.subplot(221)
net.plot(nodes=dc, ax=ax)
cc = nx.closeness_centrality(G)
cc = pd.Series(cc)
cc.name = 'Closeness Centrality'
ax = plt.subplot(222)
net.plot(nodes=cc, ax=ax)
bc = nx.betweenness_centrality(G)
bc = pd.Series(bc)
bc.name = 'Betweenness Centrality'
ax = plt.subplot(223)
net.plot(nodes=bc, ax=ax)
cfcc = nx.current_flow_closeness_centrality(G)
cfcc = pd.Series(cfcc)
cfcc.name = 'Current Flow Closeness Centrality'
ax = plt.subplot(224)
net.plot(nodes=cfcc, ax=ax)
To create a single plot for a centrality, just omit the axes object creation and don’t pass one to the plotting function:
lc = nx.load_centrality(G)
lc = pd.Series(lc)
lc.name = 'Load Centrality'
net.plot(nodes=lc)
Finally, show the plots:
plt.show()
Summary¶
import os
import networkx as nx
from matplotlib import pyplot as plt
import pandas as pd
import oopnet as on
filename = os.path.join('data', 'C-town.inp')
net = on.Network.read(filename)
G = on.MultiGraph(net)
plt.figure()
dc = nx.degree_centrality(G)
dc = pd.Series(dc)
dc.name = 'Degree Centrality'
ax = plt.subplot(221)
net.plot(nodes=dc, ax=ax)
cc = nx.closeness_centrality(G)
cc = pd.Series(cc)
cc.name = 'Closeness Centrality'
ax = plt.subplot(222)
net.plot(nodes=cc, ax=ax)
bc = nx.betweenness_centrality(G)
bc = pd.Series(bc)
bc.name = 'Betweenness Centrality'
ax = plt.subplot(223)
net.plot(nodes=bc, ax=ax)
cfcc = nx.current_flow_closeness_centrality(G)
cfcc = pd.Series(cfcc)
cfcc.name = 'Current Flow Closeness Centrality'
ax = plt.subplot(224)
net.plot(nodes=cfcc, ax=ax)
lc = nx.load_centrality(G)
lc = pd.Series(lc)
lc.name = 'Load Centrality'
net.plot(nodes=lc)
plt.show()