__init__.py 33.2 KB
Newer Older
Tiago Peixoto's avatar
Tiago Peixoto committed
1
#! /usr/bin/env python
2
# -*- coding: utf-8 -*-
Tiago Peixoto's avatar
Tiago Peixoto committed
3
#
4
5
# graph_tool -- a general graph manipulation python module
#
Tiago Peixoto's avatar
Tiago Peixoto committed
6
# Copyright (C) 2007-2011 Tiago de Paula Peixoto <tiago@skewed.de>
Tiago Peixoto's avatar
Tiago Peixoto committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# 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/>.

21
"""
22
``graph_tool.draw`` - Graph drawing
23
-----------------------------------
24
25
26
27
28
29
30
31

Summary
+++++++

.. autosummary::
   :nosignatures:

   graph_draw
32
   fruchterman_reingold_layout
33
   arf_layout
Tiago Peixoto's avatar
Tiago Peixoto committed
34
   sfdp_layout
35
36
37
38
   random_layout

Contents
++++++++
39
40
"""

41
42
43
44
45
46
47
import sys
import os
import os.path
import time
import warnings
import ctypes
import ctypes.util
48
import tempfile
49
from .. import _degree, _prop, PropertyMap, _check_prop_vector,\
50
     _check_prop_scalar, _check_prop_writable, group_vector_property,\
51
52
     ungroup_vector_property, GraphView
from .. topology import label_components
Tiago Peixoto's avatar
Tiago Peixoto committed
53
from .. decorators import _limit_args
54
import numpy.random
55
from numpy import *
56
import copy
57
58
59

from .. dl_import import dl_import
dl_import("import libgraph_tool_layout")
60

61
62
63
64
65
66
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
67

68
69
70
try:
    libname = ctypes.util.find_library("c")
    libc = ctypes.CDLL(libname)
71
72
    if hasattr(libc, "open_memstream"):
        libc.open_memstream.restype = ctypes.POINTER(ctypes.c_char)
73
74
75
except OSError:
    pass

Tiago Peixoto's avatar
Tiago Peixoto committed
76

77
78
79
80
81
82
83
84
85
86
87
88
try:
    libname = ctypes.util.find_library("gvc")
    if libname is None:
        raise OSError()
    libgv = ctypes.CDLL(libname)
    # 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
89
    libgv.agstrdup_html.restype = ptype
90
91
92
93
94
95
96
97
    # 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()
except OSError:
    warnings.warn("error importing graphviz C library (libgvc)... " + \
                  "graph_draw() will not work.", ImportWarning)


98
__all__ = ["graph_draw", "fruchterman_reingold_layout", "arf_layout",
Tiago Peixoto's avatar
Tiago Peixoto committed
99
           "sfdp_layout", "random_layout", "interactive_window", "cairo_draw"]
100

Tiago Peixoto's avatar
Tiago Peixoto committed
101

102
103
104
105
106
107
def htmlize(val):
    if len(val) >= 2 and val[0] == "<" and val[-1] == ">":
        return ctypes.string_at(libgv.agstrdup_html(val[1:-1]))
    return val


108
def aset(elem, attr, value):
109
    v = htmlize(str(value))
110
111
112
113
114
115
116
    libgv.agsafeset(elem, str(attr), v, v)


def aget(elem, attr):
    return ctypes.string_at(libgv.agget(elem, str(attr)))


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

    Parameters
    ----------
128
129
130
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
    pos : :class:`~graph_tool.PropertyMap` or tuple of :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
131
        Vertex property maps containing the x and y coordinates of the vertices.
132
    size : tuple of scalars (optional, default: ``(15,15)``)
133
        Size (in centimeters) of the canvas.
134
135
136
137
138
139
140
141
    pin : bool or :class:`~graph_tool.PropertyMap` (default: ``False``)
        If ``True``, the vertices are not moved from their initial position. If
        a :class:`~graph_tool.PropertyMap` is passed, it is used to pin nodes
        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``)
142
        If specified, limits the maximum number of iterations.
143
    ratio : string or float (default: ``"fill"``)
