简体   繁体   English

如何在 Graph Networkx 中找到具有公共节点的边?

[英]How to find edges with common nodes in Graph Networkx?

I have this graph:我有这个图:

G = nx.MultiGraph()

source_nodes = ['A', 'A', 'B', 'D']
target_nodes = ['B', 'C', 'D', 'E']

for u,v in zip(source_nodes, target_nodes):
    G.add_edge(u, v)

and the edges I get are:我得到的边缘是:

(A, B)
(A, C)
(B, D)
(D, E)

if the target node of an edge is the source node from another edge, I would like to create an edge between them.如果一条边的目标节点是另一条边的源节点,我想在它们之间创建一条边。 For instance, for the above example the new edges will be:例如,对于上面的示例,新边将是:

(A, D) and (A, E) . (A, D)(A, E)

I'm new in Networkx and I'm not sure how to do that...我是 Networkx 的新手,我不知道该怎么做...

  1. Firstly, you use MultiGraph .首先,您使用MultiGraph It is not directed and doesn't store info about sources and targets (they become equal connected nodes).它不是定向的,也不存储有关源和目标的信息(它们成为相等的连接节点)。 You should use DiGraphs or MultiDiGraphs to store info in a directed graph.您应该使用DiGraphsMultiDiGraphs在有向图中存储信息。

  2. NetworkX DiGraphs and MultiDiGraphs has functions predecessors and successors , that can be applied to a particular node. NetworkX DiGraphs 和 MultiDiGraphs 具有predecessorssuccessors 功能,可以应用于特定节点。 You can use them to check if an edge from predecessor to successor exists, and if not, create it.您可以使用它们来检查从前任到后继的边是否存在,如果不存在,则创建它。

import networkx as nx

G = nx.DiGraph()  # Not a MultiGraph! (can be MultiDiGraph)

source_nodes = ['A', 'A', 'B', 'D']
target_nodes = ['B', 'C', 'D', 'E']

for u,v in zip(source_nodes, target_nodes):
    G.add_edge(u, v)

# For each node
for n in G.nodes:
    # We check all predecessors and successors
    for p in G.predecessors(n):
        for s in G.successors(n):
            # If graph has no edge from predecessor to successor
            if (p, s) not in G.edges:
                print(p, s)  # Print, can be removed
                # We add this node
                G.add_edge(p, s)

If you want to create edges not for all nodes, but for a set of nodes, you can replace G.nodes: in the line for n in G.nodes: with a given set of nodes, like:如果您不想为所有节点创建边,而是为一组节点创建边,则可以将G.nodes:G.nodes:for n in G.nodes:为给定的一组节点,例如:

for n in [1, 2, 3]:

If you want to create edges only for one node, you don't need the main loop:如果只想为一个节点创建边,则不需要主循环:

NODE_ID = 2

# We check all predecessors and successors of a node
for p in G.predecessors(NODE_ID):
    for s in G.successors(NODE_ID):
        # If graph has no edge from predecessor to successor
        if (p, s) not in G.edges:
            print(p, s)  # Print, can be removed
            # We add this node
            G.add_edge(p, s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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