如何解决将dict评估为networkx中的边缘权重
在networkx多重图中,我存储了一个不同值的字典(在下面的示例中,a
和b
)。如何评估最短路径算法(例如Dijkstra)的权重(例如lambda
或键)?对于评估,它是a
或b
。
import networkx as nx
G = nx.MultiGraph()
G.add_edge('a','b',weight_dict={'a' : 1,'b': 2})
G.add_edge('a',weight_dict={'a' : 10,'b': 9})
G.add_edge('b','c','b': 1})
G.add_edge('a',weight_dict={'a' : 30,'b': 30})
nx.multi_source_dijkstra(G,{'a'},weight=lambda u,v,d: G[u][v][d]['a']) # obviously does not work
解决方法
由于它是一个多图,因此作为预处理,可以以最小的权重(对于给定的属性名称)检索一组边。然后,根据networkx
文档,
weight(字符串或函数)–如果这是一个函数,则边的权重是该函数返回的值。该函数必须恰好接受三个位置参数:边的两个端点和该边的边属性字典。该函数必须返回一个数字。
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',weight_dict={'a' : 10,'b': 9})
G.add_edge('b','c','b': 1})
G.add_edge('a',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','c']})
attribute_name = 'b'
产生
({'a': 0,'b': 2,'c': 3},'c']})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。