graphviz_graph.py 4.9 KB
Newer Older
Y
Yan Chunwei 已提交
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
import random
import subprocess


def crepr(v):
    if type(v) is str or type(v) is unicode:
        return '"%s"' % v
    return str(v)


class Rank(object):
    def __init__(self, kind, name, priority):
        '''
        kind: str
        name: str
        priority: int
        '''
        self.kind = kind
        self.name = name
        self.priority = priority
        self.nodes = []

    def __str__(self):
        if not self.nodes:
            return ''

        return '{' + 'rank={};'.format(self.kind) + \
T
Thuan Nguyen 已提交
28
               ','.join([node.name for node in self.nodes]) + '}'
Y
Yan Chunwei 已提交
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


# the python package graphviz is too poor.
class Graph(object):
    rank_counter = 0

    def __init__(self, title, **attrs):
        self.title = title
        self.attrs = attrs
        self.nodes = []
        self.edges = []
        self.rank_groups = {}

    def code(self):
        return self.__str__()

    def rank_group(self, kind, priority):
        name = "rankgroup-%d" % Graph.rank_counter
        Graph.rank_counter += 1
        rank = Rank(kind, name, priority)
        self.rank_groups[name] = rank
        return name

    def node(self, label, prefix, **attrs):
        node = Node(label, prefix, **attrs)

        if 'rank' in attrs:
            rank = self.rank_groups[attrs['rank']]
            del attrs['rank']
            rank.nodes.append(node)
        self.nodes.append(node)
        return node

    def edge(self, source, target, **attrs):
        edge = Edge(source, target, **attrs)
        self.edges.append(edge)
        return edge

    def display(self, dot_path):
        file = open(dot_path, 'w')
        file.write(self.__str__())
        image_path = dot_path[:-3] + "jpg"
Q
Qiao Longfei 已提交
71
        cmd = ["dot", "-Tjpg", dot_path, "-o", image_path]
Y
Yan Chunwei 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
        return image_path

    def show(self, dot_path):
        image = self.display(dot_path)
        cmd = ["feh", image]
        subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
Y
Yan Chunwei 已提交
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

    def _rank_repr(self):
        ranks = sorted(
            self.rank_groups.items(),
            cmp=lambda a, b: a[1].priority > b[1].priority)
        repr = []
        for x in ranks:
            repr.append(str(x[1]))
        return '\n'.join(repr) + '\n'

    def __str__(self):
        reprs = [
            'digraph G {',
            'title = {}'.format(crepr(self.title)),
        ]

        for attr in self.attrs:
            reprs.append("{key}={value};".format(
                key=attr, value=crepr(self.attrs[attr])))

        reprs.append(self._rank_repr())

        random.shuffle(self.nodes)
        reprs += [str(node) for node in self.nodes]

        for x in self.edges:
            reprs.append(str(x))

        reprs.append('}')
        return '\n'.join(reprs)


class Node(object):
    counter = 1

    def __init__(self, label, prefix, **attrs):
        self.label = label
        self.name = "%s_%d" % (prefix, Node.counter)
        self.attrs = attrs
        Node.counter += 1

    def __str__(self):
        reprs = '{name} [label={label} {extra} ];'.format(
            name=self.name,
            label=self.label,
            extra=',' + ','.join("%s=%s" % (key, crepr(value))
                                 for key, value in self.attrs.items())
            if self.attrs else "")
        return reprs


class Edge(object):
    def __init__(self, source, target, **attrs):
        '''
        Link source to target.
        :param source: Node
        :param target: Node
        :param graph: Graph
        :param attrs: dic
        '''
        self.source = source
        self.target = target
        self.attrs = attrs

    def __str__(self):
        repr = "{source} -> {target} {extra}".format(
            source=self.source.name,
            target=self.target.name,
            extra="" if not self.attrs else
            "[" + ','.join("{}={}".format(attr[0], crepr(attr[1]))
                           for attr in self.attrs.items()) + "]")
        return repr


g_graph = Graph(title="some model")


def add_param(label, graph=None):
    if not graph:
        graph = g_graph
    return graph.node(label=label, prefix='param', color='blue')


def add_op(label, graph=None):
    if not graph:
        graph = g_graph
    label = '\n'.join([
        '<table border="0">',
        '  <tr>',
        '    <td>',
        label,
        '    </td>'
        '  </tr>',
        '</table>',
    ])
    return graph.node(label=label, prefix='op', shape="none")


def add_edge(source, target):
    return g_graph.edge(source, target)


if __name__ == '__main__':
    n0 = add_param(crepr("layer/W0.w"))
    n1 = add_param(crepr("layer/W0.b"))

    n2 = add_op("sum")

    add_edge(n0, n2)
    add_edge(n1, n2)

    print g_graph.code()
    g_graph.display('./1.dot')