-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph.py
More file actions
164 lines (119 loc) · 4.21 KB
/
graph.py
File metadata and controls
164 lines (119 loc) · 4.21 KB
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
from __future__ import print_function, division
import numpy as np
import matplotlib.pyplot as plt
class Graph:
def __init__(self, nodes, xy=None, links=None):
self.N = len(nodes)
self.nodes = nodes
if xy is None:
xy = np.zeros((self.N, 2))
self.xy = xy
if links is None:
links = []
self.links = links
neighbors = []
for i in xrange(self.N):
n = [j[0] for j in links if j[1] == i] + [j[1] for j in links if j[0] == i]
neighbors.append(n)
self.neighbors = neighbors
def forcedirectedlayout(self):
converged, self.xy = FD(self)
def plot(self, fig=None, ax=None):
xy = self.xy[:, :]
xymax = np.max(xy, axis=0)
xymin = np.min(xy, axis=0)
# imin = [np.where(xy[:, i] == xymin[i])[0] for i in xrange[2]]
xy -= np.reshape(np.tile(.5 * (xymax + xymin), self.N), (self.N, 2))
xyscale = np.max((xymax - xymin) / 100)
show = False
if fig is None or ax is None:
show = True
fig, ax = plt.subplots(figsize=(4, 4))
for link in self.links:
ax.plot(xy[link[0:2], 0] / xyscale, xy[link[0:2], 1] / xyscale, 'b')
for i in xrange(self.N):
x, y = xy[i, 0:2] / xyscale
circle = plt.Circle((x, y), 3, color='#e5e5e5', zorder=10)
ax.add_artist(circle)
ax.text(x, y + 1, '{0}'.format(i), zorder=20, ha='center', va='center')
ax.set_xlim([-60, 60])
ax.set_ylim([-60, 60])
if show is True:
plt.show()
def FD(graph):
""" Force directed layout routine """
energy = 0
heat = 0.02
xy = 1 * np.random.rand(graph.N, 2)
vs = np.zeros((graph.N, 2))
settings = {'vmax': 1, 'friction': .2}
cnt = 0
converged = False
while not converged:
cnt += 1
if heat > 0:
if cnt == 20:
heat = .01
elif cnt == 40:
heat = .005
elif cnt == 80:
heat = 0
xy, vs, energy = FDstep(graph, xy, vs, energy, heat, settings)
if energy > 100 * graph.N:
break
# print(np.sum(np.abs(vs))/graph.N)
converged = np.sum(np.abs(vs)) / graph.N < 1e-3
if cnt > 500:
converged = True
print(cnt)
return converged, xy
def FDstep(graph, xy=None, vs=None, energy=0, heat=0.5, settings=None):
""" Force directed layout step"""
N = graph.N
if xy is None:
xy = np.random.rand(N, 2)
if vs is None:
vs = np.zeros((N, 2))
# xy += -np.reshape(np.tile(np.sum(xy, axis=0)/N, N), (N, 2))
nenergy = 0
rforce = np.zeros((N, 2)) # repelling force
aforce = np.zeros((N, 2)) # attractive force
for i in xrange(N):
for j in xrange(N):
if i == j:
continue
d = xy[i, :] - xy[j, :]
r = np.sqrt(np.sum(d ** 2))
rforce[i, :] += 0.001 * d / r ** 3 if r > 0.001 else .1 * (np.random.rand(2) - .5)
nenergy += 0.005 / max(r, 0.001) # new energy
for i in xrange(N):
for j in graph.neighbors[i]:
d = xy[i, :] - xy[j, :]
r = np.sqrt(np.sum(d ** 2))
aforce[i, :] += -2 * d / 100 if r > 0.001 else .1 * (np.random.rand(2) - .5)
nenergy += r ** 2 / 100
vs += (aforce + rforce)
# idx = np.where(np.abs(vs) > settings['vmax'])
# vs[idx] = settings['vmax']*np.sign(vs[idx])
vs -= settings['friction'] * vs
# idx = np.where(np.abs(vs) > settings['friction'])
# vs[idx] += -settings['friction']*np.sign(vs[idx])
if heat > 0:
vs += 2 * heat * (2 * np.random.rand(N, 2) - 1)
xy += vs
# if heat > 0:
# xy +=
xy += -np.reshape(np.tile(np.sum(xy, axis=0), N) / N, (N, 2))
# print(vs)
# graph.xy = xy
# graph.plot()
return xy, vs, nenergy
if __name__ == "__main__":
# This is a small demonstration of this graph library
# showing how to plot of a 7 site chain using
# force-directed layout.
nodes = [0] * 7
links = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0], [4, 6], [6, 5]]
g = Graph(nodes, None, links)
g.forcedirectedlayout()
g.plot()