viz.py 17.1 KB
Newer Older
Zihao Ye's avatar
Zihao Ye committed
1
import os
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
2

Zihao Ye's avatar
Zihao Ye committed
3
4
import matplotlib as mpl
import matplotlib.animation as animation
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
5
6
7
8
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import torch as th
Zihao Ye's avatar
Zihao Ye committed
9
10
from networkx.algorithms import bipartite

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
11

Zihao Ye's avatar
Zihao Ye committed
12
13
14
15
16
17
18
19
20
21
def get_attention_map(g, src_nodes, dst_nodes, h):
    """
    To visualize the attention score between two set of nodes.
    """
    n, m = len(src_nodes), len(dst_nodes)
    weight = th.zeros(n, m, h).fill_(-1e8)
    for i, src in enumerate(src_nodes.tolist()):
        for j, dst in enumerate(dst_nodes.tolist()):
            if not g.has_edge_between(src, dst):
                continue
22
            eid = g.edge_ids(src, dst)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
23
            weight[i][j] = g.edata["score"][eid].squeeze(-1).cpu().detach()
Zihao Ye's avatar
Zihao Ye committed
24
25
26
27
28

    weight = weight.transpose(0, 2)
    att = th.softmax(weight, -2)
    return att.numpy()

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
29

Zihao Ye's avatar
Zihao Ye committed
30
def draw_heatmap(array, input_seq, output_seq, dirname, name):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
31
    dirname = os.path.join("log", dirname)
Zihao Ye's avatar
Zihao Ye committed
32
33
34
35
36
37
38
39
40
41
42
43
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    fig, axes = plt.subplots(2, 4)
    cnt = 0
    for i in range(2):
        for j in range(4):
            axes[i, j].imshow(array[cnt].transpose(-1, -2))
            axes[i, j].set_yticks(np.arange(len(input_seq)))
            axes[i, j].set_xticks(np.arange(len(output_seq)))
            axes[i, j].set_yticklabels(input_seq, fontsize=4)
            axes[i, j].set_xticklabels(output_seq, fontsize=4)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
44
45
46
47
48
49
50
            axes[i, j].set_title("head_{}".format(cnt), fontsize=10)
            plt.setp(
                axes[i, j].get_xticklabels(),
                rotation=45,
                ha="right",
                rotation_mode="anchor",
            )
Zihao Ye's avatar
Zihao Ye committed
51
52
53
54
            cnt += 1

    fig.suptitle(name, fontsize=12)
    plt.tight_layout()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
55
    plt.savefig(os.path.join(dirname, "{}.pdf".format(name)))
Zihao Ye's avatar
Zihao Ye committed
56
57
    plt.close()

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
58

Zihao Ye's avatar
Zihao Ye committed
59
def draw_atts(maps, src, tgt, dirname, prefix):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
60
    """
Zihao Ye's avatar
Zihao Ye committed
61
62
63
    maps[0]: encoder self-attention
    maps[1]: encoder-decoder attention
    maps[2]: decoder self-attention
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
64
65
66
67
68
    """
    draw_heatmap(maps[0], src, src, dirname, "{}_enc_self_attn".format(prefix))
    draw_heatmap(maps[1], src, tgt, dirname, "{}_enc_dec_attn".format(prefix))
    draw_heatmap(maps[2], tgt, tgt, dirname, "{}_dec_self_attn".format(prefix))

Zihao Ye's avatar
Zihao Ye committed
69

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
70
mode2id = {"e2e": 0, "e2d": 1, "d2d": 2}
Zihao Ye's avatar
Zihao Ye committed
71
72
73

colorbar = None

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
74

Zihao Ye's avatar
Zihao Ye committed
75
76
77
78
79
80
81
82
83
def att_animation(maps_array, mode, src, tgt, head_id):
    weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
    fig, axes = plt.subplots(1, 2)

    def weight_animate(i):
        global colorbar
        if colorbar:
            colorbar.remove()
        plt.cla()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
84
        axes[0].set_title("heatmap")
Zihao Ye's avatar
Zihao Ye committed
85
86
87
88
        axes[0].set_yticks(np.arange(len(src)))
        axes[0].set_xticks(np.arange(len(tgt)))
        axes[0].set_yticklabels(src)
        axes[0].set_xticklabels(tgt)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
