【问题标题】:How to search a specific path using node labels and return node ids in Networkx?如何在 Networkx 中使用节点标签搜索特定路径并返回节点 ID?
【发布时间】:2021-01-06 10:57:05
【问题描述】:

我有一个使用 Networkx 的网络图,其中每个节点都有一个 id:1 到 N。每个节点还有一个标签,它是一个字符串(为简单起见,字母)。我希望能够搜索这些标签的特定列表并找到与路径对应的节点 ID。例如,我想从下面的网络中找到路径 ['l', 'a', 'o'] 并返回节点 id,正确答案是 [1, 4, 5]:

import numpy as np
import networkx as nx
import matplotlib.pyplot as plt


def set_node_labels(G, arr):
    values = arr.flatten()
    labels = {}
    for node in G.nodes():
        labels[node] = values[node]
    nx.set_node_attributes(G, labels, "label")
    return labels

test_array = np.array([['f', 'l', 'p'],
                       ['r', 'a', 'o'],
                       ['b', 't', 'd']])


W,H = test_array.shape

index_array = np.arange(0, len(test_array.ravel()), 1, dtype=np.uint8).reshape((W,H))
print(index_array)


node_connections = []
for j in range(H-1):
    for i in range(W-1):
        n1 = (index_array[j, i], index_array[j, i+1])
        n2 = (index_array[j, i], index_array[(j+1), i])
        n3 = (index_array[j, i], index_array[(j+1), i+1])

        node_connections.extend([n1, n2, n3])
    n4 = (index_array[j, W-1], index_array[(j + 1), W-1])
    node_connections.extend([n4])

print(node_connections)

# create graph
G = nx.MultiGraph()
G.add_edges_from(node_connections)

labels = set_node_labels(G, test_array)

这有两个麻烦:1)如何搜索特定路径,而不仅仅是源和目标;如何使用标签搜索并返回 id? 非常感谢任何帮助。

【问题讨论】:

    标签: python networking networkx


    【解决方案1】:

    我想出了一个结果。这可能不是最有效的,但如果其他人想到更好的方法,请发布。添加这个以防这可能对任何人都有帮助。

    import numpy as np
    import networkx as nx
    import matplotlib.pyplot as plt
    
    
    def set_node_labels(G, arr):
        values = arr.flatten()
        labels = {}
        for node in G.nodes():
            labels[node] = values[node]
        nx.set_node_attributes(G, labels, "label")
        return labels
    
    
    def get_possible_seq(seq, idx_array, letter_array, G):
        found_seqs = []
        found_sqs_loc = []
        first_letter = seq[0]
        last_letters = seq[1:]
        first_letter_idx = idx_array[np.where(letter_array == first_letter)]
        last_letters_idx = []
        for letters in last_letters:
            last_letters_idx.extend(idx_array[np.where(letter_array == [letter for letter in letters])])
    
        for s in first_letter_idx:
    
            # correction for double counting on start letter position
            last_letters_idx = np.array(last_letters_idx)[last_letters_idx != s]
    
            for path in nx.all_simple_paths(G, s, last_letters_idx, cutoff=len(seq) - 1):
                string = []
                for node in path:
                    string.extend(G.nodes[node]['label'])
                found_seqs.append(string)
                found_sqs_loc.append(path)
        return found_seqs, found_sqs_loc
    
    
    test_array = np.array([['f', 'l', 'p'],
                           ['r', 'a', 'o'],
                           ['b', 't', 'd']])
    
    test_seqs = ['lao']
    
    W,H = test_array.shape
    
    index_array = np.arange(0, len(test_array.ravel()), 1, dtype=np.uint8).reshape((W,H))
    
    node_connections = []
    for j in range(H-1):
        for i in range(W-1):
            n1 = (index_array[j, i], index_array[j, i+1])
            n2 = (index_array[j, i], index_array[(j+1), i])
            n3 = (index_array[j, i], index_array[(j+1), i+1])
    
            node_connections.extend([n1, n2, n3])
        n4 = (index_array[j, W-1], index_array[(j + 1), W-1])
        node_connections.extend([n4])
    
    # create graph
    G = nx.MultiGraph()
    G.add_edges_from(node_connections)
    
    labels = set_node_labels(G, test_array)
    
    found_seqs, found_seqs_loc = get_possible_seq(test_seqs[0], index_array, test_array, G)
    print(found_seqs)
    print(found_seqs_loc)
    print(list(test_seqs[0]))
    target_seq_idx = found_seqs.index(list(test_seqs[0]))
    print(target_seq_idx)
    print(found_seqs_loc[target_seq_idx])
    

    这给出了 [1, 4, 5] 的正确答案。但是,这仅在只有一个相关序列实例时才有效。如果没有,它只会给出第一个实例。

    【讨论】:

      猜你喜欢
      • 2012-01-02
      • 2022-08-18
      • 2021-04-20
      • 1970-01-01
      • 1970-01-01
      • 2023-01-02
      • 1970-01-01
      • 2011-08-21
      • 2021-03-13
      相关资源
      最近更新 更多