import networkx as nx
from networkx.algorithms.approximation import connectivity
import time
N = 40 # node size
p = 0.6 # edge proportion of Complete graph
G = nx.fast_gnp_random_graph(N, p, seed=0)
print("=="*30)
print(f"Node size: {N}, Edge size: {len(G.edges())}")
print("--" * 30)
print("== Start")
start_time = time.time()
MIN_global_node_connectivity = len(G)
WRONG_connectivity_count = 0
# G:nx.Graph 의 모든 node pair들의 local connnectivity를 approximation한다.
for n1, d1 in connectivity.all_pairs_node_connectivity(G).items():
for n2, approx_c in d1.items():
if MIN_global_node_connectivity>=approx_c:
MIN_global_node_connectivity = approx_c
# `local_node_connectivity`는 특정 source, target에 대해서만 계산해주는 함수
# 장난 삼아 assert를 넣기는 했지만, 틀릴 리가 없다.
assert approx_c == connectivity.local_node_connectivity(G, n1, n2)
# 앞서 말한 것과 같이, local_node_connectivity는 두 노드간의 disjoint_path의 수와 동일해야 한다.
disjoint_paths = nx.algorithms.connectivity.node_disjoint_paths(G, n1, n2)
disjoint_path_count = 0
for _ in disjoint_paths:
disjoint_path_count+=1
# `disjoint_path_count`가 정확한 node connectivity이므로 출력함.
if approx_c!=disjoint_path_count:# Wrong
print(
f"WRONG - {n1:3d} => {n2:3d} - approx: {approx_c:3d} - disjoint_path_count: {disjoint_path_count:3d}"
)
WRONG_connectivity_count+=1
# graph의 node connectivity와 all_pairs_node_connectivity의 최소값은 당연히 같아야 함.
assert connectivity.node_connectivity(G) == MIN_global_node_connectivity
print("--" * 30)
print(f"Accuracy: {1-WRONG_connectivity_count/(N*(N-1)):%}")
print(f"== complete with comp. time: {time.time()-start_time:6.2f} sec")
print("==" * 30)
============================================================
Node size: 40, Edge size: 456
------------------------------------------------------------
== Start
WRONG - 7 => 14 - approx: 21 - disjoint_path_count: 22
WRONG - 14 => 7 - approx: 21 - disjoint_path_count: 22
------------------------------------------------------------
Accuracy: 99.871795%
== complete with comp. time: 20.81 sec
============================================================
댓글남기기