__init__.py 7.51 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /usr/bin/env python
# graph_tool.py -- a general graph manipulation python module
#
# Copyright (C) 2007 Tiago de Paula Peixoto <tiago@forked.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

19
import sys, os, os.path, time
Tiago Peixoto's avatar
Tiago Peixoto committed
20
21
22
23
24
25
26
27
import matplotlib.cm
import matplotlib.colors
from .. core import _degree, _prop, PropertyMap
from .. decorators import _limit_args
import gv

def graph_draw(g, pos=None, size=(15,15), pin=False, layout="neato",
               maxiter=None, ratio="fill", overlap=False, splines=False,
28
29
               mode="major", vsize=0.1, penwidth=1.0, eweight=None, ewidth=None,
               gprops={}, vprops={}, eprops={}, vcolor=None, ecolor=None,
Tiago Peixoto's avatar
Tiago Peixoto committed
30
               vcmap=matplotlib.cm.jet, vnorm=True, ecmap=matplotlib.cm.jet,
31
               enorm=True, output="", output_format="auto", returngv=False,
32
               fork=True, seed=0):
Tiago Peixoto's avatar
Tiago Peixoto committed
33
34
    """Draw a graph using graphviz."""

35
36
37
38
39
40
41
42
    if output != "":
        output = os.path.expanduser(output)
        # check opening file for writing, since graphview will bork if it is not
        # possible to open file
        if os.path.dirname(output) != "" and \
               not os.access(os.path.dirname(output), os.W_OK):
            raise IOError("cannot write to " + os.path.dirname(output))

Tiago Peixoto's avatar
Tiago Peixoto committed
43
44
45
46
47
48
49
50
    if g.is_directed():
        gvg = gv.digraph("G")
    else:
        gvg = gv.graph("G")

    # main graph properties
    gv.setv(gvg,"outputorder", "edgesfirst")
    gv.setv(gvg,"mode", mode)
51
52
53
54
55
56
57
58
    if overlap == False:
        if layout == "neato" and mode == "ipsep":
            overlap = "ipsep"
        else:
            overlap = "false"
    else:
        overlap = "true"
    if isinstance(overlap,str):
Tiago Peixoto's avatar
Tiago Peixoto committed
59
60
61
62
        gv.setv(gvg,"overlap", overlap)
    if splines:
        gv.setv(gvg,"splines", "true")
    gv.setv(gvg,"ratio", str(ratio))
63
    gv.setv(gvg,"size", "%f,%f" % (size[0]/2.54,size[1]/2.54)) # centimeters
Tiago Peixoto's avatar
Tiago Peixoto committed
64
65
    if maxiter != None:
        gv.setv(gvg,"maxiter", str(maxiter))
Tiago Peixoto's avatar
Tiago Peixoto committed
66
67
68
69
70
    if seed != 0:
        if type(seed) == int:
            gv.setv(gvg, "start", "%d" % seed)
        else:
            gv.setv(gvg, "start", seed)
Tiago Peixoto's avatar
Tiago Peixoto committed
71
72

    # apply all user supplied properties
73
    for k,val in gprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        if isinstance(val, PropertyMap):
            gv.setv(gvg, k, str(val[g]))
        else:
            gv.setv(gvg, k, str(val))

    # normalize color properties
    if vcolor != None and not isinstance(vcolor, str):
        minmax = [float("inf"), -float("inf")]
        for v in g.vertices():
            c = vcolor[v]
            minmax[0] = min(c,minmax[0])
            minmax[1] = max(c,minmax[1])
        if vnorm:
            vnorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    if ecolor != None and not isinstance(ecolor, str):
        minmax = [float("inf"), -float("inf")]
        for e in g.edges():
92
            c = ecolor[e]
