由于它是一个多重图,作为预处理,人们可以检索具有最小权重的一组边(对于给定的属性名称)。然后,根据networkx 文档,
weight (string or function) – 如果这是一个函数,边的权重是函数返回的值。该函数必须准确地接受三个位置参数:一条边的两个端点和该边的边属性字典。该函数必须返回一个数字。
import networkx as nx
import pandas as pd
#Function to get minimal edges per attribute name
def get_edge_attributes(G, name):
edges = G.edges(data=True)
rows = [(e[0],e[1],e[-1]['weight_dict'][name]) for e in edges]
df = pd.DataFrame(rows)
df = df.iloc[df.groupby([0,1])[2].idxmin()]
return df
G = nx.MultiGraph()
G.add_edge('a', 'b', weight_dict={'a' : 1, 'b': 2})
G.add_edge('a', 'b', weight_dict={'a' : 10, 'b': 9})
G.add_edge('b', 'c', weight_dict={'a' : 1, 'b': 1})
G.add_edge('a', 'c', weight_dict={'a' : 30, 'b': 30})
attribute_name = 'a'
#Retrieve minimal weigths
subweight = get_edge_attributes(G,attribute_name)
#Function to retrieve weigths. It takes into account that the graph is undirected.
def return_weight(u,v,d):
x = subweight[((subweight[0]==u)&(subweight[1]==v))|
((subweight[1]==u)&(subweight[0]==v))][2].values[0]
return x
# Run
nx.multi_source_dijkstra(G, {'a'}, weight=return_weight)
使用attribute_name = 'a' 运行产生
({'a': 0, 'b': 1, 'c': 2}, {'a': ['a'], 'b': ['a', 'b'], 'c': ['a', 'b', 'c']})
而attribute_name = 'b' 产生
({'a': 0, 'b': 2, 'c': 3}, {'a': ['a'], 'b': ['a', 'b'], 'c': ['a', 'b', 'c']})