89
90
91
92
93
94
95
96
        plt.setp(
            axes[0].get_xticklabels(),
            rotation=45,
            ha="right",
            rotation_mode="anchor",
        )

        fig.suptitle("epoch {}".format(i))
Zihao Ye's avatar
Zihao Ye committed
97
98
99
        weight = weights[i].transpose(-1, -2)
        heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
        colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
100
        axes[0].set_aspect("equal")
Zihao Ye's avatar
Zihao Ye committed
101
        axes[1].axis("off")
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
102
103
104
105
106
107
108
109
110
        graph_att_head(src, tgt, weight, axes[1], "graph")

    ani = animation.FuncAnimation(
        fig,
        weight_animate,
        frames=len(weights),
        interval=500,
        repeat_delay=2000,
    )
Zihao Ye's avatar
Zihao Ye committed
111
112
    return ani

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
113

Zihao Ye's avatar
Zihao Ye committed
114
115
def graph_att_head(M, N, weight, ax, title):
    "credit: Jinjing Zhou"
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
116
117
    in_nodes = len(M)
    out_nodes = len(N)
Zihao Ye's avatar
Zihao Ye committed
118

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
119
    g = nx.bipartite.generators.complete_bipartite_graph(in_nodes, out_nodes)
Zihao Ye's avatar
Zihao Ye committed
120
121
    X, Y = bipartite.sets(g)
    height_in = 10
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
122
    height_out = height_in
Zihao Ye's avatar
Zihao Ye committed
123
    height_in_y = np.linspace(0, height_in, in_nodes)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
124
125
126
    height_out_y = np.linspace(
        (height_in - height_out) / 2, height_out, out_nodes
    )
Zihao Ye's avatar
Zihao Ye committed
127
    pos = dict()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
128
129
130
131
132
133
134
135
    pos.update(
        (n, (1, i)) for i, n in zip(height_in_y, X)
    )  # put nodes from X at x=1
    pos.update(
        (n, (3, i)) for i, n in zip(height_out_y, Y)
    )  # put nodes from Y at x=2
    ax.axis("off")
    ax.set_xlim(-1, 4)
Zihao Ye's avatar
Zihao Ye committed
136
    ax.set_title(title)
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
137
138
139
140
141
142
143
144
145
146
147
    nx.draw_networkx_nodes(
        g, pos, nodelist=range(in_nodes), node_color="r", node_size=50, ax=ax
    )
    nx.draw_networkx_nodes(
        g,
        pos,
        nodelist=range(in_nodes, in_nodes + out_nodes),
        node_color="b",
        node_size=50,
        ax=ax,
    )
Zihao Ye's avatar
Zihao Ye committed
148
    for edge in g.edges():
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
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
        nx.draw_networkx_edges(
            g,
            pos,
            edgelist=[edge],
            width=weight[edge[0], edge[1] - in_nodes] * 1.5,
            ax=ax,
        )
    nx.draw_networkx_labels(
        g,
        pos,
        {i: label + "  " for i, label in enumerate(M)},
        horizontalalignment="right",
        font_size=8,
        ax=ax,
    )
    nx.draw_networkx_labels(
        g,
        pos,
        {i + in_nodes: "  " + label for i, label in enumerate(N)},
        horizontalalignment="left",
        font_size=8,
        ax=ax,
    )


Zihao Ye's avatar
Zihao Ye committed
174
import networkx as nx
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
175
from matplotlib.patches import ConnectionStyle, FancyArrowPatch
Zihao Ye's avatar
Zihao Ye committed
176
from networkx.utils import is_string_like
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
177

Zihao Ye's avatar
Zihao Ye committed
178
"The following function was modified from the source code of networkx"
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202


