-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvisualization.py
323 lines (296 loc) · 9.9 KB
/
visualization.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
Plot matrix based on JSON data written by FRANK library
usage: visualization.py [options]
options:
-h, --help Show help message.
--input=<JSON-file> Read input from the specified JSON file. This file
should be generated by FRANK::write_JSON.
[default: matrix.json]
--sv-tolerance=<float> Plot singular values that exceed a specified threshold
instead of generic patch representation
"""
from docopt import docopt
import sys
import json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gs
import matplotlib.patches as mpatch
yrblue = '#005396'
yrpink = '#cf006b'
yrgreen = '#539600'
plot_singular_values = False
tolerance = 1e-6
eps = 1e-16
def read_xml(in_file):
tree = ET.parse(in_file)
return tree
def plot_hierarchical(node, gs_node, color=False):
dim = [len(node['children']), len(node['children'][0])]
level = node['level']
shared_col_b = [
{
'exists':False, 'children':None,
'level':level+1, 'dim':dim[0],
'width': None
}
for i in range(dim[0])
]
shared_row_b = [
{
'exists':False, 'children':None,
'level':level+1, 'dim':dim[1],
'width': None
}
for j in range(dim[1])
]
gs_subgrid = gs.GridSpecFromSubplotSpec(
dim[0], dim[1], subplot_spec=gs_node
)
for i in range(dim[0]):
for j in range(dim[1]):
child = node['children'][i][j]
sub_type = child['type']
if sub_type == 'Hierarchical':
shared_col_b[i]['children'], shared_row_b[j]['children'] = (
plot_hierarchical(
child,
gs_subgrid[i, j],
# (level == 0 and [i, j] in [[0, 0], [0, 1]]) or color
)
)
elif sub_type == 'LowRank':
if plot_singular_values:
plot_lowrank(child, gs_subgrid[i, j])
else:
plot_lowrank_patches(
child, gs_subgrid[i, j], dim
# (level == 0 and [i, j] in [[0, 0], [0, 1]]) or (color and i >= j)
)
elif sub_type == 'LowRankShared':
width = plot_lowrank_shared_patches(
child, gs_subgrid[i, j], dim
# (level == 0 and [i, j] in [[0, 0], [0, 1]]) or (color and i >= j)
)
shared_col_b[i]['exists'] = True
shared_col_b[j]['width'] = width
shared_row_b[j]['exists'] = True
shared_row_b[i]['width'] = width
elif sub_type == 'Dense':
if plot_singular_values:
plot_dense(child, gs_subgrid[i, j])
else:
plot_dense_patch(
child, gs_subgrid[i, j]
# (level == 0 and [i, j] in [[0, 0], [0, 1]]) or (color and i >= j),
# 'lower'
)
return shared_col_b, shared_row_b
def plot_lowrank(node, gs_node):
dim = node['dim']
svalues = [x+eps for x in node['svalues']]
count = 0
for sv in svalues:
if sv > tolerance:
count += 1
slog = np.log10(svalues[0:count])
ax = plt.subplot(gs_node)
ax.text(0.5*count, 0.5, f"{count}", {'fontsize': 'x-small'})
# ax.text(
# 0.5, 0.5,
# "{}\n({}, {})".format(
# node['level'], node['abs_pos'][0], node['abs_pos'][1]
# ),
# horizontalalignment='center', verticalalignment='center'
# )
ylow = int(np.log10(tolerance))
ax.set(
xlim=(-0.5, len(slog)+0.5),
ylim=(0, -(ylow-2)),
xticks=[], yticks=[]
)
ax.bar(np.arange(len(slog)), slog-ylow, width=1, color=yrpink)
def plot_lowrank_patches(node, gs_node, dim, has_color=True):
level = node['level']
ax = plt.subplot(gs_node)
ax.set(xticks=[], yticks=[])
dist = 0.0075*2**(level*np.sqrt(dim[0]/2)-int(level/4))
k = (1.0 - 3*dist)/40*2**(level*np.sqrt(dim[0]/2)-int(level/4))
n = (1.0 - 3*dist-k)
color = yrpink if has_color else "grey"
U = mpatch.Rectangle(
(dist, dist),
k, n,
edgecolor='none',
facecolor=color
)
S = mpatch.Rectangle(
(dist, 2*dist+n),
k, k,
edgecolor='none',
facecolor=color
)
V = mpatch.Rectangle(
(2*dist+k, 2*dist+n),
n, k,
edgecolor='none',
facecolor=color
)
# Add the patch to the Axes
ax.add_patch(U)
ax.add_patch(S)
ax.add_patch(V)
def plot_lowrank_shared_patches(node, gs_node, dim, has_color=True):
level = node['level']
ax = plt.subplot(gs_node)
ax.set(xticks=[], yticks=[])
dist = 0.0075*2**(level*np.sqrt(dim[0]/2)-int(level/4))
k = (1.0 - 3*dist)/40*2**(level*np.sqrt(dim[0]/2)-int(level/4))
n = (1.0 - 3*dist-k)
color = yrpink if has_color else "grey"
S = mpatch.Rectangle(
(dist, 2*dist+n),
k, k,
edgecolor='none',
facecolor=color
)
# Add the patch to the Axes
ax.add_patch(S)
return k
def plot_dense(node, gs_node):
dim = node['dim']
svalues = [x+eps for x in node['svalues']]
count = 0
for sv in svalues:
if sv > tolerance:
count += 1
slog = np.log10(svalues[0:count])
ax = plt.subplot(gs_node)
ax.text(0.5*count, 0.5, f"{count}", {'fontsize': 'x-small'})
# ax.text(
# 0.5, 0.5,
# "{}\n({}, {})".format(
# node['level'], node['abs_pos'][0], node['abs_pos'][1]
# ),
# horizontalalignment='center', verticalalignment='center'
# )
ylow = int(np.log10(tolerance))
ax.set(
xlim=(-0.5, len(slog)+0.5),
ylim=(0, -(ylow-2)),
xticks=[], yticks=[]
)
ax.bar(np.arange(len(slog)), slog-ylow, width=1, color=yrblue)
def plot_dense_patch(node, gs_node, has_color=True, ul=None):
ax = plt.subplot(gs_node)
ax.set(xticks=[], yticks=[])
color = yrblue if has_color else "grey"
if ul is None or not has_color:
patch = mpatch.Rectangle(
(0.0, 0.0),
1.0, 1.0,
edgecolor='none',
facecolor=color
)
# Add the patch to the Axes
ax.add_patch(patch)
else:
upper = mpatch.Polygon(
[[0.0, 1.0], [1.0, 1.0], [1.0, 0.0]],
edgecolor='none',
facecolor=color if ul == 'upper' else 'grey'
)
ax.add_patch(upper)
lower = mpatch.Polygon(
[[0.0, 1.0], [0.0, 0.0], [1.0, 0.0]],
edgecolor='none',
facecolor=color if ul == 'lower' else 'grey'
)
ax.add_patch(lower)
def plot_shared_basis(shared_basis, gs_root, transpose, width_factor):
gs_split = gs.GridSpecFromSubplotSpec(
1 if transpose else len(shared_basis),
len(shared_basis) if transpose else 1,
subplot_spec=gs_root
)
child_depths = [0]
for i, basis in enumerate(shared_basis):
gs_own, gs_children = None, None
if not basis['exists'] and basis['children'] is None:
continue
if basis['exists'] and basis['children'] is None:
gs_own = gs_split[i]
gs_children = None
elif not basis['exists'] and basis['children'] is not None:
gs_own = None
gs_children = gs_split[i]
elif basis['exists'] and basis['children'] is not None:
gs_own, gs_children = gs.GridSpecFromSubplotSpec(
2 if transpose else 1,
1 if transpose else 2,
subplot_spec=gs_split[i]
)
else:
print(basis['exists'], basis['children'])
raise ValueError
depth = 0
if gs_children is not None:
depth += plot_shared_basis(
basis['children'], gs_children, transpose, width_factor
)
if gs_own is not None:
if transpose:
gs_split[i].set_height_ratios(1, depth)
else:
gs_split[i].set_width_ratios(1, depth)
if gs_own is not None:
depth += 1
ax = plt.subplot(gs_own)
ax.axis('off')
level = basis['level']
dim = basis['dim']
width = basis['width']*width_factor/dim
base = mpatch.Rectangle(
(
0.05 if transpose else 0.5-width/2,
0.5-width/2 if transpose else 0.05
),
0.9 if transpose else width, width if transpose else 0.9,
edgecolor='none',
facecolor=yrpink
)
ax.add_patch(base)
child_depths.append(depth)
return max(child_depths)
def main():
args = docopt(__doc__)
in_path = args["--input"]
with open(in_path) as in_file:
root = json.load(in_file)
if(args["--sv-tolerance"]):
global tolerance
tolerance = float(args['--sv-tolerance'])
global plot_singular_values
plot_singular_values = True
fig = plt.figure(figsize=(5, 5), dpi=200)
grid = fig.add_gridspec(2, 2)
shared_col_b, shared_row_b = plot_hierarchical(
root,
grid[1, 1]
)
width_factor = 20
col_basis_width = plot_shared_basis(
shared_col_b, grid[1, 0], False, width_factor
)
grid.set_width_ratios([col_basis_width, width_factor])
row_basis_height = plot_shared_basis(
shared_row_b, grid[0, 1], True, width_factor
)
grid.set_height_ratios([row_basis_height, width_factor])
# TODO change figure size if width of bases varies (.set_size_inches)
plt.tight_layout()
plt.subplots_adjust(wspace=0, hspace=0)
plt.savefig(in_path.split('.')[0] + ".pdf")
# plt.show()
if __name__ == '__main__':
main()