使用Python networkx从无向多图中删除循环

时间:2016-04-13 17:04:00

标签: python graph networkx

所以我有一个无向多图(从本体派生),我希望删除创建周期的边(但不是所有边,多图的成分必须保持连接)。使用networkx包有没有一种好方法?

2 个答案:

答案 0 :(得分:1)

可能没有一种独特的方法可以为您的图表执行此操作。但也许找到一棵生成树会解决你的问题? https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.mst.minimum_spanning_tree.html

答案 1 :(得分:0)

所以我最终得到了

def as_spanning_trees(G):
    """
    For a given graph with multiple sub graphs, find the components
    and draw a spanning tree.

    Returns a new Graph with components as spanning trees (i.e. without cycles).

    Parameters
    ---------
    G:        - networkx.Graph
    """

    G2 = nx.Graph()
    # We find the connected constituents of the graph as subgraphs
    graphs = nx.connected_component_subgraphs(G, copy=False)

    # For each of these graphs we extract the spanning tree, removing the cycles
    for g in graphs:
        T = nx.minimum_spanning_tree(g)
        G2.add_edges_from(T.edges())
        G2.add_nodes_from(T.nodes())

    return G2