-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathlocal_graph.py
204 lines (135 loc) · 5.1 KB
/
local_graph.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# -*- coding: utf-8 -*-
import random
import cPickle as pickle
import subprocess
import networkx as nx
from renren import FriendsStore, RenRenRelationShip
RENREN_FILE = 'renren_data'
def _dump(data):
with open(RENREN_FILE, 'w') as f:
pickle.dump(data, f, 2)
def _load():
try:
with open(RENREN_FILE, 'r') as f:
return pickle.load(f)
except IOError:
from utils import get_accounts
r = RenRenRelationShip(*get_accounts())
print 'collect friends'
data = r.collect_friends(level=2)
_dump(data)
return data
class GraphAnalysis(object):
def __init__(self):
self.G = nx.Graph()
self.min_node_size = 5
self.max_node_size = 10
def import_data(self, fs_list, min_keep=20):
for fs in fs_list:
self.G.add_node(fs.uid, lv=fs.level)
if fs.friends:
edges = [(fs.uid, u) for u in fs.friends]
self.G.add_edges_from(edges)
# 删掉level 2点,否则最后生成的图片点重叠在一起,看不清
for n in self.G.nodes():
if self.G.node[n]['lv'] == 2:
self.G.remove_node(n)
self.clear_nodes()
self.degree = nx.degree(self.G)
self.max_degree_value = max(self.degree.values())
self.max_degree_value_floated = float(self.max_degree_value)
def _clear_nodes(self):
need_clear = False
for n in self.G.nodes():
if self.G.degree(n) < 2:
self.G.remove_node(n)
need_clear = True
return need_clear
def clear_nodes(self):
while self._clear_nodes():
pass
def one_node_size(self, n):
d = self.degree[n]
d = d / self.max_degree_value_floated * self.max_node_size
if d < self.min_node_size:
d = self.min_node_size
return d
def get_node_size(self, nodes):
return [self.one_node_size(n) for n in nodes]
def one_node_color(self, n):
d = self.degree[n]
if d > self.max_degree_value / 2:
_range = [0.5, 0.8]
else:
_range = [0.8, 1.0]
_make = lambda: random.uniform(*_range)
_love = _make
_ohyes = _make
return (_make(), _love(), _ohyes())
def get_node_color(self, nodes):
return [self.one_node_color(n) for n in nodes]
def save(self, f='result.png', it=55):
import matplotlib.pyplot as plt
pos = nx.spring_layout(self.G, iterations=it)
nx.draw_networkx_edges(self.G, pos, alpha=0.1)
nx.draw_networkx_nodes(
self.G,
pos,
node_size = self.get_node_size(self.G.nodes()),
node_color = self.get_node_color(self.G.nodes()),
alpha = 0.8,
)
plt.axis('off')
plt.savefig(f, dpi=200)
plt.clf()
class DrawGraphviz(GraphAnalysis):
COLORS = [
'#F20010', '#FC4292', '#B94C4A', '#D19D39', '#A79D0F', '#A65FCC',
'#9470E7', '#19CD1D', '#1DDF9A', '#52A79F', '#24B5D9', '#2080DC',
]
def __init__(self):
super(DrawGraphviz, self).__init__()
self.min_node_size = 0.05
self.max_node_size = 0.2
def one_node_color(self, n):
d = self.degree[n]
for index, color in enumerate(self.COLORS):
if d * (index+1) >= self.max_degree_value:
return color
return color
def save(self, f='result.png'):
node_attr_template = {
'sharp': "point",
'color': "",
'style': "filled",
'width': 0.1,
'height': 0.1,
'fixedsize': "true",
'label': "",
}
for n in self.G.nodes():
attr = node_attr_template.copy()
attr['width'] = self.one_node_size(n)
attr['height'] = attr['width']
attr['color'] = self.one_node_color(n)
self.G.node[n] = attr
edges = self.G.edge[n]
for ed in edges:
self.G.edge[n][ed] = {'color': '{0}22'.format(attr['color'])}
DOT_FILE = '_renren.dot'
nx.write_dot(self.G, DOT_FILE)
pipe = subprocess.PIPE
graphviz_command = ['dot']
graphviz_command.append(DOT_FILE)
graphviz_command.extend(['-Tpng', '-Kneato', '-o'])
graphviz_command.append(f)
p = subprocess.Popen(graphviz_command, stdin=pipe, stdout=pipe, stderr=pipe)
ret_code = p.wait()
if ret_code !=0 :
_, ret_error_msg = p.communicate()
raise Exception(ret_error_msg)
if __name__ == '__main__':
data = _load()
g = DrawGraphviz()
g.import_data(data)
g.save()