I'm working on a networkx graph project. one of my tasks is to find out the shortest path between two nodes and sumup the weights. I can locate the shortest path, as you may see. However, I have no idea how to sum up the weights of each edge in the shortest path. I think there is going to be a simple function in the package, but I found none.
import matplotlib.pyplot as plt
import networkx as nx
def graph(path):
G = nx.Graph()
for line in open(path):
strlist = line.split(',')
n1 = strlist[0].replace('.0', '')
n2 = strlist[1].replace('.0', '')
weight = round(float(strlist[2]), 2)
G.add_weighted_edges_from([(n1, n2, weight)])
# labels = dict((i, i) for i in G.nodes())
# nx.draw_networkx_labels(G, pos=nx.spring_layout(G), labels=labels)
# plt.savefig(filename)
elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] > 0.5]
esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d["weight"] <= 0.5]
pos = nx.spring_layout(G)
# nodes
nx.draw_networkx_nodes(G, pos, node_size=200, node_color='#ff0000', alpha=0.9)
# edges
nx.draw_networkx_edges(G, pos, edgelist=elarge, width=1, edge_color='b', alpha=0.05)
nx.draw_networkx_edges(G, pos, edgelist=esmall, width=1, edge_color='b', alpha=0.3)
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
nx.draw_networkx_edge_labels(G, pos, edge_labels, font_size=8, font_family='sans-serif')
plt.axis("off")
plt.show()
return G
G = graph('graph.csv')
shortest_value = nx.shortest_path_length(G, source='210', target='2771')
print(shortest_value)
shortest_path = nx.shortest_path(G, source='210', target='2771', method='dijkstra')
print('shortest path:{}'.format(shortest_path))
print('distance:{}'.format(shortest_value))
Use networkx.Graph.size.
From the examples:
>>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> G.size()
2
>>> G.size(weight="weight")
6.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With