def draw_networkx_edges(
    G,
    pos,
    edgelist=None,
    width=1.0,
    edge_color="k",
    style="solid",
    alpha=1.0,
    arrowstyle="-|>",
    arrowsize=10,
    edge_cmap=None,
    edge_vmin=None,
    edge_vmax=None,
    ax=None,
    arrows=True,
    label=None,
    node_size=300,
    nodelist=None,
    node_shape="o",
    connectionstyle="arc3",
    **kwds
):
Zihao Ye's avatar
Zihao Ye committed
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
    """Draw the edges of the graph G.

    This draws only the edges of the graph G.

    Parameters
    ----------
    G : graph
       A networkx graph

    pos : dictionary
       A dictionary with nodes as keys and positions as values.
       Positions should be sequences of length 2.

    edgelist : collection of edge tuples
       Draw only specified edges(default=G.edges())

    width : float, or array of floats
       Line width of edges (default=1.0)

    edge_color : color string, or array of floats
       Edge color. Can be a single color format string (default='r'),
       or a sequence of colors with the same length as edgelist.
       If numeric values are specified they will be mapped to
       colors using the edge_cmap and edge_vmin,edge_vmax parameters.

    style : string
       Edge line style (default='solid') (solid|dashed|dotted,dashdot)

    alpha : float
       The edge transparency (default=1.0)

    edge_ cmap : Matplotlib colormap
       Colormap for mapping intensities of edges (default=None)

    edge_vmin,edge_vmax : floats
       Minimum and maximum for edge colormap scaling (default=None)

    ax : Matplotlib Axes object, optional
       Draw the graph in the specified Matplotlib axes.

    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.

    arrowstyle : str, optional (default='-|>')
       For directed graphs, choose the style of the arrow heads.
       See :py:class: `matplotlib.patches.ArrowStyle` for more
       options.

    arrowsize : int, optional (default=10)
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.

    label : [None| string]
       Label for legend

    Returns
    -------
    matplotlib.collection.LineCollection
        `LineCollection` of the edges

    list of matplotlib.patches.FancyArrowPatch
        `FancyArrowPatch` instances of the directed edges

    Depending whether the drawing includes arrows or not.

    Notes
    -----
    For directed graphs, arrows are drawn at the head end.  Arrows can be
    turned off with keyword arrows=False. Be sure to include `node_size' as a
    keyword argument; arrows are drawn considering the size of nodes.

    Examples
    --------
    >>> G = nx.dodecahedral_graph()
    >>> edges = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))

    >>> G = nx.DiGraph()
    >>> G.add_edges_from([(1, 2), (1, 3), (2, 3)])
    >>> arcs = nx.draw_networkx_edges(G, pos=nx.spring_layout(G))
    >>> alphas = [0.3, 0.4, 0.5]
    >>> for i, arc in enumerate(arcs):  # change alpha values of arcs
    ...     arc.set_alpha(alphas[i])

    Also see the NetworkX drawing examples at
    https://networkx.github.io/documentation/latest/auto_examples/index.html

    See Also
    --------
    draw()
    draw_networkx()
    draw_networkx_nodes()
    draw_networkx_labels()
    draw_networkx_edge_labels()
    """
    try:
        import matplotlib
        import matplotlib.cbook as cb
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
302
        import matplotlib.pyplot as plt
Zihao Ye's avatar
Zihao Ye committed
303
        import numpy as np
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
304
305
306
        from matplotlib.collections import LineCollection
        from matplotlib.colors import colorConverter, Colormap, Normalize
        from matplotlib.patches import ConnectionStyle, FancyArrowPatch
Zihao Ye's avatar
Zihao Ye committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
    except ImportError:
        raise ImportError("Matplotlib required for draw()")
    except RuntimeError:
        print("Matplotlib unable to open display")
        raise

    if ax is None:
        ax = plt.gca()

    if edgelist is None:
        edgelist = list(G.edges())

    if not edgelist or len(edgelist) == 0:  # no edges!
        return None

    if nodelist is None:
        nodelist = list(G.nodes())

    # set edge positions
    edge_pos = np.asarray([(pos[e[0]], pos[e[1]]) for e in edgelist])

    if not cb.iterable(width):
        lw = (width,)
    else:
        lw = width

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
333
334
335
336
337
    if (
        not is_string_like(edge_color)
        and cb.iterable(edge_color)
        and len(edge_color) == len(edge_pos)
    ):
Zihao Ye's avatar
Zihao Ye committed
338
339
340
        if np.alltrue([is_string_like(c) for c in edge_color]):
            # (should check ALL elements)
            # list of color letters such as ['k','r','k',...]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
341
342
343
            edge_colors = tuple(
                [colorConverter.to_rgba(c, alpha) for c in edge_color]
            )
Zihao Ye's avatar
Zihao Ye committed
344
345
        elif np.alltrue([not is_string_like(c) for c in edge_color]):
            # If color specs are given as (rgb) or (rgba) tuples, we're OK
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
346
347
348
            if np.alltrue(
                [cb.iterable(c) and len(c) in (3, 4) for c in edge_color]
            ):