Tiago Peixoto's avatar
Tiago Peixoto committed
93
94
95
96
97
98
99
100
101
102
103
            minmax[0] = min(c,minmax[0])
            minmax[1] = max(c,minmax[1])
        if enorm:
            enorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])

    nodes = []
    edges = []

    # add nodes
    for v in g.vertices():
        n = gv.node(gvg,str(g.vertex_index[v]))
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
        if type(vsize) != tuple:
            vw = vh = vsize
        else:
            vw, vh = vsize
        if type(vw) == PropertyMap:
            vw = vw[v]
        if type(vh) == PropertyMap:
            vh = vh[v]

        if type(vw) == str and vw == "in":
            vw = v.in_degree()
        if type(vw) == str and vw == "out":
            vw = v.out_degree()
        if type(vw) == str and vw == "total":
            vw = v.in_degree() + v.out_degree()

        if type(vh) == str and vh == "in":
            vh = v.in_degree()
        if type(vh) == str and vh == "out":
            vh = v.out_degree()
        if type(vh) == str and vh == "total":
            vh = v.in_degree() + v.out_degree()

        gv.setv(n, "width", "%g" % vw)
        gv.setv(n, "height", "%g" % vh)
Tiago Peixoto's avatar
Tiago Peixoto committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        gv.setv(n, "style", "filled")
        gv.setv(n, "color", "black")
        # apply color
        if vcolor != None:
            if isinstance(vcolor,str):
                gv.setv(n, "fillcolor", vcolor)
            else:
                color = tuple([int(c*255.0) for c in vcmap(vnorm(vcolor[v]))])
                gv.setv(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
        else:
            gv.setv(n, "fillcolor", "red")
        gv.setv(n, "label", "")

        # user supplied position
        if pos != None:
            gv.setv(n, "pos", "%f,%f" % (pos[0][v],pos[1][v]))
            gv.setv(n, "pin", str(pin))

        # apply all user supplied properties
148
        for k,val in vprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
149
150
151
152
153
154
155
156
157
            if isinstance(val, PropertyMap):
                gv.setv(n, k, str(val[v]))
            else:
                gv.setv(n, k, str(val))
        nodes.append(n)
    for e in g.edges():
        ge = gv.edge(nodes[g.vertex_index[e.source()]],
                     nodes[g.vertex_index[e.target()]])
        gv.setv(ge, "arrowsize", "0.3")
158
159
        if g.is_directed():
            gv.setv(ge, "arrowhead", "vee")
Tiago Peixoto's avatar
Tiago Peixoto committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
        # apply color
        if ecolor != None:
            if isinstance(ecolor,str):
                gv.setv(ge, "color", ecolor)
            else:
                color = tuple([int(c*255.0) for c in ecmap(enorm(ecolor[e]))])
                gv.setv(ge, "color", "#%.2x%.2x%.2x%.2x" % color)

        # apply weight
        if eweight != None:
            if isinstance(eweight, PropertyMap):
                gv.setv(ge, "weight", str(eweight[e]))
            else:
                gv.setv(ge, "weight", str(eweight))

        # apply width
        if ewidth != None:
            if isinstance(ewidth, PropertyMap):
                gv.setv(ge, "penwidth", str(ewidth[e]))
            else:
                gv.setv(ge, "penwidth", str(ewidth))

        # apply all user supplied properties
183
        for k,v in eprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
            if isinstance(v, PropertyMap):
                gv.setv(ge, k, str(v[e]))
            else:
                gv.setv(ge, k, str(v))
        edges.append(ge)

    gv.layout(gvg, layout)
    gv.render(gvg, "dot", "/dev/null") # retrieve postitions

    if pos == None:
        pos = (g.new_vertex_property("double"), g.new_vertex_property("double"))
    for n in xrange(0, len(nodes)):
        p = gv.getv(nodes[n], "pos")
        p = p.split(",")
        pos[0][g.vertex(n)] = float(p[0])
        pos[1][g.vertex(n)] = float(p[1])
200
201
202
203
204

    if output_format == "auto":
        if output == "":
            output_format = "xlib"
        else:
205
            output_format = output.split(".")[-1]
Tiago Peixoto's avatar
Tiago Peixoto committed
206
207
208
209
210
211
212
213

    # if using xlib we need to fork the process, otherwise good ol' graphviz
    # will call exit() when the window is closed
    if output_format == "xlib":
        pid = os.fork()
        if pid == 0:
            gv.render(gvg, output_format, output)
            sys.exit(1) # since we forked, it's good to be sure
214
215
        if not fork:
            os.wait()
Tiago Peixoto's avatar
Tiago Peixoto committed
216
217
    else:
        gv.render(gvg, output_format, output)
218
219
220
221
222
223

    if returngv:
        return pos, gv
    else:
        gv.rm(gvg)
        return pos