144
        Sets the aspect ratio (drawing height/drawing width) for the
145
        drawing. Note that this is adjusted before the ``size`` attribute
146
147
        constraints are enforced.

148
149
        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
150
151
152
        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.

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

157
158
159
160
        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.
161

162
163
164
165
166
167
        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.
168

169
170
        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
171
172
173
174
        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.
175
    overlap : bool or string (default: ``"prism"``)
176
        Determines if and how node overlaps should be removed. Nodes are first
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
        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``)
198
199
        Specifies margin to leave around nodes when removing node overlap. This
        guarantees a minimal non-zero distance between nodes.
200
201
202
203
    splines : bool (default: ``False``)
        If ``True``, the edges are drawn as splines and routed around the
        vertices.
    vsize : float, :class:`~graph_tool.PropertyMap`, or tuple (default: ``0.105``)
204
205
        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.
206
    penwidth : float, :class:`~graph_tool.PropertyMap` or tuple (default: ``1.0``)
207
208
        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
Tiago Peixoto's avatar
Tiago Peixoto committed
209
210
        on text. If a tuple is specified, the first value should be a property
        map, and the second is a scale factor.
211
    elen : float or :class:`~graph_tool.PropertyMap` (default: ``None``)
212
        Preferred edge length, in inches.
213
    gprops : dict (default: ``{}``)
214
215
        Additional graph properties, as a dictionary. The keys are the property
        names, and the values must be convertible to string.
216
    vprops : dict (default: ``{}``)
217
218
219
        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.
220
    eprops : dict (default: ``{}``)
221
222
223
        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.
224
    vcolor : string or :class:`~graph_tool.PropertyMap` (default: ``"#a40000"``)
225
226
        Drawing color for vertices. If the valued supplied is a property map,
        the values must be scalar types, whose color values are obtained from
227
228
        the ``vcmap`` argument.
    ecolor : string or :class:`~graph_tool.PropertyMap` (default: ``"#2e3436"``)
229
230
        Drawing color for edges. If the valued supplied is a property map,
        the values must be scalar types, whose color values are obtained from
231
232
        the ``ecmap`` argument.
    vcmap : :class:`matplotlib.colors.Colormap` (default: :class:`matplotlib.cm.jet`)
233
        Vertex color map.
234
    vnorm : bool (default: ``True``)
235
        Normalize vertex color values to the [0,1] range.
236
    ecmap : :class:`matplotlib.colors.Colormap` (default: :class:`matplotlib.cm.jet`)
237
        Edge color map.
238
    enorm : bool (default: ``True``)
239
        Normalize edge color values to the [0,1] range.
240
    vorder : :class:`~graph_tool.PropertyMap` (default: ``None``)
241
242
        Scalar vertex property map which specifies the order with which vertices
        are drawn.
243
    eorder : :class:`~graph_tool.PropertyMap` (default: ``None``)
244
245
        Scalar edge property map which specifies the order with which edges
        are drawn.
246
    output : string (default: ``""``)
247
        Output file name.
248
249
250
251
252
253
254
255
256
257
258
259
260
261
    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``
        parameter, or ``xlib`` if it is empty. If the value is ``None``, no
        output is produced.
    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
262
        returned (defaults to png format).
263
264
265

    Returns
    -------
266
    pos : :class:`~graph_tool.PropertyMap`
267
        Vector vertex property map with the x and y coordinates of the vertices.
268
    gv : gv.digraph or gv.graph (optional, only if ``returngv == True``)
269
270
271
272
273
        Internally used graphviz graph.


    Notes
    -----
274
275
276
    This function is a wrapper for the [graphviz] routines. Extensive additional
    documentation for the graph, vertex and edge properties is available at:
    http://www.graphviz.org/doc/info/attrs.html.
277
278
279
280


    Examples
    --------
281
    >>> from numpy import *
282
283
284
    >>> from numpy.random import seed, zipf
    >>> seed(42)
    >>> g = gt.random_graph(1000, lambda: min(zipf(2.4), 40),
285
    ...                     lambda i, j: exp(abs(i - j)), directed=False)
286
    >>> # extract largest component
