當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python NetworkX gomory_hu_tree用法及代碼示例


本文簡要介紹 networkx.algorithms.flow.gomory_hu_tree 的用法。

用法:

gomory_hu_tree(G, capacity='capacity', flow_func=None)

返回無向圖 G 的 Gomory-Hu 樹。

具有容量的無向圖的 Gomory-Hu 樹是加權樹,它表示圖中所有 s-t 對的最小 s-t 割。

它隻需要 n-1 最小切割計算,而不是明顯的 n(n-1)/2 。該樹表示所有s-t割,因為任何一對節點之間的最小割值是Gomory-Hu樹中兩個節點之間的最短路徑中的最小邊權重。

Gomory-Hu 樹還具有這樣的特性,即在任意兩個節點之間的最短路徑中移除具有最小權重的邊會留下兩個連通分量,這些分量形成 G 中節點的劃分,定義了最小 s-t 割。

有關詳細信息,請參閱下麵的示例部分。

參數

GNetworkX 圖

無向圖

capacitystring

圖 G 的邊應該有一個屬性容量,表示邊可以支持多少流量。如果此屬性不存在,則認為邊具有無限容量。默認值:‘capacity’。

flow_func函數

執行底層流計算的函數。默認值 edmonds_karp() 。此函數在具有右尾度分布的稀疏圖中表現更好。 shortest_augmenting_path() 在更密集的圖中表現更好。

返回

TreeNetworkX 圖

NetworkX 圖表示輸入圖的 Gomory-Hu 樹。

拋出

NetworkXNotImplemented

如果輸入圖是有向的,則引發。

NetworkXError

如果輸入圖是空圖,則引發。

注意

該實現基於Gusfield方法[1]來計算Comory-Hu樹,該方法不需要節點收縮並且具有與原始方法相同的計算複雜度。

參考

1

Gusfield D: Very simple methods for all pairs network flow analysis. SIAM J Comput 19(1):143-155, 1990.

例子

>>> G = nx.karate_club_graph()
>>> nx.set_edge_attributes(G, 1, "capacity")
>>> T = nx.gomory_hu_tree(G)
>>> # The value of the minimum cut between any pair
... # of nodes in G is the minimum edge weight in the
... # shortest path between the two nodes in the
... # Gomory-Hu tree.
... def minimum_edge_weight_in_shortest_path(T, u, v):
...     path = nx.shortest_path(T, u, v, weight="weight")
...     return min((T[u][v]["weight"], (u, v)) for (u, v) in zip(path, path[1:]))
>>> u, v = 0, 33
>>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
>>> cut_value
10
>>> nx.minimum_cut_value(G, u, v)
10
>>> # The Comory-Hu tree also has the property that removing the
... # edge with the minimum weight in the shortest path between
... # any two nodes leaves two connected components that form
... # a partition of the nodes in G that defines the minimum s-t
... # cut.
... cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
>>> T.remove_edge(*edge)
>>> U, V = list(nx.connected_components(T))
>>> # Thus U and V form a partition that defines a minimum cut
... # between u and v in G. You can compute the edge cut set,
... # that is, the set of edges that if removed from G will
... # disconnect u from v in G, with this information:
... cutset = set()
>>> for x, nbrs in ((n, G[n]) for n in U):
...     cutset.update((x, y) for y in nbrs if y in V)
>>> # Because we have set the capacities of all edges to 1
... # the cutset contains ten edges
... len(cutset)
10
>>> # You can use any maximum flow algorithm for the underlying
... # flow computations using the argument flow_func
... from networkx.algorithms import flow
>>> T = nx.gomory_hu_tree(G, flow_func=flow.boykov_kolmogorov)
>>> cut_value, edge = minimum_edge_weight_in_shortest_path(T, u, v)
>>> cut_value
10
>>> nx.minimum_cut_value(G, u, v, flow_func=flow.boykov_kolmogorov)
10

相關用法


注:本文由純淨天空篩選整理自networkx.org大神的英文原創作品 networkx.algorithms.flow.gomory_hu_tree。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。