__init__.py 8.05 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
20
21
22
23
"""
``graph_tool.draw`` - Graph Drawing
-----------------------------------
"""

24
import sys, os, os.path, time, warnings
Tiago Peixoto's avatar
Tiago Peixoto committed
25
26
from .. core import _degree, _prop, PropertyMap
from .. decorators import _limit_args
27
28
29
30
31
32

try:
    import gv
except ImportError:
    warnings.warn("error importing gv module... graph_draw() will not work.",
                  ImportWarning)
33
34
35
36
37
38
try:
    import matplotlib.cm
    import matplotlib.colors
except ImportError:
    warnings.warn("error importing matplotlib module... " + \
                  "graph_draw() will not work.", ImportWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
39
40
41

def graph_draw(g, pos=None, size=(15,15), pin=False, layout="neato",
               maxiter=None, ratio="fill", overlap=False, splines=False,
42
43
               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
44
               vcmap=matplotlib.cm.jet, vnorm=True, ecmap=matplotlib.cm.jet,
45
               enorm=True, output="", output_format="auto", returngv=False,
46
               fork=False, seed=0):
Tiago Peixoto's avatar
Tiago Peixoto committed
47
48
    """Draw a graph using graphviz."""

49
50
51
52
53
54
55
56
    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
57
58
59
60
61
62
63
64
    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)
65
66
67
68
69
70
71
72
    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
73
74
75
76
        gv.setv(gvg,"overlap", overlap)
    if splines:
        gv.setv(gvg,"splines", "true")
    gv.setv(gvg,"ratio", str(ratio))
77
    gv.setv(gvg,"size", "%f,%f" % (size[0]/2.54,size[1]/2.54)) # centimeters
Tiago Peixoto's avatar
Tiago Peixoto committed
78
79
    if maxiter != None:
        gv.setv(gvg,"maxiter", str(maxiter))
Tiago Peixoto's avatar
Tiago Peixoto committed
80
81
82
83
84
    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
85
86

    # apply all user supplied properties
87
    for k,val in gprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
88
89
90
91
92
93
94
95
96
97
98
99
        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])
100
101
        if minmax[0] == minmax[1]:
            minmax[1] += 1
Tiago Peixoto's avatar
Tiago Peixoto committed
102
103
104
105
106
107
        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():
108
            c = ecolor[e]
Tiago Peixoto's avatar
Tiago Peixoto committed
109
110
            minmax[0] = min(c,minmax[0])
            minmax[1] = max(c,minmax[1])
111
112
        if minmax[0] == minmax[1]:
            minmax[1] += 1
Tiago Peixoto's avatar
Tiago Peixoto committed
113
114
115
116
117
118
119
120
121
        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]))
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
        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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
        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
166
        for k,val in vprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
167
168
169
170
171
172
173
174
175
            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")
176
177
        if g.is_directed():
            gv.setv(ge, "arrowhead", "vee")
Tiago Peixoto's avatar
Tiago Peixoto committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
        # 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
201
        for k,v in eprops.iteritems():
Tiago Peixoto's avatar
Tiago Peixoto committed
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
            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])
218
219
220
221
222

    if output_format == "auto":
        if output == "":
            output_format = "xlib"
        else:
223
            output_format = output.split(".")[-1]
Tiago Peixoto's avatar
Tiago Peixoto committed
224
225
226

    # if using xlib we need to fork the process, otherwise good ol' graphviz
    # will call exit() when the window is closed
227
    if output_format == "xlib" or fork:
Tiago Peixoto's avatar
Tiago Peixoto committed
228
229
230
        pid = os.fork()
        if pid == 0:
            gv.render(gvg, output_format, output)
231
232
            os._exit(0) # since we forked, it's good to be sure
        if output_format != "xlib":
233
            os.wait()
Tiago Peixoto's avatar
Tiago Peixoto committed
234
235
    else:
        gv.render(gvg, output_format, output)
236
237
238
239
240

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