287
    >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
288
    >>> deg = g.degree_property_map("out")
289
    >>> deg.a = 2 * (sqrt(deg.a) * 0.5 + 0.4)
290
    >>> ebet = gt.betweenness(g)[1]
291
292
293
294
    >>> ebet.a *= 4000
    >>> ebet.a += 10
    >>> gt.graph_draw(g, vsize=deg, vcolor=deg, vorder=deg, elen=10,
    ...               ecolor=ebet, eorder=ebet, penwidth=ebet,
295
    ...               overlap="prism", output="graph-draw.pdf")
296
    <...>
297

298
    .. figure:: graph-draw.*
299
300
301
302
303
304
305
306
307
        :align: center

        Kamada-Kawai force-directed layout of a graph with a power-law degree
        distribution, and dissortative degree correlation. The vertex size and
        color indicate the degree, and the edge color and width the edge
        betweeness centrality.

    References
    ----------
308
    .. [graphviz] http://www.graphviz.org
309
310

    """
Tiago Peixoto's avatar
Tiago Peixoto committed
311

312
    if output != "" and output is not None:
313
        output = os.path.expanduser(output)
314
        # check opening file for writing, since graphviz will bork if it is not
315
316
317
318
319
        # 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))

320
321
322
    has_layout = False
    try:
        gvg = libgv.agopen("G", 1 if g.is_directed() else 0)
323

324
        if layout is None:
325
326
327
328
            if pin == False:
                layout = "neato" if g.num_vertices() <= 1000 else "sfdp"
            else:
                layout = "neato"
329

330
331
332
333
        if layout == "arf":
            layout = "neato"
            pos = arf_layout(g, pos=pos)
            pin = True
Tiago Peixoto's avatar
Tiago Peixoto committed
334

335
        if pos is not None:
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
            # 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")
357
358
        if type(overlap) is bool:
            overlap = "true" if overlap else "false"
359
        else:
360
361
362
            overlap = str(overlap)
        aset(gvg, "overlap", overlap)
        if sep is not None:
363
364
365
366
367
368
            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))
369
        if maxiter is not None:
370
371
372
373
374
375
376
377
378
379
380
381
382
            aset(gvg, "maxiter", maxiter)

        seed = numpy.random.randint(sys.maxint)
        aset(gvg, "start", "%d" % seed)

        # apply all user supplied graph properties
        for k, val in gprops.iteritems():
            if isinstance(val, PropertyMap):
                aset(gvg, k, val[g])
            else:
                aset(gvg, k, val)

        # normalize color properties
383
384
        if (isinstance(vcolor, PropertyMap) and
            vcolor.value_type() != "string"):
385
386
387
388
389
390
391
392
393
394
395
396
            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 minmax[0] == minmax[1]:
                minmax[1] += 1
            if vnorm:
                vnorm = matplotlib.colors.normalize(vmin=minmax[0], vmax=minmax[1])
            else:
                vnorm = lambda x: x

397
398
        if (isinstance(ecolor, PropertyMap) and
            ecolor.value_type() != "string"):
399
400
401
402
403
404
405
406
407
408
409
410
            minmax = [float("inf"), -float("inf")]
            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:
                enorm = matplotlib.colors.normalize(vmin=minmax[0],
                                                    vmax=minmax[1])
            else:
                enorm = lambda x: x
411

412
413
        if vcmap is None:
            vcmap = matplotlib.cm.jet
Tiago Peixoto's avatar
Tiago Peixoto committed
414

415
416
        if ecmap is None:
            ecmap = matplotlib.cm.jet
417

418
        # add nodes
419
        if vorder is not None:
420
            vertices = sorted(g.vertices(), lambda a, b: cmp(vorder[a], vorder[b]))
421
        else:
422
423
424
            vertices = g.vertices()
        for v in vertices:
            n = libgv.agnode(gvg, str(int(v)))
Tiago Peixoto's avatar
Tiago Peixoto committed
425

426
427
            if type(vsize) == PropertyMap:
                vw = vh = vsize[v]
Tiago Peixoto's avatar
Tiago Peixoto committed
428
            else:
429
430
431
432
433
434
                vw = vh = vsize

            aset(n, "shape", "circle")
            aset(n, "width", "%g" % vw)
            aset(n, "height", "%g" % vh)
            aset(n, "style", "filled")
435
            aset(n, "color", "#2e3436")
436
437
438
439
            # apply color
            if isinstance(vcolor, str):
                aset(n, "fillcolor", vcolor)
            else:
440
441
442
443
444
445
                color = vcolor[v]
                if isinstance(color, str):
                    aset(n, "fillcolor", color)
                else:
                    color = tuple([int(c * 255.0) for c in vcmap(vnorm(color))])
                    aset(n, "fillcolor", "#%.2x%.2x%.2x%.2x" % color)
446
447
448
            aset(n, "label", "")

            # user supplied position
449
            if pos is not None:
450
451
452
453
454
455
456
                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)
457
458
459
460
461
462
463
464
465

            # apply all user supplied properties
            for k, val in vprops.iteritems():
                if isinstance(val, PropertyMap):
                    aset(n, k, val[v])
                else:
                    aset(n, k, val)

        # add edges
466
        if eorder is not None:
467
            edges = sorted(g.edges(), lambda a, b: cmp(eorder[a], eorder[b]))
468
        else:
469
470
471
472
473
474
475
476
477
478
479
480
            edges = g.edges()
        for e in edges:
            ge = libgv.agedge(gvg,
                              libgv.agnode(gvg, str(int(e.source()))),
                              libgv.agnode(gvg, str(int(e.target()))))
            aset(ge, "arrowsize", "0.3")
            if g.is_directed():
                aset(ge, "arrowhead", "vee")

            # apply color
            if isinstance(ecolor, str):
                aset(ge, "color", ecolor)
Tiago Peixoto's avatar
Tiago Peixoto committed
481
            else:
482
483
484
485
486
487
                color = ecolor[e]
                if isinstance(color, str):
                    aset(ge, "color", color)
                else:
                    color = tuple([int(c * 255.0) for c in ecmap(enorm(color))])
                    aset(ge, "color", "#%.2x%.2x%.2x%.2x" % color)
488
489

            # apply edge length
490
            if elen is not None:
491
492
493
494
495
496
                if isinstance(elen, PropertyMap):
                    aset(ge, "len", elen[e])
                else:
                    aset(ge, "len", elen)

            # apply width
497
            if penwidth is not None:
498
499
500
501
502
503
504
505
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
532
                if isinstance(penwidth, PropertyMap):
                    aset(ge, "penwidth", penwidth[e])
                else:
                    aset(ge, "penwidth", penwidth)

            # apply all user supplied properties
            for k, v in eprops.iteritems():
                if isinstance(v, PropertyMap):
                    aset(ge, k, v[e])
                else:
                    aset(ge, k, v)

        libgv.gvLayout(gvc, gvg, layout)
        has_layout = True
        retv = libgv.gvRender(gvc, gvg, "dot", None)  # retrieve positions only

        if pos == None:
            pos = (g.new_vertex_property("double"),
                   g.new_vertex_property("double"))
        for v in g.vertices():
            n = libgv.agnode(gvg, str(int(v)))
            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"
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
            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))
                libgv.gvRender(gvc, gvg, output_format, fstream)
                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]
                libgv.gvRenderFilename(gvc, gvg, output_format, output)
                data = open(output).read()
                os.remove(output)
548
549
550
551
        else:
            if output_format == "auto":
                if output == "":
                    output_format = "xlib"
552
                elif output is not None:
553
554
555
556
557
558
559
560
561
562
563
                    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:
                    libgv.gvRenderFilename(gvc, gvg, output_format, output)
                    os._exit(0)  # since we forked, it's good to be sure
                if output_format != "xlib":
                    os.wait()
564
            elif output is not None:
565
                libgv.gvRenderFilename(gvc, gvg, output_format, output)
Tiago Peixoto's avatar
Tiago Peixoto committed
566

567
568
569
        ret = [pos]
        if return_string:
            ret.append(data)
Tiago Peixoto's avatar
Tiago Peixoto committed
570

571
572
573
574
    finally:
        if has_layout:
            libgv.gvFreeLayout(gvc, gvg)
        libgv.agclose(gvg)
575
576
577
578
579

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

Tiago Peixoto's avatar
Tiago Peixoto committed
581

582
def random_layout(g, shape=None, pos=None, dim=2):
583
584
585
586
    r"""Performs a random layout of the graph.

    Parameters
    ----------
