/
graph_info.py
executable file
·98 lines (83 loc) · 3.15 KB
/
graph_info.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/env python
from __future__ import print_function
import operator
import networkx as nx
import network
import utils
import community
from utils import timeit
import matplotlib.pyplot as plt
class GraphInfo(object):
def __init__(self, graph):
self.graph = graph
self.init()
@timeit
def _clustering(self):
return nx.average_clustering(self.graph)
@timeit
def _diameter(self):
shortest_path_dict_dict = nx.all_pairs_shortest_path_length(self.graph)
diameter = 0
for shortest_path_dict in shortest_path_dict_dict.values():
current_shortest = sorted(shortest_path_dict.values(), reverse=True)[0]
if diameter < current_shortest:
diameter = current_shortest
return diameter
def _connected_component(self):
if self.graph.is_directed():
edges_in_wcc = set()
nodes_in_wcc = set()
wcc_counter = 0
for wcc in nx.weakly_connected_components(self.graph):
wcc_counter += 1
print(type(wcc))
nodes_in_wcc.add(wcc.nodes())
edges_in_wcc.add(wcc.edges())
else: # undirected
scc_counter = 0
for scc in nx.strongly_connected_components(self.graph):
scc_counter += 0
print(type(scc))
def _triangles(self):
triangles_dict = nx.triangles(self.graph)
return sum([v for v in triangles_dict.values()])
@timeit
def _sorted_degrees(self, ego_set=None):
degree_dict = self.graph.degree()
sorted_degrees = sorted(degree_dict.items(), key=operator.itemgetter(1), reverse=True)
if ego_set is None:
return sorted_degrees
filtered = []
for e in sorted_degrees:
if e[0] in ego_set:
filtered.append(e)
return filtered
# noinspection PyAttributeOutsideInit
def init(self):
self.node_num = len(self.graph.nodes())
self.edge_num = len(self.graph.edges())
self.sorted_degree = self._sorted_degrees()
# noinspection PyAttributeOutsideInit
def dump_info(self):
# self.diameter = self._diameter()
self.clustering_efficient = self._clustering()
print('nodes: {}'.format(self.node_num))
print('edges: {}'.format(self.edge_num))
# print('diameter: {}'.format(self.diameter))
print('average clustering coefficient: {}'.format(self.clustering_efficient))
degrees = sum([d[1] for d in self.sorted_degree])
nodes = float(len(self.graph.nodes()))
print('average degrees: {}'.format(degrees / nodes))
def draw(self):
G = self.graph
part = community.best_partition(G)
values = [part.get(node) for node in G.nodes()]
nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.savefig('network.pdf')
if __name__ == '__main__':
name = 'facebook'
gzip_file = utils.get_gzip_fname(name)
s = network.Network.from_combined(name, gzip_file)
ego_set = utils.collect_ego_set(name)
g_info = GraphInfo(s.graph)
g_info.draw()