【问题标题】:Evaluate dict as edge weight in networkx将dict评估为networkx中的边缘权重
【发布时间】:2020-10-12 07:58:18
【问题描述】:

在 networkx 多重图中,我存储了一个包含不同值的字典(在以下示例中为 ab)。如何评估最短路径算法(例如,对于 Dijkstra)的权重(例如 lambda 或密钥)?对于评估,它是ab

import networkx as nx
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})

nx.multi_source_dijkstra(G, {'a'}, weight=lambda u, v, d: G[u][v][d]['a']) # obviously does not work

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    由于它是一个多重图,作为预处理,人们可以检索具有最小权重的一组边(对于给定的属性名称)。然后,根据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']})
    

    【讨论】:

      猜你喜欢
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-22
      • 1970-01-01
      • 2017-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多