587
    g : :class:`~graph_tool.Graph`
588
        Graph to be used.
589
    shape : tuple or list (optional, default: ``None``)
Tiago Peixoto's avatar
Tiago Peixoto committed
590
591
592
593
        Rectangular shape of the bounding area. The size of this parameter must
        match `dim`, and each element can be either a pair specifying a range,
        or a single value specifying a range starting from zero. If None is
        passed, a square of linear size :math:`\sqrt{N}` is used.
594
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
595
        Vector vertex property maps where the coordinates should be stored.
596
    dim : int (optional, default: ``2``)
597
598
599
600
        Number of coordinates per vertex.

    Returns
    -------
601
602
603
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.
604
605
606
607

    Notes
    -----
    This algorithm has complexity :math:`O(V)`.
Tiago Peixoto's avatar
Tiago Peixoto committed
608
609
610
611
612
613
614
615
616
617
618

    Examples
    --------
    >>> from numpy.random import seed
    >>> seed(42)
    >>> g = gt.random_graph(100, lambda: (3, 3))
    >>> shape = [[50, 100], [1, 2], 4]
    >>> pos = gt.random_layout(g, shape=shape, dim=3)
    >>> pos[g.vertex(0)].a
    array([ 86.59969709,   1.31435598,   0.64651486])

