在networkx中给定距离内高效识别ancestors/descendants

Efficiently identifying ancestors/descendants within a given distance, in networkx

networkx 中是否有 function/method 来识别给定(可选加权)距离内的所有 ancestors/descendants?

例如,是否可以有效地产生与以下函数相同的结果?

import networkx
g = networkx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
                (1, 3, {'length':11}),
                (2, 4, {'length':4}),
                (2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)

def descendants_within(graph, start_node=1, constraint=10, weight='length'):
    result = set()
    for node in networkx.descendants(graph, start_node):
        if networkx.shortest_path_length(graph, start_node, node, weight) < constraint:
            result.add(node)
    return result

print(descendants_within(g))

#set([2, 4])

一些 NetworkX 最短路径算法有一个 "cutoff" 参数。例如,在您的情况下,您可以 运行 从源节点到所有其他节点的 "single source shortest path" 计算,并将搜索限制为短于指定截止长度的路径。在下面的示例中,Dijkstra 算法用于计算加权网络的最短路径。

import networkx as nx
g = nx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
                (1, 3, {'length':11}),
                (2, 4, {'length':4}),
                (2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)

lengths = nx.single_source_dijkstra_path_length(g, source=1, weight='length', cutoff=10)
print(dict(lengths).keys())
# [1, 2, 4]