Zihao Ye's avatar
Zihao Ye committed
349
350
351
352
353
                edge_colors = tuple(edge_color)
            else:
                # numbers (which are going to be mapped with a colormap)
                edge_colors = None
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
354
            raise ValueError("edge_color must contain color names or numbers")
Zihao Ye's avatar
Zihao Ye committed
355
356
    else:
        if is_string_like(edge_color) or len(edge_color) == 1:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
357
            edge_colors = (colorConverter.to_rgba(edge_color, alpha),)
Zihao Ye's avatar
Zihao Ye committed
358
        else:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
359
            msg = "edge_color must be a color or list of one color per edge"
Zihao Ye's avatar
Zihao Ye committed
360
361
            raise ValueError(msg)

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
362
363
364
365
366
367
368
369
370
    if not G.is_directed() or not arrows:
        edge_collection = LineCollection(
            edge_pos,
            colors=edge_colors,
            linewidths=lw,
            antialiaseds=(1,),
            linestyle=style,
            transOffset=ax.transData,
        )
Zihao Ye's avatar
Zihao Ye committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385

        edge_collection.set_zorder(1)  # edges go behind nodes
        edge_collection.set_label(label)
        ax.add_collection(edge_collection)

        # Note: there was a bug in mpl regarding the handling of alpha values
        # for each line in a LineCollection. It was fixed in matplotlib by
        # r7184 and r7189 (June 6 2009). We should then not set the alpha
        # value globally, since the user can instead provide per-edge alphas
        # now.  Only set it globally if provided as a scalar.
        if cb.is_numlike(alpha):
            edge_collection.set_alpha(alpha)

        if edge_colors is None:
            if edge_cmap is not None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
386
                assert isinstance(edge_cmap, Colormap)
Zihao Ye's avatar
Zihao Ye committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
            edge_collection.set_array(np.asarray(edge_color))
            edge_collection.set_cmap(edge_cmap)
            if edge_vmin is not None or edge_vmax is not None:
                edge_collection.set_clim(edge_vmin, edge_vmax)
            else:
                edge_collection.autoscale()
        return edge_collection

    arrow_collection = None

    if G.is_directed() and arrows:
        # Note: Waiting for someone to implement arrow to intersection with
        # marker.  Meanwhile, this works well for polygons with more than 4
        # sides and circle.

        def to_marker_edge(marker_size, marker):
            if marker in "s^>v<d":  # `large` markers need extra space
                return np.sqrt(2 * marker_size) / 2
            else:
                return np.sqrt(marker_size) / 2

        # Draw arrows with `matplotlib.patches.FancyarrowPatch`
        arrow_collection = []
        mutation_scale = arrowsize  # scale factor of arrow head
        arrow_colors = edge_colors
        if arrow_colors is None:
            if edge_cmap is not None:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
414
                assert isinstance(edge_cmap, Colormap)
Zihao Ye's avatar
Zihao Ye committed
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
            else:
                edge_cmap = plt.get_cmap()  # default matplotlib colormap
            if edge_vmin is None:
                edge_vmin = min(edge_color)
            if edge_vmax is None:
                edge_vmax = max(edge_color)
            color_normal = Normalize(vmin=edge_vmin, vmax=edge_vmax)

        for i, (src, dst) in enumerate(edge_pos):
            x1, y1 = src
            x2, y2 = dst
            arrow_color = None
            line_width = None
            shrink_source = 0  # space from source to tail
            shrink_target = 0  # space from  head to target
            if cb.iterable(node_size):  # many node sizes
                src_node, dst_node = edgelist[i]
                index_node = nodelist.index(dst_node)
                marker_size = node_size[index_node]
                shrink_target = to_marker_edge(marker_size, node_shape)
            else:
                shrink_target = to_marker_edge(node_size, node_shape)
            if arrow_colors is None:
                arrow_color = edge_cmap(color_normal(edge_color[i]))
            elif len(arrow_colors) > 1:
                arrow_color = arrow_colors[i]
            else:
                arrow_color = arrow_colors[0]
            if len(lw) > 1:
                line_width = lw[i]
            else:
                line_width = lw[0]
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
447
448
449
450
451
452
453
454
455
456
457
458
            arrow = FancyArrowPatch(
                (x1, y1),
                (x2, y2),
                arrowstyle=arrowstyle,
                shrinkA=shrink_source,
                shrinkB=shrink_target,
                mutation_scale=mutation_scale,
                connectionstyle=connectionstyle,
                color=arrow_color,
                linewidth=line_width,
                zorder=1,
            )  # arrows go behind nodes