619
620
    """

621
    if pos == None:
Tiago Peixoto's avatar
Tiago Peixoto committed
622
623
        pos = g.new_vertex_property("vector<double>")
    _check_prop_vector(pos, name="pos")
624

Tiago Peixoto's avatar
Tiago Peixoto committed
625
    pos = ungroup_vector_property(pos, range(0, dim))
626
627

    if shape == None:
Tiago Peixoto's avatar
Tiago Peixoto committed
628
        shape = [sqrt(g.num_vertices())] * dim
629
630

    for i in xrange(dim):
Tiago Peixoto's avatar
Tiago Peixoto committed
631
632
633
634
635
636
637
        if hasattr(shape[i], "__len__"):
            if len(shape[i]) != 2:
                raise ValueError("The elements of 'shape' must have size 2.")
            r = [min(shape[i]), max(shape[i])]
        else:
            r = [min(shape[i], 0), max(shape[i], 0)]
        d = r[1] - r[0]
638
639
640
641

        # deal with filtering
        p = pos[i].ma
        p[:] = numpy.random.random(len(p)) * d + r[0]
642

Tiago Peixoto's avatar
Tiago Peixoto committed
643
    pos = group_vector_property(pos)
644
645
    return pos

Tiago Peixoto's avatar
Tiago Peixoto committed
646

647
648
649
650
651
652
653
def fruchterman_reingold_layout(g, weight=None, a=None, r=1., scale=None,
                                circular=False, grid=True, t_range=None,
                                n_iter=100, pos=None):
    r"""Calculate the Fruchterman-Reingold spring-block layout of the graph.

    Parameters
    ----------
654
    g : :class:`~graph_tool.Graph`
655
        Graph to be used.
656
    weight : :class:`PropertyMap` (optional, default: ``None``)
657
658
659
660
661
662
663
        An edge property map with the respective weights.
    a : float (optional, default: :math:`V`)
        Attracting force between adjacent vertices.
    r : float (optional, default: 1.0)
        Repulsive force between vertices.
    scale : float (optional, default: :math:`\sqrt{V}`)
        Total scale of the layout (either square side or radius).
664
665
    circular : bool (optional, default: ``False``)
        If ``True``, the layout will have a circular shape. Otherwise the shape
666
        will be a square.
667
668
    grid : bool (optional, default: ``True``)
        If ``True``, the repulsive forces will only act on vertices which are on
