简体   繁体   中英

How to find a path between 2 nodes based on in-between node's attribute's value using networkx graph?

I can search thru a tree and get shortest path between nodes using just simple:

nx.shortest_path(G, source=, target=)

But how can I choose a path going thru a node with particular attribute's value?

I have simple graph with nodes

G = nx.Graph()
for token in document:
    G.add_node(token.orth_, item = token.i, tag = token.tag_, dep = token.dep_)

and edges:

for token in document:    
    for child in token.children:
        G.add_edge(token.orth_, child.orth_, pitem = token.i, citem = child.i,
                   ptag = token.tag_, pdep = token.dep_, ctag = child.tag_, cdep = child.dep_)

Can I find simple solution because now i'm struggling to build complicated function.

EDIT

The idea is to have a function like this: (sketchy)

def getPathByNode(betw_word, betw_attr, src_word, src_attr, trg_word, trg_attr):
    nx.shortest_path(G, source=src, source_attr=src_attr, target=trg, target_attr=trg_attr, through=betw_word, through_attr=betw_attr)
    ....

But of course not all parameters must be passed. As inputs I'd take for example:

source_attr = {'dep_': 'ROOT'}
target_attr = {'tag_': 'NN'}

through = "of" or through = "from" or through_attr = {'tag_': 'IN'}

And et cetera. I'm currently trying to build recursion starting from the middle ( through='from' ) and searchning for neighhbors but the same situatuion - missing attributes.

for i in G.neighbors("from"):
    print(i)

i is just a string.

A simple solution would be computing all paths from source to target. Then just filter out all paths without a node that has the desired condition, and choose the shortest path among this set of paths. Assuming you have an undirected and unweighted graph, something like this should work:

import networkx as nx

# Generate a sample graph:
G = nx.barabasi_albert_graph(10, 3, seed=42)
print(G.edges())

def check_attribute(G, node):
    # Say the condition is node id is 3:
    return node == 3

valid_paths = []
for path in nx.all_simple_paths(G, source=0, target=7):
    cond = False
    for node in path:
        if check_attribute(G, node):
            cond = True
            valid_paths.append(path)
            break

lengths = [len(path) for path in valid_paths]
shortest_path = valid_paths[lengths.index(min(lengths))]
print('valid paths: {}'.format(valid_paths))
print('shortest_path: {}'.format(shortest_path))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM