graphviz_draw.py 23.9 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
2
3
4
5
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2006-2021 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7
#
8
9
10
11
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
Tiago Peixoto's avatar
Tiago Peixoto committed
12
#
13
14
15
16
# 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 Lesser General Public License for more
# details.
Tiago Peixoto's avatar
Tiago Peixoto committed
17
#
18
19
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
Tiago Peixoto's avatar
Tiago Peixoto committed
20
21
22
23
24
25
26
27

import sys
import os
import os.path
import warnings
import ctypes
import ctypes.util
import tempfile
28
from .. import PropertyMap, group_vector_property, ungroup_vector_property
29
import numpy
Tiago Peixoto's avatar
Tiago Peixoto committed
30
31
32
33
34
35
36
37
38
import numpy.random
import copy

from .. draw import arf_layout

try:
    import matplotlib.cm
    import matplotlib.colors
except ImportError:
39
    msg = "Error importing matplotlib module... graphviz_draw() will not work"
40
41
    warnings.filterwarnings("always", msg, ImportWarning)
    warnings.warn(msg, ImportWarning)
42
    raise
Tiago Peixoto's avatar
Tiago Peixoto committed
43
44
45
46
47
48
49

try:
    libname = ctypes.util.find_library("c")
    libc = ctypes.CDLL(libname)
    if hasattr(libc, "open_memstream"):
        libc.open_memstream.restype = ctypes.POINTER(ctypes.c_char)
except OSError:
50
51
52
    msg = "Error importing C standard library... graphviz_draw() will not work."
    warnings.filterwarnings("always", msg, ImportWarning)
    warnings.warn(msg, ImportWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
53
54
55
56
57
58
59
    pass


try:
    libname = ctypes.util.find_library("gvc")
    if libname is None:
        raise OSError()
60
    libgv = ctypes.CDLL(libname, ctypes.RTLD_GLOBAL)
Tiago Peixoto's avatar
Tiago Peixoto committed
61
62
63
64
65
66
67
68
    # properly set the return types of certain functions
    ptype = ctypes.POINTER(ctypes.c_char)
    libgv.gvContext.restype = ptype
    libgv.agopen.restype = ptype
    libgv.agnode.restype = ptype
    libgv.agedge.restype = ptype
    libgv.agget.restype = ptype
    libgv.agstrdup_html.restype = ptype
69
70
71
    libgv.agstrdup_html.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
    libgv.agraphof.restype = ctypes.c_void_p
    libgv.agraphof.argtypes = [ctypes.c_void_p]
Tiago Peixoto's avatar
Tiago Peixoto committed
72
73
74
    # create a context to use the whole time (if we keep freeing and recreating
    # it, we will hit a memory leak in graphviz)
    gvc = libgv.gvContext()
75
76
77

    try:
        gv_new_api = True
78
79
        libgv_directed = ctypes.c_int.in_dll(libgv, "Agdirected")
        libgv_undirected = ctypes.c_int.in_dll(libgv, "Agundirected")
80
81
82
83
84
    except AttributeError:
        gv_new_api = False
        libgv_directed = 1
        libgv_undirected = 0

Tiago Peixoto's avatar
Tiago Peixoto committed
85
except OSError:
86
87
88
    msg = "Error importing graphviz C library (libgvc)... graphviz_draw() will not work."
    warnings.filterwarnings("always", msg, ImportWarning)
    warnings.warn(msg, ImportWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
89
90


91
def htmlize(elem, val):
Tiago Peixoto's avatar
Tiago Peixoto committed
92
    if len(val) >= 2 and val[0] == "<" and val[-1] == ">":
93
        g = libgv.agraphof(elem)
94
        return ctypes.string_at(libgv.agstrdup_html(g, str(val[1:-1]).encode("utf8"))).decode("utf8")
Tiago Peixoto's avatar
Tiago Peixoto committed
95
96
97
98
    return val


def aset(elem, attr, value):
99
    v = htmlize(elem, str(value)).encode("utf8")
100
    libgv.agsafeset(elem, str(attr).encode("utf8"), v, v)
Tiago Peixoto's avatar
Tiago Peixoto committed
101
102
103


def aget(elem, attr):
104
105
106
    s = ctypes.string_at(libgv.agget(elem,
                                     str(attr).encode("utf8")))
    return s.decode("utf8")
Tiago Peixoto's avatar
Tiago Peixoto committed
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121


def graphviz_draw(g, pos=None, size=(15, 15), pin=False, layout=None,
                  maxiter=None, ratio="fill", overlap=True, sep=None,
                  splines=False, vsize=0.105, penwidth=1.0, elen=None,
                  gprops={}, vprops={}, eprops={}, vcolor="#a40000",
                  ecolor="#2e3436", vcmap=None, vnorm=True, ecmap=None,
                  enorm=True, vorder=None, eorder=None, output="",
                  output_format="auto", fork=False, return_string=False):
    r"""Draw a graph using graphviz.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
122
    pos : :class:`~graph_tool.VertexPropertyMap` or tuple of :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
123
124
125
        Vertex property maps containing the x and y coordinates of the vertices.
    size : tuple of scalars (optional, default: ``(15,15)``)
        Size (in centimeters) of the canvas.
126
    pin : bool or :class:`~graph_tool.VertexPropertyMap` (default: ``False``)
Tiago Peixoto's avatar
Tiago Peixoto committed
127
        If ``True``, the vertices are not moved from their initial position. If
128
        a :class:`~graph_tool.VertexPropertyMap` is passed, it is used to pin nodes
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
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
        individually.
    layout : string (default: ``"neato" if g.num_vertices() <= 1000 else "sfdp"``)
        Layout engine to be used. Possible values are ``"neato"``, ``"fdp"``,
        ``"dot"``, ``"circo"``, ``"twopi"`` and ``"arf"``.
    maxiter : int (default: ``None``)
        If specified, limits the maximum number of iterations.
    ratio : string or float (default: ``"fill"``)
        Sets the aspect ratio (drawing height/drawing width) for the
        drawing. Note that this is adjusted before the ``size`` attribute
        constraints are enforced.

        If ``ratio`` is numeric, it is taken as the desired aspect ratio. Then,
        if the actual aspect ratio is less than the desired ratio, the drawing
        height is scaled up to achieve the desired ratio; if the actual ratio is
        greater than that desired ratio, the drawing width is scaled up.

        If ``ratio == "fill"`` and the size attribute is set, node positions are
        scaled, separately in both x and y, so that the final drawing exactly
        fills the specified size.

        If ``ratio == "compress"`` and the size attribute is set, dot attempts
        to compress the initial layout to fit in the given size. This achieves a
        tighter packing of nodes but reduces the balance and symmetry.  This
        feature only works in dot.

        If ``ratio == "expand"``, the size attribute is set, and both the width
        and the height of the graph are less than the value in size, node
        positions are scaled uniformly until at least one dimension fits size
        exactly.  Note that this is distinct from using size as the desired
        size, as here the drawing is expanded before edges are generated and all
        node and text sizes remain unchanged.

        If ``ratio == "auto"``, the page attribute is set and the graph cannot
        be drawn on a single page, then size is set to an "ideal" value. In
        particular, the size in a given dimension will be the smallest integral
        multiple of the page size in that dimension which is at least half the
        current size. The two dimensions are then scaled independently to the
        new size. This feature only works in dot.
    overlap : bool or string (default: ``"prism"``)
        Determines if and how node overlaps should be removed. Nodes are first
        enlarged using the sep attribute. If ``True``, overlaps are retained. If
        the value is ``"scale"``, overlaps are removed by uniformly scaling in x
        and y. If the value is ``False``, node overlaps are removed by a
        Voronoi-based technique. If the value is ``"scalexy"``, x and y are
        separately scaled to remove overlaps.

        If sfdp is available, one can set overlap to ``"prism"`` to use a
        proximity graph-based algorithm for overlap removal. This is the
        preferred technique, though ``"scale"`` and ``False`` can work well with
        small graphs. This technique starts with a small scaling up, controlled
        by the overlap_scaling attribute, which can remove a significant portion
        of the overlap. The prism option also accepts an optional non-negative
        integer suffix. This can be used to control the number of attempts made
        at overlap removal. By default, ``overlap == "prism"`` is equivalent to
        ``overlap == "prism1000"``. Setting ``overlap == "prism0"`` causes only
        the scaling phase to be run.

        If the value is ``"compress"``, the layout will be scaled down as much
        as possible without introducing any overlaps, obviously assuming there
        are none to begin with.
    sep : float (default: ``None``)
        Specifies margin to leave around nodes when removing node overlap. This
        guarantees a minimal non-zero distance between nodes.
    splines : bool (default: ``False``)
        If ``True``, the edges are drawn as splines and routed around the
        vertices.
195
    vsize : float, :class:`~graph_tool.VertexPropertyMap`, or tuple (default: ``0.105``)
Tiago Peixoto's avatar
Tiago Peixoto committed
196
197
        Default vertex size (width and height). If a tuple is specified, the
        first value should be a property map, and the second is a scale factor.
198
    penwidth : float, :class:`~graph_tool.EdgePropertyMap` or tuple (default: ``1.0``)
Tiago Peixoto's avatar
Tiago Peixoto committed
199
200
201
202
        Specifies the width of the pen, in points, used to draw lines and
        curves, including the boundaries of edges and clusters. It has no effect
        on text. If a tuple is specified, the first value should be a property
        map, and the second is a scale factor.
203
    elen : float or :class:`~graph_tool.EdgePropertyMap` (default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
204
205
206
207
208
209
210
211
212
213
214
215
        Preferred edge length, in inches.
    gprops : dict (default: ``{}``)
        Additional graph properties, as a dictionary. The keys are the property
        names, and the values must be convertible to string.
    vprops : dict (default: ``{}``)
        Additional vertex properties, as a dictionary. The keys are the property
        names, and the values must be convertible to string, or vertex property
        maps, with values convertible to strings.
    eprops : dict (default: ``{}``)
        Additional edge properties, as a dictionary. The keys are the property
        names, and the values must be convertible to string, or edge property
        maps, with values convertible to strings.
216
    vcolor : string or :class:`~graph_tool.VertexPropertyMap` (default: ``"#a40000"``)
Tiago Peixoto's avatar
Tiago Peixoto committed
217
218
219
        Drawing color for vertices. If the valued supplied is a property map,
        the values must be scalar types, whose color values are obtained from
        the ``vcmap`` argument.
220
    ecolor : string or :class:`~graph_tool.EdgePropertyMap` (default: ``"#2e3436"``)
Tiago Peixoto's avatar
Tiago Peixoto committed
221
222
223
        Drawing color for edges. If the valued supplied is a property map,
        the values must be scalar types, whose color values are obtained from
        the ``ecmap`` argument.
224
    vcmap : :class:`matplotlib.colors.Colormap` (default: :obj:`matplotlib.cm.jet`)
Tiago Peixoto's avatar
Tiago Peixoto committed
225
226
227
        Vertex color map.
    vnorm : bool (default: ``True``)
        Normalize vertex color values to the [0,1] range.
228
    ecmap : :class:`matplotlib.colors.Colormap` (default: :obj:`matplotlib.cm.jet`)
Tiago Peixoto's avatar
Tiago Peixoto committed
229
230
231
232
233
234
        Edge color map.
    enorm : bool (default: ``True``)
        Normalize edge color values to the [0,1] range.
    vorder : :class:`~graph_tool.PropertyMap` (default: ``None``)
        Scalar vertex property map which specifies the order with which vertices
        are drawn.
235
    eorder : :class:`~graph_tool.VertexPropertyMap` (default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
236
237
238
        Scalar edge property map which specifies the order with which edges
        are drawn.
    output : string (default: ``""``)
Malte R's avatar
Malte R committed
239
        Output file name. If ``None`` then no output is produced.
Tiago Peixoto's avatar
Tiago Peixoto committed
240
241
242
243
244
    output_format : string (default: ``"auto"``)
        Output file format. Possible values are ``"auto"``, ``"xlib"``,
        ``"ps"``, ``"svg"``, ``"svgz"``, ``"fig"``, ``"mif"``, ``"hpgl"``,
        ``"pcl"``, ``"png"``, ``"gif"``, ``"dia"``, ``"imap"``, ``"cmapx"``. If
        the value is ``"auto"``, the format is guessed from the ``output``
Malte R's avatar
Malte R committed
245
        parameter, or ``xlib`` if it is empty.
Tiago Peixoto's avatar
Tiago Peixoto committed
246
247
248
249
250
251
252
253
254
255
256
    fork : bool (default: ``False``)
        If ``True``, the program is forked before drawing. This is used as a
        work-around for a bug in graphviz, where the ``exit()`` function is
        called, which would cause the calling program to end. This is always
        assumed ``True``, if ``output_format == 'xlib'``.
    return_string : bool (default: ``False``)
        If ``True``, a string containing the rendered graph as binary data is
        returned (defaults to png format).

    Returns
    -------
257
    pos : :class:`~graph_tool.VertexPropertyMap`
Tiago Peixoto's avatar
Tiago Peixoto committed
258
259
260
261
262
263
264
        Vector vertex property map with the x and y coordinates of the vertices.
    gv : gv.digraph or gv.graph (optional, only if ``returngv == True``)
        Internally used graphviz graph.


    Notes
    -----
265
    This function is a wrapper for the [graphviz]_ routines. Extensive additional
Tiago Peixoto's avatar
Tiago Peixoto committed
266
267
268
269
270
271
    documentation for the graph, vertex and edge properties is available at:
    http://www.graphviz.org/doc/info/attrs.html.


    Examples
    --------
272
273
274
275
276
277
278
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)
       from numpy import sqrt

279
280
    >>> g = gt.price_network(1500)
    >>> deg = g.degree_property_map("in")
Tiago Peixoto's avatar
Tiago Peixoto committed
281
282
    >>> deg.a = 2 * (sqrt(deg.a) * 0.5 + 0.4)
    >>> ebet = gt.betweenness(g)[1]
283
284
    >>> gt.graphviz_draw(g, vcolor=deg, vorder=deg, elen=10,
    ...                  ecolor=ebet, eorder=ebet, output="graphviz-draw.pdf")
Tiago Peixoto's avatar
Tiago Peixoto committed
285
286
    <...>

287
288
289
290
291
292
    .. testcode::
       :hide:

       gt.graphviz_draw(g, vcolor=deg, vorder=deg, elen=10,
                        ecolor=ebet, eorder=ebet, output="graphviz-draw.png")

Tiago Peixoto's avatar
Tiago Peixoto committed
293
294
295
    .. figure:: graphviz-draw.*
        :align: center

296
297
        Kamada-Kawai force-directed layout of a Price network with 1500
        nodes. The vertex size and color indicate the degree, and the edge color
298
        corresponds to the edge betweenness centrality
Tiago Peixoto's avatar
Tiago Peixoto committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315

    References
    ----------
    .. [graphviz] http://www.graphviz.org

    """

    if output != "" and output is not None:
        output = os.path.expanduser(output)
        # check opening file for writing, since graphviz 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))

    has_layout = False
    try:
316
317
318
        if gv_new_api:
            gvg = libgv.agopen("G".encode("utf8"),
                               libgv_directed if g.is_directed() else libgv_undirected,
319
                               0)
320
321
322
        else:
            gvg = libgv.agopen("G".encode("utf8"),
                               libgv_directed if g.is_directed() else libgv_undirected)
Tiago Peixoto's avatar
Tiago Peixoto committed
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371

        if layout is None:
            if pin == False:
                layout = "neato" if g.num_vertices() <= 1000 else "sfdp"
            else:
                layout = "neato"

        if layout == "arf":
            layout = "neato"
            pos = arf_layout(g, pos=pos)
            pin = True

        if pos is not None:
            # copy user-supplied property
            if isinstance(pos, PropertyMap):
                pos = ungroup_vector_property(pos, [0, 1])
            else:
                pos = (g.copy_property(pos[0]), g.copy_property(pos[1]))

        if type(vsize) == tuple:
            s = g.new_vertex_property("double")
            g.copy_property(vsize[0], s)
            s.a *= vsize[1]
            vsize = s

        if type(penwidth) == tuple:
            s = g.new_edge_property("double")
            g.copy_property(penwidth[0], s)
            s.a *= penwidth[1]
            penwidth = s

        # main graph properties
        aset(gvg, "outputorder", "edgesfirst")
        aset(gvg, "mode", "major")
        if type(overlap) is bool:
            overlap = "true" if overlap else "false"
        else:
            overlap = str(overlap)
        aset(gvg, "overlap", overlap)
        if sep is not None:
            aset(gvg, "sep", sep)
        if splines:
            aset(gvg, "splines", "true")
        aset(gvg, "ratio", ratio)
        # size is in centimeters... convert to inches
        aset(gvg, "size", "%f,%f" % (size[0] / 2.54, size[1] / 2.54))
        if maxiter is not None:
            aset(gvg, "maxiter", maxiter)

372
        seed = numpy.random.randint(sys.maxsize)
Tiago Peixoto's avatar
Tiago Peixoto committed
373
374
375
        aset(gvg, "start", "%d" % seed)

        # apply all user supplied graph properties
376
        for k, val in gprops.items():
Tiago Peixoto's avatar
Tiago Peixoto committed
377
378
379
380
381
382
383
384
            if isinstance(val, PropertyMap):
                aset(gvg, k, val[g])
            else:
                aset(gvg, k, val)

        # normalize color properties
        if (isinstance(vcolor, PropertyMap) and
            vcolor.value_type() != "string"):
385
            minmax = [numpy.inf, -numpy.inf]
Tiago Peixoto's avatar
Tiago Peixoto committed
386
387
388
389
390
391
392
            for v in g.vertices():
                c = vcolor[v]
                minmax[0] = min(c, minmax[0])
                minmax[1] = max(c, minmax[1])
            if minmax[0] == minmax[1]:
                minmax[1] += 1
            if vnorm:
393
                vnorm = matplotlib.colors.Normalize(vmin=minmax[0], vmax=minmax[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
394
395
396
397
398
            else:
                vnorm = lambda x: x

        if (isinstance(ecolor, PropertyMap) and
            ecolor.value_type() != "string"):
399
            minmax = [numpy.inf, -numpy.inf]
Tiago Peixoto's avatar
Tiago Peixoto committed
400
401
402
403
404
405
406
            for e in g.edges():
                c = ecolor[e]
                minmax[0] = min(c, minmax[0])
                minmax[1] = max(c, minmax[1])
            if minmax[0] == minmax[1]:
                minmax[1] += 1
            if enorm:
407
                enorm = matplotlib.colors.Normalize(vmin=minmax[0],
Tiago Peixoto's avatar
Tiago Peixoto committed
408
409
410
411
412
413
414
415
416
417
418
419
                                                    vmax=minmax[1])
            else:
                enorm = lambda x: x

        if vcmap is None:
            vcmap = matplotlib.cm.jet

        if ecmap is None:
            ecmap = matplotlib.cm.jet

        # add nodes
        if vorder is not None:
420
            vertices = sorted(g.vertices(), key = lambda a: vorder[a])
Tiago Peixoto's avatar
Tiago Peixoto committed
421
422
423
        else:
            vertices = g.vertices()
        for v in vertices:
424
            if gv_new_api:
425
                n = libgv.agnode(gvg, str(int(v)).encode("utf8"), 1)
426
            else:
427
                n = libgv.agnode(gvg, str(int(v)).encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
428

429
            if isinstance(vsize, PropertyMap):
Tiago Peixoto's avatar
Tiago Peixoto committed
430
431
432
433
434
435
436
437
438
439
                vw = vh = vsize[v]
            else:
                vw = vh = vsize

            aset(n, "shape", "circle")
            aset(n, "width", "%g" % vw)
            aset(n, "height", "%g" % vh)
            aset(n, "style", "filled")
            aset(n, "color", "#2e3436")
            # apply color
440
441
            if isinstance(vcolor, str):
                aset(n, "fillcolor", vcolor)
Tiago Peixoto's avatar
Tiago Peixoto committed
442
443
            else:
                color = vcolor[v]
444
445
                if isinstance(color, str):
                    aset(n, "fillcolor", color)
Tiago Peixoto's avatar
Tiago Peixoto committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
                else:
                    color = tuple([int(c * 255.0) for c in vcmap(vnorm(color))])
                    aset(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
            aset(n, "label", "")

            # user supplied position
            if pos is not None:
                if isinstance(pin, bool):
                    pin_val = pin
                else:
                    pin_val = pin[v]
                aset(n, "pos", "%f,%f%s" % (pos[0][v], pos[1][v],
                                            "!" if pin_val else ""))
                aset(n, "pin", pin_val)

            # apply all user supplied properties
462
            for k, val in vprops.items():
Tiago Peixoto's avatar
Tiago Peixoto committed
463
464
465
466
467
468
469
                if isinstance(val, PropertyMap):
                    aset(n, k, val[v])
                else:
                    aset(n, k, val)

        # add edges
        if eorder is not None:
470
            edges = sorted(g.edges(), key = lambda a: eorder[a])
Tiago Peixoto's avatar
Tiago Peixoto committed
471
472
473
        else:
            edges = g.edges()
        for e in edges:
474
475
476
477
            if gv_new_api:
                ge = libgv.agedge(gvg,
                                  libgv.agnode(gvg, str(int(e.source())).encode("utf8"), False),
                                  libgv.agnode(gvg, str(int(e.target())).encode("utf8"), False),
478
                                  str(g.edge_index[e]).encode("utf8"), 1)
479
480
481
482
            else:
                ge = libgv.agedge(gvg,
                                  libgv.agnode(gvg, str(int(e.source())).encode("utf8")),
                                  libgv.agnode(gvg, str(int(e.target())).encode("utf8")))
Tiago Peixoto's avatar
Tiago Peixoto committed
483
484
485
            aset(ge, "arrowsize", "0.3")
            if g.is_directed():
                aset(ge, "arrowhead", "vee")
486
487
488
                aset(ge, "dir", "forward")
            else:
                aset(ge, "dir", "none")
Tiago Peixoto's avatar
Tiago Peixoto committed
489
490

            # apply color
491
492
            if isinstance(ecolor, str):
                aset(ge, "color", ecolor)
Tiago Peixoto's avatar
Tiago Peixoto committed
493
494
            else:
                color = ecolor[e]
495
496
                if isinstance(color, str):
                    aset(ge, "color", color)
Tiago Peixoto's avatar
Tiago Peixoto committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
                else:
                    color = tuple([int(c * 255.0) for c in ecmap(enorm(color))])
                    aset(ge, "color", "#%.2x%.2x%.2x%.2x" % color)

            # apply edge length
            if elen is not None:
                if isinstance(elen, PropertyMap):
                    aset(ge, "len", elen[e])
                else:
                    aset(ge, "len", elen)

            # apply width
            if penwidth is not None:
                if isinstance(penwidth, PropertyMap):
                    aset(ge, "penwidth", penwidth[e])
                else:
                    aset(ge, "penwidth", penwidth)

            # apply all user supplied properties
516
            for k, v in eprops.items():
Tiago Peixoto's avatar
Tiago Peixoto committed
517
518
519
520
521
                if isinstance(v, PropertyMap):
                    aset(ge, k, v[e])
                else:
                    aset(ge, k, v)

522
        libgv.gvLayout(gvc, gvg, layout.encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
523
        has_layout = True
524
        retv = libgv.gvRender(gvc, gvg, "dot".encode("utf8"), None)  # retrieve positions only
Tiago Peixoto's avatar
Tiago Peixoto committed
525

Tiago Peixoto's avatar
Tiago Peixoto committed
526
        if pos is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
527
528
529
            pos = (g.new_vertex_property("double"),
                   g.new_vertex_property("double"))
        for v in g.vertices():
530
            n = libgv.agnode(gvg, str(int(v)).encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
            p = aget(n, "pos")
            p = p.split(",")
            pos[0][v] = float(p[0])
            pos[1][v] = float(p[1])

        # I don't get this, but it seems necessary
        pos[0].a /= 100
        pos[1].a /= 100

        pos = group_vector_property(pos)

        if return_string:
            if output_format == "auto":
                output_format = "png"
            if hasattr(libc, "open_memstream"):
                buf = ctypes.c_char_p()
                buf_len = ctypes.c_size_t()
                fstream = libc.open_memstream(ctypes.byref(buf),
                                              ctypes.byref(buf_len))
550
                libgv.gvRender(gvc, gvg, output_format.encode("utf8"), fstream)
Tiago Peixoto's avatar
Tiago Peixoto committed
551
552
553
554
555
556
                libc.fclose(fstream)
                data = copy.copy(ctypes.string_at(buf, buf_len.value))
                libc.free(buf)
            else:
                # write to temporary file, if open_memstream is not available
                output = tempfile.mkstemp()[1]
557
558
                libgv.gvRenderFilename(gvc, gvg, output_format.encode("utf8"),
                                       output.encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
559
560
                data = open(output).read()
                os.remove(output)
Malte R's avatar
Malte R committed
561
        elif output is not None:
Tiago Peixoto's avatar
Tiago Peixoto committed
562
563
564
            if output_format == "auto":
                if output == "":
                    output_format = "xlib"
Malte R's avatar
Malte R committed
565
                else:
Tiago Peixoto's avatar
Tiago Peixoto committed
566
567
568
569
570
571
572
                    output_format = output.split(".")[-1]

            # 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" or fork:
                pid = os.fork()
                if pid == 0:
573
574
                    libgv.gvRenderFilename(gvc, gvg, output_format.encode("utf8"),
                                           output.encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
575
576
577
                    os._exit(0)  # since we forked, it's good to be sure
                if output_format != "xlib":
                    os.wait()
Malte R's avatar
Malte R committed
578
            else:
579
580
                libgv.gvRenderFilename(gvc, gvg, output_format.encode("utf8"),
                                       output.encode("utf8"))
Tiago Peixoto's avatar
Tiago Peixoto committed
581
582
583
584
585
586
587
588
589
590
591
592
593
594

        ret = [pos]
        if return_string:
            ret.append(data)

    finally:
        if has_layout:
            libgv.gvFreeLayout(gvc, gvg)
        libgv.agclose(gvg)

    if len(ret) > 1:
        return tuple(ret)
    else:
        return ret[0]