Zihao Ye's avatar
Zihao Ye committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473

            # There seems to be a bug in matplotlib to make collections of
            # FancyArrowPatch instances. Until fixed, the patches are added
            # individually to the axes instance.
            arrow_collection.append(arrow)
            ax.add_patch(arrow)

    # update view
    minx = np.amin(np.ravel(edge_pos[:, :, 0]))
    maxx = np.amax(np.ravel(edge_pos[:, :, 0]))
    miny = np.amin(np.ravel(edge_pos[:, :, 1]))
    maxy = np.amax(np.ravel(edge_pos[:, :, 1]))

    w = maxx - minx
    h = maxy - miny
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
474
    padx, pady = 0.05 * w, 0.05 * h
Zihao Ye's avatar
Zihao Ye committed
475
476
477
478
479
480
481
482
    corners = (minx - padx, miny - pady), (maxx + padx, maxy + pady)
    ax.update_datalim(corners)
    ax.autoscale_view()

    return arrow_collection


def draw_g(graph):
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
483
484
485
486
487
488
489
490
491
492
    g = graph.g.to_networkx()
    fig = plt.figure(figsize=(8, 4), dpi=150)
    ax = fig.subplots()
    ax.axis("off")
    ax.set_ylim(-1, 1.5)
    en_indx = graph.nids["enc"].tolist()
    de_indx = graph.nids["dec"].tolist()
    en_l = {i: np.array([i, 0]) for i in en_indx}
    de_l = {i: np.array([i + 2, 1]) for i in de_indx}
    en_de_s = []
Zihao Ye's avatar
Zihao Ye committed
493
494
    for i in en_indx:
        for j in de_indx:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
495
496
497
            en_de_s.append((i, j))
            g.add_edge(i, j)
    en_s = []
Zihao Ye's avatar
Zihao Ye committed
498
499
    for i in en_indx:
        for j in en_indx:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
500
501
            g.add_edge(i, j)
            en_s.append((i, j))
Zihao Ye's avatar
Zihao Ye committed
502

Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
503
504
    de_s = []
    for idx, i in enumerate(de_indx):
Zihao Ye's avatar
Zihao Ye committed
505
        for j in de_indx[idx:]:
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
            g.add_edge(i, j)
            de_s.append((i, j))

    nx.draw_networkx_nodes(
        g, en_l, nodelist=en_indx, node_color="r", node_size=60, ax=ax
    )
    nx.draw_networkx_nodes(
        g, de_l, nodelist=de_indx, node_color="r", node_size=60, ax=ax
    )
    draw_networkx_edges(
        g,
        en_l,
        edgelist=en_s,
        ax=ax,
        connectionstyle="arc3,rad=-0.3",
        width=0.5,
    )
    draw_networkx_edges(
        g,
        de_l,
        edgelist=de_s,
        ax=ax,
        connectionstyle="arc3,rad=-0.3",
        width=0.5,
    )
    draw_networkx_edges(g, {**en_l, **de_l}, edgelist=en_de_s, width=0.3, ax=ax)
Zihao Ye's avatar
Zihao Ye committed
532
    # ax.add_patch()
Hongzhi (Steve), Chen's avatar
Hongzhi (Steve), Chen committed
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
    ax.text(
        len(en_indx) + 0.5,
        0,
        "Encoder",
        verticalalignment="center",
        horizontalalignment="left",
    )

    ax.text(
        len(en_indx) + 0.5,
        1,
        "Decoder",
        verticalalignment="center",
        horizontalalignment="right",
    )
    delta = 0.03
    for value in {**en_l, **de_l}.values():
        x, y = value
        ax.add_patch(
            FancyArrowPatch(
                (x - delta, y + delta),
                (x - delta, y - delta),
                arrowstyle="->",
                mutation_scale=8,
                connectionstyle="arc3,rad=3",
            )
        )
Zihao Ye's avatar
Zihao Ye committed
560
    plt.show(fig)