import networkx as nx
import numpy as np
def np_normalize_dict(input_dict):
"""
input_dict: {node_name: centrality_float}에서
value를 normalize하여 리턴.
"""
vs = np.array(list(input_dict.values()))
vs /= np.linalg.norm(vs)
return {k: v for k, v in zip(input_dict.keys(), vs)}
def custom_local_reaching_centraliyt(G, target_node):
"""
- local reaching centrality
- target_node에서 다른 모든 node까지의 거리에 대해서 역수를 취해서 합함.
harmonic centrality: 다른 모든 node v부터 target_node u 까지의 거리의 역수 합.
"""
path_ls = [1/nx.shortest_path_length(G, target_node, n) for n in G if target_node!=n]
return sum(path_ls)/(len(G)-1)
# Graph generation
G = nx.DiGraph()
G.add_edges_from([(0, 1), (1, 2)])
# harmonic centrality and normalization
nx_harmonic_cent = nx.harmonic_centrality(G)
nx_harmonic_cent = np_normalize_dict(nx_harmonic_cent)
# global reaching centrality and normalization
nx_node_reaching_centraliy = {n: nx.local_reaching_centrality(G, n) for n in G}
nx_node_reaching_centraliy = np_normalize_dict(nx_node_reaching_centraliy)
for n in G:
print(
f"{n:3d} ::: ",
round(nx_node_reaching_centraliy[n], 8),
round(nx_harmonic_cent[n], 8))
print("=="*20)
0 ::: 0.89442719 0.0
1 ::: 0.4472136 0.5547002
2 ::: 0.0 0.83205029
댓글남기기