669
        the same site on a grid. Otherwise they will act on all vertex pairs.
670
    t_range : tuple of floats (optional, default: ``(scale / 10, scale / 1000)``)
671
672
        Temperature range used in annealing. The temperature limits the
        displacement at each iteration.
673
    n_iter : int (optional, default: ``100``)
674
        Total number of iterations.
675
    pos : :class:`PropertyMap` (optional, default: ``None``)
676
677
678
679
680
681
        Vector vertex property maps where the coordinates should be stored. If
        provided, this will also be used as the initial position of the
        vertices.

    Returns
    -------
682
683
684
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.
685
686
687
688

    Notes
    -----
    This algorithm is defined in [fruchterman-reingold]_, and has
Tiago Peixoto's avatar
Tiago Peixoto committed
689
690
    complexity :math:`O(\text{n-iter}\times V^2)` if `grid=False` or
    :math:`O(\text{n-iter}\times (V + E))` otherwise.
691
692
693
694
695
696
697

    Examples
    --------
    >>> from numpy.random import seed, zipf
    >>> seed(42)
    >>> g = gt.price_network(300)
    >>> pos = gt.fruchterman_reingold_layout(g, n_iter=1000)
698
    >>> gt.graph_draw(g, pos=pos, pin=True, output="graph-draw-fr.pdf")
699
700
    <...>

701
    .. figure:: graph-draw-fr.*
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
        :align: center

        Fruchterman-Reingold layout of a Price network.

    References
    ----------
    .. [fruchterman-reingold] Fruchterman, Thomas M. J.; Reingold, Edward M.
       "Graph Drawing by Force-Directed Placement". Software – Practice & Experience
       (Wiley) 21 (11): 1129–1164. (1991) :doi:`10.1002/spe.4380211102`
    """

    if pos == None:
        pos = random_layout(g, dim=2)
    _check_prop_vector(pos, name="pos", floating=True)

    if a is None:
        a = float(g.num_vertices())

    if scale is None:
        scale = sqrt(g.num_vertices())

    if t_range is None:
        t_range = (scale / 10, scale / 1000)

    ug = GraphView(g, directed=False)
    libgraph_tool_layout.fruchterman_reingold_layout(ug._Graph__graph,
                                                     _prop("v", g, pos),
                                                     _prop("e", g, weight),
                                                     a, r, not circular, scale,
                                                     grid, t_range[0],
                                                     t_range[1], n_iter)
    return pos


def arf_layout(g, weight=None, d=0.5, a=10, dt=0.001, epsilon=1e-6,
737
               max_iter=1000, pos=None, dim=2):
738
739
    r"""Calculate the ARF spring-block layout of the graph.

Tiago Peixoto's avatar
Tiago Peixoto committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weight : :class:`~graph_tool.PropertyMap` (optional,
    default: ``None``) An edge property map with the respective weights. d : float (optional, default: ``0.5``) Opposing force between vertices. a : float (optional, default: ``10``) Attracting force between adjacent vertices. dt : float (optional, default: ``0.001``) Iteration step size. epsilon : float (optional, default: ``1e-6``) Convergence criterion. max_iter : int (optional, default: ``1000``) Maximum number of iterations. If this value is ``0``, it runs until convergence. pos : :class:` ~ graph_tool.PropertyMap` (optional, default: ``None``) Vector vertex property maps where the coordinates should be stored. dim : int (optional, default: ``2``) Number of coordinates per vertex.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm is defined in [geipel-self-organization-2007]_, and has
    complexity :math:`O(V^2)`.

    Examples
    --------
    >>> from numpy.random import seed, zipf
    >>> seed(42)
    >>> g = gt.price_network(300)
    >>> pos = gt.arf_layout(g, max_iter=0)
    >>> gt.graph_draw(g, pos=pos, pin=True, output="graph-draw-arf.pdf")
    <...>

    .. figure:: graph-draw-arf.*
        :align: center

        ARF layout of a Price network.

    References
    ----------
    .. [geipel-self-organization-2007] Markus M. Geipel, "Self-Organization
       applied to Dynamic Network Layout", International Journal of Modern
       Physics C vol. 18, no. 10 (2007), pp. 1537-1549,
       :doi:`10.1142/S0129183107011558`, :arxiv:`0704.1748v5`
    .. _arf: http://www.sg.ethz.ch/research/graphlayout
    """

    if pos is None:
        if dim != 2:
            pos = random_layout(g, dim=dim)
        else:
            pos = graph_draw(g, output=None)
    _check_prop_vector(pos, name="pos", floating=True)

    ug = GraphView(g, directed=False)
    libgraph_tool_layout.arf_layout(ug._Graph__graph, _prop("v", g, pos),
                                    _prop("e", g, weight), d, a, dt, max_iter,
                                    epsilon, dim)
    return pos


def sfdp_layout(g, weight=None, pin=None, C=0.2, K=None, p=2., theta=1.2,
                init_step=None, step_schedule=0.9, max_level=9, epsilon=1e-8,
                max_iter=0, pos=None, verbose=False):
    r"""Calculate the sfdp spring-block layout of the graph.

