首页
学习
活动
专区
圈层
工具
发布

图归约
EN

Stack Overflow用户
提问于 2018-09-13 20:14:41
回答 1查看 1.4K关注 0票数 6

我一直在编写一段代码来简化图形。问题是有一些我想要删除的分支。一旦我删除了一个分支,我就可以合并或不合并节点,这取决于分支加入的节点之间的路径数量。

也许下面的例子说明了我想要什么:

我拥有的代码如下:

代码语言:javascript
复制
from networkx import DiGraph, all_simple_paths, draw
from matplotlib import pyplot as plt

# data preparation
branches = [(2, 1),
            (3, 2),
            (4, 3),
            (4, 13),
            (7, 6),
            (6, 5),
            (5, 4),
            (8, 7),
            (9, 8),
            (9, 10),
            (10, 11),
            (11, 12),
            (12, 1),
            (13, 9)]

branches_to_remove_idx = [11, 10, 9, 8, 6, 5, 3, 2, 0]
ft_dict = dict()
graph = DiGraph()

for i, br in enumerate(branches):
    graph.add_edge(br[0], br[1])
    ft_dict[i] = (br[0], br[1])

# Processing -----------------------------------------------------
for idx in branches_to_remove_idx:

    # get the nodes that define the edge to remove
    f, t = ft_dict[idx]

    # get the number of paths from 'f' to 't'
    n_paths = len(list(all_simple_paths(graph, f, t)))

    if n_paths == 1:
        # remove branch and merge the nodes 'f' and 't'
        #
        #       This is what I have no clue how to do
        #
        pass

    else:
        # remove the branch and that's it
        graph.remove_edge(f, t)
        print('Simple removal of', f, t)

# -----------------------------------------------------------------

draw(graph, with_labels=True)
plt.show()

我觉得应该有一种更简单的直接方法从第一个数字中获得最后一个数字,给出分支指数,但我不知道。

EN

回答 1

Stack Overflow用户

发布于 2018-09-14 17:43:34

我想这或多或少就是你想要的。我正在将链中的所有节点(连接的次数为2的节点)合并为一个超节点。我返回新的图和一个将超级节点映射到收缩节点的字典。

代码语言:javascript
复制
import networkx as nx

def contract(g):
    """
    Contract chains of neighbouring vertices with degree 2 into one hypernode.

    Arguments:
    ----------
    g -- networkx.Graph instance

    Returns:
    --------
    h -- networkx.Graph instance
        the contracted graph

    hypernode_to_nodes -- dict: int hypernode -> [v1, v2, ..., vn]
        dictionary mapping hypernodes to nodes

    """

    # create subgraph of all nodes with degree 2
    is_chain = [node for node, degree in g.degree_iter() if degree == 2]
    chains = g.subgraph(is_chain)

    # contract connected components (which should be chains of variable length) into single node
    components = list(nx.components.connected_component_subgraphs(chains))
    hypernode = max(g.nodes()) +1
    hypernodes = []
    hyperedges = []
    hypernode_to_nodes = dict()
    false_alarms = []
    for component in components:
        if component.number_of_nodes() > 1:

            hypernodes.append(hypernode)
            vs = [node for node in component.nodes()]
            hypernode_to_nodes[hypernode] = vs

            # create new edges from the neighbours of the chain ends to the hypernode
            component_edges = [e for e in component.edges()]
            for v, w in [e for e in g.edges(vs) if not ((e in component_edges) or (e[::-1] in component_edges))]:
                if v in component:
                    hyperedges.append([hypernode, w])
                else:
                    hyperedges.append([v, hypernode])

            hypernode += 1

        else: # nothing to collapse as there is only a single node in component:
            false_alarms.extend([node for node in component.nodes()])

    # initialise new graph with all other nodes
    not_chain = [node for node in g.nodes() if not node in is_chain]
    h = g.subgraph(not_chain + false_alarms)
    h.add_nodes_from(hypernodes)
    h.add_edges_from(hyperedges)

    return h, hypernode_to_nodes


edges = [(2, 1),
         (3, 2),
         (4, 3),
         (4, 13),
         (7, 6),
         (6, 5),
         (5, 4),
         (8, 7),
         (9, 8),
         (9, 10),
         (10, 11),
         (11, 12),
         (12, 1),
         (13, 9)]

g = nx.Graph(edges)

h, hypernode_to_nodes = contract(g)

print("Edges in contracted graph:")
print(h.edges())
print('')
print("Hypernodes:")
for hypernode, nodes in hypernode_to_nodes.items():
    print("{} : {}".format(hypernode, nodes))

这将为您的示例返回:

代码语言:javascript
复制
Edges in contracted graph:
[(9, 13), (9, 14), (9, 15), (4, 13), (4, 14), (4, 15)]

Hypernodes:
14 : [1, 2, 3, 10, 11, 12]
15 : [8, 5, 6, 7]
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52313551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档