示例#1
0
def amr_subgraphs_optimized(g, n_min=1, n_max=None):  # g: AMRGraph object
    """ -> connected subgraphs whose number of nodes is >= n_min & <= n_max """
    output = defaultdict(list)
    # PROXY_AFP_ENG_20021112_0467.11 - a cyclic graph
    if not nx.is_directed_acyclic_graph(g):
        print('The input graph is not directed acyclic.')
        return output

    amr_root = list(g.successors('@'))[0]
    order = list(nx.dfs_preorder_nodes(g, amr_root))
    #    print(order)
    if not n_max:
        n_max = len(g.nodes())
    # assumption: n_min < n_max
    for i in range(n_min, n_max + 1):
        #        print(i)
        for n in order:
            #            pool = list(nx.dfs_preorder_nodes(g,'s',depth_limit=i-1))
            pool = set(y for v in nx.dfs_successors(g, n, depth_limit=i -
                                                    1).values() for y in v)
            #            print(n,pool)
            if len(pool) < i - 1:
                continue
            for ns in itertools.combinations(pool, i - 1):
                sg = g.subgraph((n, ) + ns).copy()
                if nx.is_connected(sg.to_undirected()):
                    amr_root = list(nx.topological_sort(sg))[0]
                    sg.add_edge('@', amr_root, label='')
                    sg = AMRGraph(sg)
                    sg.meta = '# connected subgraph of {} nodes'.format(i)
                    output[i].append(sg)
    return output
示例#2
0
def construct_amr_subgraph(g, nodes, root_node=None):
    """ Add dummy root node '@', apply AMRGraph type """
    if root_node:
        output = g.subgraph(nodes.union({root_node})).copy()
    else:
        output = g.subgraph(nodes).copy()
        # assumption: nx.is_directed_acyclic_graph(output)==True
        root_node = list(nx.topological_sort(output))[0]
    output.add_edge('@', root_node, label='')
    output = AMRGraph(output)
    output.meta = '# root node: {}'.format(root_node)
    return output
示例#3
0
def amr_subgraphs(g, num):  # g: AMRGraph object
    """ -> connected subgraphs with more than num nodes """
    output = defaultdict(list)
    # assumption: num < len(g.nodes())+1
    for i in range(num, len(g.nodes()) + 1):
        for nodes in itertools.combinations(g.nodes(), i):
            sg = g.subgraph(nodes).copy()
            if nx.is_connected(sg.to_undirected()) and '@' not in sg.nodes():
                amr_root = list(nx.topological_sort(sg))[0]
                sg.add_edge('@', amr_root, label='')
                sg = AMRGraph(sg)
                sg.meta = '# connected subgraph of {} nodes'.format(i)
                output[i].append(sg)
    return output