Different Graph Weights¶
In this example, we will discuss how to specify different weights for edges, when creating a Graph from an OOPNET network.
First, we import os
, networkx
and oopnet
.
import os
import networkx as nx
import oopnet as on
filename = os.path.join('data', 'C-town.inp')
We will use the “Anytown” model in this example, so we read it:
net = on.Network.read(filename)
When we create a networkx.Graph
(or networkx.DiGraph
, networkx.MultiGraph
or networkx.MultiDiGraph
) object using the corresponding factories in oopnet.graph
, the pipe lengths are used as weights in the graph. We will use Dijkstra’s shortest path to compare the different graphs.
G = on.MultiGraph(net)
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')
Average Shortest Path: 3494.6983087192225
You can specify a different weight, by passing a weight
argument. You can specify any Link attribute you want (e.g. roughness
). If a link doesn’t have the attribute, a default value is used 0.00001
).
G = on.MultiGraph(net, weight='diameter')
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')
Average Shortest Path: 6363.355196667406
You can specify a different default value, if you want to:
G = on.MultiGraph(net, weight='diameter', default=0)
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')
Average Shortest Path: 6363.355182198411
Summary¶
import os
import networkx as nx
import oopnet as on
filename = os.path.join('data', 'C-town.inp')
net = on.Network.read(filename)
G = on.MultiGraph(net)
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')
G = on.MultiGraph(net, weight='diameter')
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')
G = on.MultiGraph(net, weight='diameter', default=0)
avg_sp = nx.average_shortest_path_length(G, 'weight')
print(f'Average Shortest Path: {avg_sp}')