递归地将子图添加到图中的所有节点

时间:2017-11-01 15:39:32

标签: python recursion data-structures graph tree

所以,我的图形数据结构如下:

graph = {'graphData': {'nodes': List of Nodes,
                       'edges': List of Edges,}
         }

除此之外,我还有一个子图列表如下:

Subgraphs

在第一步中,我将那些具有一个节点的子图作为SOI [注释3下的3]添加到一起形成如下:

SOI Subgraphs

以下代码负责:

    for coreferanceGraph in unattached_graphs:
        coreferanceGraph = self.merge_entity_in_graph(soi_node, coreferanceGraph, "value-entityName")

        if coreferanceGraph:
            edges_in_coreferenceGraph = coreferanceGraph['graphData']['edges']
            nodes_in_coreferenceGraph = coreferanceGraph['graphData']['nodes']

            for node in nodes_in_coreferenceGraph:
                if node not in graph['graphData']['nodes']:
                    graph['graphData']['nodes'].append(node)

            for edge in edges_in_coreferenceGraph:
                if edge not in graph['graphData']['edges']:
                    graph['graphData']['edges'].append(edge)

            attached_graphs.append(coreferanceGraph)

        else:
            continue

以上代码中发生的情况是: 对于第一个图像中的每个未附加的子图,我使用函数 merge_entity_in_graph()查找是否有任何子图具有SOI节点。如果子图中存在SOI,则返回子图,并将其添加到由变量 graph = dict()定义的结构定义的原始Graph变量。

在下一步中,我想以递归方式添加图像1中的所有这些sugraph,以添加到存在的开放节点。在我的例子中,根据图2,那是Ec,Ep,E1。

我的期望是:

enter image description here

如果有更多的子图,其中一个节点为 Ef,Eq,Er ,它们也会以递归方式添加。

我的问题是,我该如何实现这一目标?我写了一个方法如下,但不确定天气方法是否正确:

def add_other_subgraphs(self, subgraph, node, all_nodes, graph, coreference_graphs):
    """

    Args:
        subgraph (dict):
        node (dict):
        all_nodes (list):
        graph (dict):

    Returns:

    """

    subgraph_edges = subgraph['graphData']['edges']
    subgraph_nodes = subgraph['graphData']['nodes']

    for node in subgraph_nodes:
        if node not in graph['graphData']['nodes']:
            graph['graphData']['nodes'].append(node)

    for edge in subgraph_edges:
        if edge not in graph['graphData']['edges']:
            graph['graphData']['edges'].append(edge)

    for node in graph['graphData']['nodes']:
        coreference_graph = self.fetch_coreference_graph(node, coreference_graphs)
        if coreference_graph:
            graph = self.add_other_subgraphs(coreference_graph, node, all_nodes, graph, coreference_graphs)
        else:
            return graph

    return graph

将为每个节点调用 add_other_subgraphs()函数,即 Ec,Ep,E1

0 个答案:

没有答案