800
801
    Parameters
    ----------
802
    g : :class:`~graph_tool.Graph`
803
        Graph to be used.
804
    weight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
805
        An edge property map with the respective weights.
806
    epsilon : float (optional, default: ``1e-6``)
807
        Convergence criterion.
808
809
    max_iter : int (optional, default: ``1000``)
        Maximum number of iterations. If this value is ``0``, it runs until
810
        convergence.
811
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
812
813
814
815
        Vector vertex property maps where the coordinates should be stored.

    Returns
    -------
816
817
818
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.
819
820
821

    Notes
    -----
822
    This algorithm is defined in [geipel-self-organization-2007]_, and has
823
824
825
826
827
828
    complexity :math:`O(V^2)`.

    Examples
    --------
    >>> from numpy.random import seed, zipf
    >>> seed(42)
829
830
    >>> g = gt.price_network(300)
    >>> pos = gt.arf_layout(g, max_iter=0)
831
    >>> gt.graph_draw(g, pos=pos, pin=True, output="graph-draw-arf.pdf")
832
833
    <...>

834
    .. figure:: graph-draw-arf.*
835
836
        :align: center

837
        ARF layout of a Price network.
838
839
840

    References
    ----------
841
    .. [geipel-self-organization-2007] Markus M. Geipel, "Self-Organization
842
843
844
       applied to Dynamic Network Layout", International Journal of Modern
       Physics C vol. 18, no. 10 (2007), pp. 1537-1549,
       :doi:`10.1142/S0129183107011558`, :arxiv:`0704.1748v5`
845
846
847
    .. _arf: http://www.sg.ethz.ch/research/graphlayout
    """

848
    if pos is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
849
        pos = random_layout(g, dim=2)
850
851
    _check_prop_vector(pos, name="pos", floating=True)

Tiago Peixoto's avatar
Tiago Peixoto committed
852
853
854
855
856
857
858
859
860
861
862
863
    if pin is not None and pin.value_type() != "bool":
        raise ValueError("'pin' property must be of type 'bool'.")

    if K is None:
        px, py = ungroup_vector_property(pos, [0, 1])
        K = sqrt((px.a.max() -  px.a.min()) * (py.a.max() -  py.a.min()) /
                 g.num_vertices())

    if init_step is None:
        px, py = ungroup_vector_property(pos, [0, 1])
        init_step = sqrt((px.a.max() -  px.a.min()) * (py.a.max() -  py.a.min())) / 10

864
    ug = GraphView(g, directed=False)
Tiago Peixoto's avatar
Tiago Peixoto committed
865
866
867
868
    libgraph_tool_layout.fdp_layout(ug._Graph__graph, _prop("v", g, pos),
                                    _prop("e", g, weight), _prop("v", g, pin),
                                    C, K, p, theta, init_step, step_schedule,
                                    max_level, epsilon, max_iter, verbose)
869
    return pos
Tiago Peixoto's avatar
Tiago Peixoto committed
870
871
872


from cairo_draw import *