cairo_draw.py 93.5 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-2015 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
from __future__ import division, absolute_import, print_function
22
23
24
import sys
if sys.version_info < (3,):
    range = xrange
25

Tiago Peixoto's avatar
Tiago Peixoto committed
26
27
import os
import warnings
28
import numpy
Tiago Peixoto's avatar
Tiago Peixoto committed
29

30
from .. topology import shortest_distance, is_bipartite
31

Tiago Peixoto's avatar
Tiago Peixoto committed
32
33
34
try:
    import cairo
except ImportError:
35
    msg = "Error importing cairo. Graph drawing will not work."
36
    warnings.warn(msg, RuntimeWarning)
37
    raise
Tiago Peixoto's avatar
Tiago Peixoto committed
38

Tiago Peixoto's avatar
Tiago Peixoto committed
39
default_cm = None
Tiago Peixoto's avatar
Tiago Peixoto committed
40
try:
41
42
    import matplotlib.artist
    import matplotlib.backends.backend_cairo
43
44
    import matplotlib.cm
    import matplotlib.colors
45
    from matplotlib.cbook import flatten
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    default_clrs = [(0.5529411764705883, 0.8274509803921568, 0.7803921568627451, 1.0),
                    #(1.0, 1.0, 0.7019607843137254, 1.0),
                    (0.7450980392156863, 0.7294117647058823, 0.8549019607843137, 1.0),
                    (0.984313725490196, 0.5019607843137255, 0.4470588235294118, 1.0),
                    (0.5019607843137255, 0.6941176470588235, 0.8274509803921568, 1.0),
                    (0.9921568627450981, 0.7058823529411765, 0.3843137254901961, 1.0),
                    (0.7019607843137254, 0.8705882352941177, 0.4117647058823529, 1.0),
                    (0.9882352941176471, 0.803921568627451, 0.8980392156862745, 1.0),
                    (0.8509803921568627, 0.8509803921568627, 0.8509803921568627, 1.0),
                    (0.7372549019607844, 0.5019607843137255, 0.7411764705882353, 1.0),
                    (0.8, 0.9215686274509803, 0.7725490196078432, 1.0),
                    (1.0, 0.9294117647058824, 0.43529411764705883, 1.0)]
    default_cm = matplotlib.colors.LinearSegmentedColormap.from_list("Set3",
                                                                     default_clrs)
60
    is_draw_inline = 'inline' in matplotlib.get_backend()
61
    color_converter = matplotlib.colors.ColorConverter()
Tiago Peixoto's avatar
Tiago Peixoto committed
62
except ImportError:
63
    msg = "Error importing matplotlib module. Graph drawing will not work."
64
    warnings.warn(msg, RuntimeWarning)
65
    raise
Tiago Peixoto's avatar
Tiago Peixoto committed
66

67
68
try:
    import IPython.display
Tiago Peixoto's avatar
Tiago Peixoto committed
69
except ImportError:
70
71
    pass

Tiago Peixoto's avatar
Tiago Peixoto committed
72
73
74
75
import numpy as np
import gzip
import bz2
import zipfile
76
import copy
77
import io
Tiago Peixoto's avatar
Tiago Peixoto committed
78
79
from collections import defaultdict

80
from .. import Graph, GraphView, PropertyMap, ungroup_vector_property,\
81
     group_vector_property, _prop, _check_prop_vector, map_property_values
82

Tiago Peixoto's avatar
Tiago Peixoto committed
83
84
85
from .. stats import label_parallel_edges, label_self_loops

from .. dl_import import dl_import
86
dl_import("from . import libgraph_tool_draw")
Tiago Peixoto's avatar
Tiago Peixoto committed
87
try:
88
    from .libgraph_tool_draw import vertex_attrs, edge_attrs, vertex_shape,\
Tiago Peixoto's avatar
Tiago Peixoto committed
89
90
        edge_marker
except ImportError:
91
92
    msg = "Error importing cairo-based drawing library. " + \
        "Was graph-tool compiled with cairomm support?"
93
    warnings.warn(msg, RuntimeWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
94
95

from .. draw import sfdp_layout, random_layout, _avg_edge_distance, \
96
97
98
99
    coarse_graphs, radial_tree_layout, prop_to_size

from .. generation import graph_union
from .. topology import shortest_path
Tiago Peixoto's avatar
Tiago Peixoto committed
100
101
102

_vdefaults = {
    "shape": "circle",
103
104
    "color": (0.6, 0.6, 0.6, 0.8),
    "fill_color": (0.6470588235294118, 0.058823529411764705, 0.08235294117647059, 0.8),
Tiago Peixoto's avatar
Tiago Peixoto committed
105
    "size": 5,
106
    "aspect": 1.,
107
    "rotation": 0.,
108
    "anchor": 1,
Tiago Peixoto's avatar
Tiago Peixoto committed
109
110
111
    "pen_width": 0.8,
    "halo": 0,
    "halo_color": [0., 0., 1., 0.5],
112
    "halo_size": 1.5,
Tiago Peixoto's avatar
Tiago Peixoto committed
113
114
115
    "text": "",
    "text_color": [0., 0., 0., 1.],
    "text_position": -1.,
116
117
    "text_rotation": 0.,
    "text_offset": [0., 0.],
Tiago Peixoto's avatar
Tiago Peixoto committed
118
119
120
    "font_family": "serif",
    "font_slant": cairo.FONT_SLANT_NORMAL,
    "font_weight": cairo.FONT_WEIGHT_NORMAL,
121
    "font_size": 12.,
122
123
    "surface": None,
    "pie_fractions": [0.75, 0.25],
124
    "pie_colors": default_clrs # ('b', 'g', 'r', 'c', 'm', 'y', 'k')
Tiago Peixoto's avatar
Tiago Peixoto committed
125
126
127
    }

_edefaults = {
128
    "color": (0.1796875, 0.203125, 0.2109375, 0.8),
Tiago Peixoto's avatar
Tiago Peixoto committed
129
130
131
132
133
    "pen_width": 1,
    "start_marker": "none",
    "mid_marker": "none",
    "end_marker": "none",
    "marker_size": 4.,
134
    "mid_marker_pos": .5,
Tiago Peixoto's avatar
Tiago Peixoto committed
135
    "control_points": [],
Tiago Peixoto's avatar
Tiago Peixoto committed
136
    "gradient": [],
137
    "dash_style": [],
138
    "text": "",
139
    "text_color": (0., 0., 0., 1.),
140
141
142
143
144
145
    "text_distance": 5,
    "text_parallel": True,
    "font_family": "serif",
    "font_slant": cairo.FONT_SLANT_NORMAL,
    "font_weight": cairo.FONT_WEIGHT_NORMAL,
    "font_size": 12.,
146
147
    "sloppy": False,
    "seamless": False
Tiago Peixoto's avatar
Tiago Peixoto committed
148
149
    }

150
151
152
153
154
155
_vtypes = {
    "shape": "int",
    "color": "vector<double>",
    "fill_color": "vector<double>",
    "size": "double",
    "aspect": "double",
156
    "rotation": "double",
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
200
201
202
203
204
    "anchor": "double",
    "pen_width": "double",
    "halo": "bool",
    "halo_color": "vector<double>",
    "halo_size": "double",
    "text": "string",
    "text_color": "vector<double>",
    "text_position": "double",
    "text_rotation": "double",
    "text_offset": "vector<double>",
    "font_family": "string",
    "font_slant": "int",
    "font_weight": "int",
    "font_size": "float",
    "surface": "object",
    "pie_fractions": "vector<double>",
    "pie_colors": "vector<double>"
    }

_etypes = {
    "color": "vector<double>",
    "pen_width": "double",
    "start_marker": "int",
    "mid_marker": "int",
    "end_marker": "int",
    "marker_size": "double",
    "mid_marker_pos": "double",
    "control_points": "vector<double>",
    "gradient": "vector<double>",
    "dash_style": "vector<double>",
    "text": "string",
    "text_color": "vector<double>",
    "text_distance": "double",
    "text_parallel": "bool",
    "font_family": "string",
    "font_slant": "int",
    "font_weight": "int",
    "font_size": "double",
    "sloppy": "bool",
    "seamless": "bool"
    }

for k in list(_vtypes.keys()):
    _vtypes[getattr(vertex_attrs, k)] = _vtypes[k]

for k in list(_etypes.keys()):
    _etypes[getattr(edge_attrs, k)] = _etypes[k]

Tiago Peixoto's avatar
Tiago Peixoto committed
205
206
207

def shape_from_prop(shape, enum):
    if isinstance(shape, PropertyMap):
208
        g = shape.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
209
        if shape.key_type() == "v":
210
211
            prop = g.new_vertex_property("int")
            descs = g.vertices()
Tiago Peixoto's avatar
Tiago Peixoto committed
212
        else:
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
            descs = g.edges()
            prop = g.new_edge_property("int")
        if shape.value_type() == "string":
            def conv(x):
                return int(getattr(enum, x))
            map_property_values(shape, prop, conv)
        else:
            rg = (min(enum.values.keys()),
                  max(enum.values.keys()))
            g.copy_property(shape, prop)
            if prop.fa.min() < rg[0]:
                prop.fa += rg[0]
            prop.fa -= rg[0]
            prop.fa %= rg[1] - rg[0] + 1
            prop.fa += rg[0]
Tiago Peixoto's avatar
Tiago Peixoto committed
228
229
        return prop
    if isinstance(shape, str):
230
        return int(getattr(enum, shape))
Tiago Peixoto's avatar
Tiago Peixoto committed
231
232
233
234
235
236
    else:
        return shape

    raise ValueError("Invalid value for attribute %s: %s" %
                     (repr(enum), repr(shape)))

237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def open_file(name, mode="r"):
    name = os.path.expanduser(name)
    base, ext = os.path.splitext(name)
    if ext == ".gz":
        out = gzip.GzipFile(name, mode)
        name = base
    elif ext == ".bz2":
        out = bz2.BZ2File(name, mode)
        name = base
    elif ext == ".zip":
        out = zipfile.ZipFile(name, mode)
        name = base
    else:
        out = open(name, mode)
    fmt = os.path.splitext(name)[1].replace(".", "")
252
    return out, fmt
253

254
255
256
257
258
259
260
261
262
263
264
265
def get_file_fmt(name):
    name = os.path.expanduser(name)
    base, ext = os.path.splitext(name)
    if ext == ".gz":
        name = base
    elif ext == ".bz2":
        name = base
    elif ext == ".zip":
        name = base
    fmt = os.path.splitext(name)[1].replace(".", "")
    return fmt

266
267
268
269
270
271
272
273
274
275
276
277
278
279
280

def surface_from_prop(surface):
    if isinstance(surface, PropertyMap):
        if surface.key_type() == "v":
            prop = surface.get_graph().new_vertex_property("object")
            descs = surface.get_graph().vertices()
        else:
            descs = surface.get_graph().edges()
            prop = surface.get_graph().new_edge_property("object")
        surface_map = {}
        for v in descs:
            if surface.value_type() == "string":
                if surface[v] not in surface_map:
                    sfc = gen_surface(surface[v])
                    surface_map[surface[v]] = sfc
281
                prop[v] = surface_map[surface[v]]
282
283
284
            elif surface.value_type() == "python::object":
                if isinstance(surface[v], cairo.Surface):
                    prop[v] = surface[v]
285
                elif surface[v] is not None:
286
287
288
289
290
291
292
293
294
295
296
297
298
299
                    raise ValueError("Invalid value type for surface property: " +
                                     str(type(surface[v])))
            else:
                raise ValueError("Invalid value type for surface property: " +
                                 surface.value_type())
        return prop

    if isinstance(surface, str):
        return gen_surface(surface)
    elif isinstance(surface, cairo.Surface) or surface is None:
        return surface

    raise ValueError("Invalid value for attribute surface: " + repr(surface))

300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def centered_rotation(g, pos, text_pos=True):
    x, y = ungroup_vector_property(pos, [0, 1])
    cm = (x.fa.mean(), y.fa.mean())
    dx = x.fa - cm[0]
    dy = y.fa - cm[0]
    angle = g.new_vertex_property("double")
    angle.fa = numpy.arctan2(dy, dx)
    pi = numpy.pi
    angle.fa += 2 * pi
    angle.fa %= 2 * pi
    if text_pos:
        idx = (angle.a > pi / 2 ) * (angle.a < 3 * pi / 2)
        tpos = g.new_vertex_property("double")
        angle.a[idx] += pi
        tpos.a[idx] = pi
        return angle, tpos
    return angle
Tiago Peixoto's avatar
Tiago Peixoto committed
317

318
def _convert(attr, val, cmap, pmap_default=False, g=None, k=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
319
    if attr == vertex_attrs.shape:
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
        new_val = shape_from_prop(val, vertex_shape)
        if pmap_default and not isinstance(val, PropertyMap):
            new_val = g.new_vertex_property("int", new_val)
        return new_val
    elif attr == vertex_attrs.surface:
        new_val = surface_from_prop(val)
        if pmap_default and not isinstance(val, PropertyMap):
            new_val = g.new_vertex_property("python::object", new_val)
        return new_val
    elif attr in [edge_attrs.start_marker, edge_attrs.mid_marker,
                  edge_attrs.end_marker]:
        new_val = shape_from_prop(val, edge_marker)
        if pmap_default and not isinstance(val, PropertyMap):
            new_val = g.new_edge_property("int", new_val)
        return new_val
    elif attr in [vertex_attrs.pie_colors]:
336
337
338
        if isinstance(val, PropertyMap):
            if val.value_type() in ["vector<double>", "vector<long double>"]:
                return val
339
            if val.value_type() in ["vector<int32_t>", "vector<int64_t>", "vector<bool>"]:
340
341
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
342
                rg = [numpy.inf, -numpy.inf]
343
344
                for v in g.vertices():
                    for x in val[v]:
345
346
                        rg[0] = min(x, rg[0])
                        rg[1] = max(x, rg[1])
347
348
                if rg[0] == rg[1]:
                    rg[1] = 1
349
350
                map_property_values(val, new_val,
                                    lambda y: flatten([cmap((x - rg[0]) / (rg[1] - rg[0])) for x in y]))
351
                return new_val
352
353
354
            if val.value_type() == "vector<string>":
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
355
356
                map_property_values(val, new_val,
                                    lambda y: flatten([color_converter.to_rgba(x) for x in y]))
357
358
359
360
361
                return new_val
            if val.value_type() == "python::object":
                try:
                    g = val.get_graph()
                    new_val = g.new_vertex_property("vector<double>")
362
                    def conv(y):
363
                        try:
364
                            new_val[v] = [float(x) for x in flatten(y)]
365
                        except ValueError:
366
367
                            new_val[v] = flatten([color_converter.to_rgba(x) for x in y])
                    map_property_values(val, new_val, conv)
368
369
370
371
372
                    return new_val
                except ValueError:
                    pass
        else:
            try:
373
                new_val = [float(x) for x in flatten(val)]
374
375
            except ValueError:
                try:
376
377
                    new_val = flatten(color_convert.to_rgba(x) for x in val)
                    new_val = list(new_val)
378
379
                except ValueError:
                    pass
380
381
382
383
384
385
386
387
388
389
            if pmap_default:
                val_a = numpy.zeros((g.num_vertices(), len(new_val)))
                for i in range(len(new_val)):
                    val_a[:, i] = new_val[i]
                return g.new_vertex_property("vector<double>", val_a)
            else:
                return new_val
    elif attr in [vertex_attrs.color, vertex_attrs.fill_color,
                  vertex_attrs.text_color, vertex_attrs.halo_color,
                  edge_attrs.color, edge_attrs.text_color]:
Tiago Peixoto's avatar
Tiago Peixoto committed
390
        if isinstance(val, list):
391
392
393
394
395
396
            new_val = val
        elif isinstance(val, (tuple, np.ndarray)):
            new_val = list(val)
        elif isinstance(val, str):
            new_val = list(color_converter.to_rgba(val))
        elif isinstance(val, PropertyMap):
Tiago Peixoto's avatar
Tiago Peixoto committed
397
            if val.value_type() in ["vector<double>", "vector<long double>"]:
398
399
                new_val = val
            elif val.value_type() in ["int32_t", "int64_t", "double",
400
401
                                      "long double", "unsigned long",
                                      "unsigned int", "bool"]:
402
                g = val.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
403
404
405
                try:
                    vrange = [val.fa.min(), val.fa.max()]
                except ValueError:
406
407
408
409
                    #vertex index
                    vrange = [int(g.vertex(0, use_index=False)),
                              int(g.vertex(g.num_vertices() - 1,
                                           use_index=False))]
410
                cnorm = matplotlib.colors.Normalize(vmin=vrange[0],
Tiago Peixoto's avatar
Tiago Peixoto committed
411
                                                    vmax=vrange[1])
412
                g = val.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
413
                if val.key_type() == "v":
414
                    prop = g.new_vertex_property("vector<double>")
Tiago Peixoto's avatar
Tiago Peixoto committed
415
                else:
416
417
418
419
420
                    prop = g.new_edge_property("vector<double>")
                map_property_values(val, prop, lambda x: cmap(cnorm(x)))
                new_val = prop
            elif val.value_type() == "string":
                g = val.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
421
                if val.key_type() == "v":
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
                    prop = g.new_vertex_property("vector<double>")
                else:
                    prop = g.new_edge_property("vector<double>")
                map_property_values(val, prop,
                                    lambda x: color_converter.to_rgba(x))
                new_val = prop
            else:
                raise ValueError("Invalid value for attribute %s: %s" %
                                 (repr(attr), repr(val)))
        if pmap_default and not isinstance(val, PropertyMap):
            if attr in [vertex_attrs.color, vertex_attrs.fill_color,
                        vertex_attrs.text_color, vertex_attrs.halo_color]:
                val_a = numpy.zeros((g.num_vertices(),len(new_val)))
                for i in range(len(new_val)):
                    val_a[:, i] = new_val[i]
                return g.new_vertex_property("vector<double>", val_a)
            else:
                val_a = numpy.zeros((g.num_edges(), len(new_val)))
                for i in range(len(new_val)):
                    val_a[:,i] = new_val[i]
                return g.new_edge_property("vector<double>", val_a)
        else:
            return new_val

    if pmap_default and not isinstance(val, PropertyMap):
447
448
        if k == "v":
            new_val = g.new_vertex_property(_vtypes[attr], val=val)
449
        else:
450
            new_val = g.new_edge_property(_etypes[attr], val=val)
451
        return new_val
452

Tiago Peixoto's avatar
Tiago Peixoto committed
453
454
455
456
457
458
    return val


def _attrs(attrs, d, g, cmap):
    nattrs = {}
    defaults = {}
459
    for k, v in attrs.items():
Tiago Peixoto's avatar
Tiago Peixoto committed
460
461
        try:
            if d == "v":
462
                attr = getattr(vertex_attrs, k)
Tiago Peixoto's avatar
Tiago Peixoto committed
463
            else:
464
465
                attr = getattr(edge_attrs, k)
        except AttributeError:
466
            warnings.warn("Unknown attribute: " + str(k), UserWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
467
468
469
470
471
472
473
            continue
        if isinstance(v, PropertyMap):
            nattrs[int(attr)] = _prop(d, g, _convert(attr, v, cmap))
        else:
            defaults[int(attr)] = _convert(attr, v, cmap)
    return nattrs, defaults

474
475
476
477
478
def _convert_props(props, d, g, cmap, pmap_default=False):
    nprops = {}
    for k, v in props.items():
        try:
            if d == "v":
479
                attr = getattr(vertex_attrs, k)
480
            else:
481
                attr = getattr(edge_attrs, k)
482
483
            nprops[k] = _convert(attr, v, cmap, pmap_default=pmap_default,
                                 g=g, k=d)
484
        except AttributeError:
485
486
487
488
            warnings.warn("Unknown attribute: " + str(k), UserWarning)
            continue
    return nprops

Tiago Peixoto's avatar
Tiago Peixoto committed
489
490
491
492
493
494
495
496
497
498
499
500

def get_attr(attr, d, attrs, defaults):
    if attr in attrs:
        p = attrs[attr]
    else:
        p = defaults[attr]
    if isinstance(p, PropertyMap):
        return p[d]
    else:
        return p


501
502
def position_parallel_edges(g, pos, loop_angle=float("nan"),
                            parallel_distance=1):
Tiago Peixoto's avatar
Tiago Peixoto committed
503
504
    lp = label_parallel_edges(GraphView(g, directed=False))
    ll = label_self_loops(g)
505
506
507
    if isinstance(loop_angle, PropertyMap):
        angle = loop_angle
    else:
508
        angle = g.new_vertex_property("double", float(loop_angle))
509

Tiago Peixoto's avatar
Tiago Peixoto committed
510
    g = GraphView(g, directed=True)
511
512
    if ((len(lp.fa) == 0 or lp.fa.max() == 0) and
        (len(ll.fa) == 0 or ll.fa.max() == 0)):
Tiago Peixoto's avatar
Tiago Peixoto committed
513
514
515
516
        return []
    else:
        spline = g.new_edge_property("vector<double>")
        libgraph_tool_draw.put_parallel_splines(g._Graph__graph,
517
                                                _prop("v", g, pos),
Tiago Peixoto's avatar
Tiago Peixoto committed
518
                                                _prop("e", g, lp),
519
                                                _prop("e", g, spline),
520
                                                _prop("v", g, angle),
521
                                                parallel_distance)
Tiago Peixoto's avatar
Tiago Peixoto committed
522
523
524
525
526
527
        return spline


def parse_props(prefix, args):
    props = {}
    others = {}
528
    for k, v in list(args.items()):
Tiago Peixoto's avatar
Tiago Peixoto committed
529
530
531
532
533
534
535
536
        if k.startswith(prefix + "_"):
            props[k.replace(prefix + "_", "")] = v
        else:
            others[k] = v
    return props, others


def cairo_draw(g, pos, cr, vprops=None, eprops=None, vorder=None, eorder=None,
537
               nodesfirst=False, vcmap=default_cm, ecmap=default_cm,
538
               loop_angle=numpy.nan, parallel_distance=None, fit_view=False,
539
               res=0, render_offset=0, max_render_time=-1, **kwargs):
Tiago Peixoto's avatar
Tiago Peixoto committed
540
    r"""
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
    Draw a graph to a :mod:`cairo` context.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
    pos : :class:`~graph_tool.PropertyMap`
        Vector-valued vertex property map containing the x and y coordinates of
        the vertices.
    cr : :class:`~cairo.Context`
        A :class:`~cairo.Context` instance.
    vprops : dict (optional, default: ``None``)
        Dictionary with the vertex properties. Individual properties may also be
        given via the ``vertex_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
    eprops : dict (optional, default: ``None``)
557
        Dictionary with the edge properties. Individual properties may also be
558
559
560
561
562
563
564
565
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
    vorder : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        If provided, defines the relative order in which the vertices are drawn.
    eorder : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        If provided, defines the relative order in which the edges are drawn.
    nodesfirst : bool (optional, default: ``False``)
        If ``True``, the vertices are drawn first, otherwise the edges are.
566
    vcmap : :class:`matplotlib.colors.Colormap` (optional, default: :class:`default_cm`)
567
        Vertex color map.
568
    ecmap : :class:`matplotlib.colors.Colormap` (optional, default: :class:`default_cm`)
569
        Edge color map.
570
    loop_angle : float or :class:`~graph_tool.PropertyMap` (optional, default: ``nan``)
571
572
573
574
575
        Angle used to draw self-loops. If ``nan`` is given, they will be placed
        radially from the center of the layout.
    parallel_distance : float (optional, default: ``None``)
        Distance used between parallel edges. If not provided, it will be
        determined automatically.
576
    fit_view : bool or float or tuple (optional, default: ``True``)
577
        If ``True``, the layout will be scaled to fit the entire clip region.
578
        If a float value is given, it will be interpreted as ``True``, and in
579
580
581
        addition the viewport will be scaled out by that factor. If a tuple
        value is given, it should have four values ``(x, y, w, h)`` that
        specify the view in user coordinates.
582
583
    bg_color : str or sequence (optional, default: ``None``)
        Background color. The default is transparent.
584
585
586
587
588
589
590
591
592
    res : float (optional, default: ``0.``):
        If shape sizes fall below this value, simplified drawing is used.
    render_offset : int (optional, default: ``0``):
        If supplied, the rendering will skip the specified initial amount of
        vertices / edges.
    max_render_time : int (optional, default: ``-1``):
        Maximum allowed time (in milliseconds) for rendering. If exceeded, the
        rendering will return unfinished. If negative values are given, the
        rendering will always complete.
593
594
595
596
597
598
599
600
    vertex_* : :class:`~graph_tool.PropertyMap` or arbitrary types (optional, default: ``None``)
        Parameters following the pattern ``vertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``vprops`` parameter.
    edge_* : :class:`~graph_tool.PropertyMap` or arbitrary types (optional, default: ``None``)
        Parameters following the pattern ``edge_<prop-name>`` specify the edge
        property with name ``<prop-name>``, as an alternative to the ``eprops``
        parameter.
Tiago Peixoto's avatar
Tiago Peixoto committed
601

602
603
604
605
606
    Returns
    -------
    offset : int
        The offset into the completed rendering. If this value is zero, the
        rendering was complete.
Tiago Peixoto's avatar
Tiago Peixoto committed
607
608
    """

609
610
    vprops = {} if vprops is None else copy.copy(vprops)
    eprops = {} if eprops is None else copy.copy(eprops)
Tiago Peixoto's avatar
Tiago Peixoto committed
611
612
613
614
615
616
617
618

    props, kwargs = parse_props("vertex", kwargs)
    vprops.update(props)
    props, kwargs = parse_props("edge", kwargs)
    eprops.update(props)
    for k in kwargs:
        warnings.warn("Unknown parameter: " + k, UserWarning)

619
    cr.save()
620
    if fit_view != False:
621
622
        extents = cr.clip_extents()
        output_size = (extents[2] - extents[0], extents[3] - extents[1])
623
624
625
626
627
        try:
            x, y, w, h = fit_view
            cr.scale(output_size[0] / w, output_size[1] / h)
            cr.translate(-x, -y)
        except TypeError:
628
            pad = fit_view if fit_view != True else 0.95
629
630
631
632
633
634
635
636
            offset, zoom = fit_to_view(g, pos, output_size,
                                       vprops.get("size", _vdefaults["size"]),
                                       vprops.get("pen_width", _vdefaults["pen_width"]),
                                       None, vprops.get("text", None),
                                       vprops.get("font_family",
                                                  _vdefaults["font_family"]),
                                       vprops.get("font_size",
                                                  _vdefaults["font_size"]),
637
                                       pad, cr)
638
639
640
641
            cr.translate(offset[0], offset[1])
            if not isinstance(fit_view, bool):
                zoom /= fit_view
            cr.scale(zoom, zoom)
642

Tiago Peixoto's avatar
Tiago Peixoto committed
643
    if "control_points" not in eprops:
644
645
646
647
648
649
650
651
652
653
        if parallel_distance is None:
            parallel_distance = vprops.get("size", _vdefaults["size"])
            if isinstance(parallel_distance, PropertyMap):
                parallel_distance = parallel_distance.fa.mean()
            parallel_distance /= 1.5
            M = cr.get_matrix()
            scale = transform_scale(M, 1,)
            parallel_distance /= scale
        eprops["control_points"] = position_parallel_edges(g, pos, loop_angle,
                                                           parallel_distance)
Tiago Peixoto's avatar
Tiago Peixoto committed
654
655
    if g.is_directed() and "end_marker" not in eprops:
        eprops["end_marker"] = "arrow"
656

657
658
659
660
661
    if vprops.get("text_position", None) == "centered":
        angle, tpos = centered_rotation(g, pos, text_pos=True)
        vprops["text_position"] = tpos
        vprops["text_rotation"] = angle

Tiago Peixoto's avatar
Tiago Peixoto committed
662
663
664
665
666
667
    vattrs, vdefaults = _attrs(vprops, "v", g, vcmap)
    eattrs, edefaults = _attrs(eprops, "e", g, ecmap)
    vdefs = _attrs(_vdefaults, "v", g, vcmap)[1]
    vdefs.update(vdefaults)
    edefs = _attrs(_edefaults, "e", g, ecmap)[1]
    edefs.update(edefaults)
668
669
670
671
672
673

    if "control_points" not in eprops:
        if parallel_distance is None:
            parallel_distance = _defaults
        eprops["control_points"] = position_parallel_edges(g, pos, loop_angle,
                                                           parallel_distance)
Tiago Peixoto's avatar
Tiago Peixoto committed
674
    g = GraphView(g, directed=True)
675
676
677
678
    count = libgraph_tool_draw.cairo_draw(g._Graph__graph, _prop("v", g, pos),
                                          _prop("v", g, vorder), _prop("e", g, eorder),
                                          nodesfirst, vattrs, eattrs, vdefs, edefs, res,
                                          render_offset, max_render_time, cr)
679
    cr.restore()
680
    return count
Tiago Peixoto's avatar
Tiago Peixoto committed
681

682
683
def color_contrast(color):
    c = np.asarray(color)
684
685
    y = c[0] * .299 + c[1] * .587 + c[2] * .114
    if y < .5:
686
687
688
689
690
691
692
        c[:3] = 1
    else:
        c[:3] = 0
    return c


def auto_colors(g, bg, pos, back):
693
694
695
    if not isinstance(bg, PropertyMap):
        if isinstance(bg, str):
            bg = color_converter.to_rgba(bg)
696
        bg = g.new_vertex_property("vector<double>", val=bg)
697
698
699
700
701
702
703
704
705
706
707
708
709
    if not isinstance(pos, PropertyMap):
        if pos == "centered":
            pos = 0
        pos = g.new_vertex_property("double", pos)
    bg_a = bg.get_2d_array(range(4))
    bgc_pos = numpy.zeros((g.num_vertices(), 5))
    for i in range(4):
        bgc_pos[:, i] = bg_a[i, :]
    bgc_pos[:, 4] = pos.fa
    bgc_pos = g.new_vertex_property("vector<double>", bgc_pos)
    def conv(x):
        bgc = x[:4]
        p = x[4]
710
        if p < 0:
711
            return color_contrast(bgc)
712
        else:
713
714
715
            return color_contrast(back)
    c = g.new_vertex_property("vector<double>")
    map_property_values(bgc_pos, c, conv)
716
717
    return c

Tiago Peixoto's avatar
Tiago Peixoto committed
718
719
def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
               nodesfirst=False, output_size=(600, 600), fit_view=True,
720
721
               inline=is_draw_inline, mplfig=None, output=None, fmt="auto",
               **kwargs):
722
723
724
725
726
727
728
729
730
731
732
733
734
735
    r"""Draw a graph to screen or to a file using :mod:`cairo`.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vector-valued vertex property map containing the x and y coordinates of
        the vertices. If not given, it will be computed using :func:`sfdp_layout`.
    vprops : dict (optional, default: ``None``)
        Dictionary with the vertex properties. Individual properties may also be
        given via the ``vertex_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
    eprops : dict (optional, default: ``None``)
736
        Dictionary with the edge properties. Individual properties may also be
737
738
739
740
741
742
743
744
745
746
747
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
    vorder : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        If provided, defines the relative order in which the vertices are drawn.
    eorder : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        If provided, defines the relative order in which the edges are drawn.
    nodesfirst : bool (optional, default: ``False``)
        If ``True``, the vertices are drawn first, otherwise the edges are.
    output_size : tuple of scalars (optional, default: ``(600,600)``)
        Size of the drawing canvas. The units will depend on the output format
        (pixels for the screen, points for PDF, etc).
748
749
750
751
752
753
    fit_view : bool, float or tuple (optional, default: ``True``)
        If ``True``, the layout will be scaled to fit the entire clip region.
        If a float value is given, it will be interpreted as ``True``, and in
        addition the viewport will be scaled out by that factor. If a tuple
        value is given, it should have four values ``(x, y, w, h)`` that
        specify the view in user coordinates.
754
755
756
    inline : bool (optional, default: ``False``)
        If ``True`` and an `IPython notebook <http://ipython.org/notebook>`_  is
        being used, an inline version of the drawing will be returned.
757
758
759
760
761
    mplfig : :mod:`matplotlib` container object (optional, default: ``None``)
        The ``mplfig`` object needs to have an ``artists`` attribute. This can
        for example be a :class:`matplotlib.figure.Figure` or
        :class:`matplotlib.axes.Axes`. Only the cairo backend is supported; use
        ``switch_backend('cairo')``.
762
763
    output : string or file object (optional, default: ``None``)
        Output file name (or object). If not given, the graph will be displayed via
764
765
766
767
768
        :func:`interactive_window`.
    fmt : string (default: ``"auto"``)
        Output file format. Possible values are ``"auto"``, ``"ps"``, ``"pdf"``,
        ``"svg"``, and ``"png"``. If the value is ``"auto"``, the format is
        guessed from the ``output`` parameter.
769
770
    bg_color : str or sequence (optional, default: ``None``)
        Background color. The default is transparent.
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
800
801
802
803
804
805
806
    vertex_* : :class:`~graph_tool.PropertyMap` or arbitrary types (optional, default: ``None``)
        Parameters following the pattern ``vertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``vprops`` parameter.
    edge_* : :class:`~graph_tool.PropertyMap` or arbitrary types (optional, default: ``None``)
        Parameters following the pattern ``edge_<prop-name>`` specify the edge
        property with name ``<prop-name>``, as an alternative to the ``eprops``
        parameter.
    **kwargs
        Any extra parameters are passed to :func:`~graph_tool.draw.interactive_window`,
        :class:`~graph_tool.draw.GraphWindow`, :class:`~graph_tool.draw.GraphWidget`
        and :func:`~graph_tool.draw.cairo_draw`.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        Vector vertex property map with the x and y coordinates of the vertices.
    selected : :class:`~graph_tool.PropertyMap` (optional, only if ``output is None``)
        Boolean-valued vertex property map marking the vertices which were
        selected interactively.

    Notes
    -----


    .. table:: **List of vertex properties**

        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | Name          | Description                                       | Accepted types         | Default Value                    |
        +===============+===================================================+========================+==================================+
        | shape         | The vertex shape. Can be one of the following     | ``str`` or ``int``     | ``"circle"``                     |
        |               | strings: "circle", "triangle", "square",          |                        |                                  |
        |               | "pentagon", "hexagon", "heptagon", "octagon"      |                        |                                  |
        |               | "double_circle", "double_triangle",               |                        |                                  |
        |               | "double_square", "double_pentagon",               |                        |                                  |
        |               | "double_hexagon", "double_heptagon",              |                        |                                  |
807
        |               | "double_octagon", "pie".                          |                        |                                  |
808
809
810
811
812
813
814
815
816
817
818
819
820
        |               | Optionally, this might take a numeric value       |                        |                                  |
        |               | corresponding to position in the list above.      |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | color         | Color used to stroke the lines of the vertex.     | ``str`` or list of     | ``[0., 0., 0., 1]``              |
        |               |                                                   | ``floats``             |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | fill_color    | Color used to fill the interior of the vertex.    | ``str`` or list of     | ``[0.640625, 0, 0, 0.9]``        |
        |               |                                                   | ``floats``             |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | size          | The size of the vertex, in the default units of   | ``float`` or ``int``   | ``5``                            |
        |               | the output format (normally either pixels or      |                        |                                  |
        |               | points).                                          |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
821
822
        | aspect        | The aspect ratio of the vertex.                   | ``float`` or ``int``   | ``1.0``                          |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
823
824
        | rotation      | Angle (in radians) to rotate the vertex.          | ``float``              | ``0.``                          |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
825
826
827
828
        | anchor        | Specifies how the edges anchor to the vertices.   |  ``int``               | ``1``                            |
        |               | If `0`, the anchor is at the center of the vertex,|                        |                                  |
        |               | otherwise it is at the border.                    |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
829
830
831
832
833
834
835
836
837
838
        | pen_width     | Width of the lines used to draw the vertex, in    | ``float`` or ``int``   | ``0.8``                          |
        |               | the default units of the output format (normally  |                        |                                  |
        |               | either pixels or points).                         |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | halo          | Whether to draw a circular halo around the        | ``bool``               | ``False``                        |
        |               | vertex.                                           |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | halo_color    | Color used to draw the halo.                      | ``str`` or list of     | ``[0., 0., 1., 0.5]``            |
        |               |                                                   | ``floats``             |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
839
840
841
        | halo_size     | Relative size of the halo.                        | ``float``              | ``1.5``                          |
        |               |                                                   |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
842
843
        | text          | Text to draw together with the vertex.            | ``str``                | ``""``                           |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
844
845
846
        | text_color    | Color used to draw the text. If the value is      | ``str`` or list of     | ``"auto"``                       |
        |               | ``"auto"``, it will be computed based on          | ``floats``             |                                  |
        |               | fill_color to maximize contrast.                  |                        |                                  |
847
848
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_position | Position of the text relative to the vertex.      | ``float`` or ``int``   | ``-1``                           |
849
        |               | If the passed value is positive, it will          |  or ``"centered"``     |                                  |
850
851
852
        |               | correspond to an angle in radians, which will     |                        |                                  |
        |               | determine where the text will be placed outside   |                        |                                  |
        |               | the vertex. If the value is negative, the text    |                        |                                  |
853
854
        |               | will be placed inside the vertex. If the value is |                        |                                  |
        |               | ``-1``, the vertex size will be automatically     |                        |                                  |
855
856
857
        |               | increased to accommodate the text. The special    |                        |                                  |
        |               | value ``"centered"`` positions the texts rotated  |                        |                                  |
        |               | radially around the center of mass.               |                        |                                  |
858
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
859
860
861
862
863
864
        | text_offset   | Text position offset.                             | list of ``float``      | ``[0.0, 0.0]``                   |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_rotation | Angle of rotation (in radians) for the text.      | ``float``              | ``0.0``                          |
        |               | The center of rotation is the position of the     |                        |                                  |
        |               | vertex.                                           |                        |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
865
866
867
868
869
870
871
872
        | font_family   | Font family used to draw the text.                | ``str``                | ``"serif"``                      |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_slant    | Font slant used to draw the text.                 | ``cairo.FONT_SLANT_*`` | :data:`cairo.FONT_SLANT_NORMAL`  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_weight   | Font weight used to draw the text.                | ``cairo.FONT_WEIGHT_*``| :data:`cairo.FONT_WEIGHT_NORMAL` |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_size     | Font size used to draw the text.                  | ``float`` or ``int``   | ``12``                           |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
873
874
        | surface       | The cairo surface used to draw the vertex. If     | :class:`cairo.Surface` | ``None``                         |
        |               | the value passed is a string, it is interpreted   | or ``str``             |                                  |
Tiago Peixoto's avatar
Tiago Peixoto committed
875
        |               | as an image file name to be loaded.               |                        |                                  |
876
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
877
878
879
880
881
882
        | pie_fractions | Fractions of the pie sections for the vertices if | list of ``int`` or     | ``[0.75, 0.25]``                 |
        |               | ``shape=="pie"``.                                 | ``float``              |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
        | pie_colors    | Colors used in the pie sections if                | list of strings or     | ``('b','g','r','c','m','y','k')``|
        |               | ``shape=="pie"``.                                 | ``float``.             |                                  |
        +---------------+---------------------------------------------------+------------------------+----------------------------------+
883
884
885
886
887
888
889
890
891
892
893
894
895
896


    .. table:: **List of edge properties**

        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | Name           | Description                                       | Accepted types         | Default Value                    |
        +================+===================================================+========================+==================================+
        | color          | Color used to stroke the edge lines.              | ``str`` or list of     | ``[0.179, 0.203,0.210, 0.8]``    |
        |                |                                                   | floats                 |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | pen_width      | Width of the line used to draw the edge, in       | ``float`` or ``int``   | ``1.0``                          |
        |                | the default units of the output format (normally  |                        |                                  |
        |                | either pixels or points).                         |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
897
        | start_marker,  | Edge markers. Can be one of "none", "arrow",      | ``str`` or ``int``     | ``none``                         |
898
899
900
901
        | mid_marker,    | "circle", "square", "diamond", or "bar".          |                        |                                  |
        | end_marker     | Optionally, this might take a numeric value       |                        |                                  |
        |                | corresponding to position in the list above.      |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
902
903
        | mid_marker_pos | Relative position of the middle marker.           | ``float``              | ``0.5``                          |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
904
905
906
907
        | marker_size    | Size of edge markers, in units appropriate to the | ``float`` or ``int``   | ``4``                            |
        |                | output format (normally either pixels or points). |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | control_points | Control points of a Bézier spline used to draw    | sequence of ``floats`` | ``[]``                           |
Tiago Peixoto's avatar
Tiago Peixoto committed
908
909
910
911
912
913
914
915
916
        |                | the edge. Each spline segment requires 6 values   |                        |                                  |
        |                | corresponding to the (x,y) coordinates of the two |                        |                                  |
        |                | intermediary control points and the final point.  |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | gradient       | Stop points of a linear gradient used to stroke   | sequence of ``floats`` | ``[]``                           |
        |                | the edge. Each group of 5 elements is interpreted |                        |                                  |
        |                | as ``[o, r, g, b, a]`` where ``o`` is the offset  |                        |                                  |
        |                | in the range [0, 1] and the remaining values      |                        |                                  |
        |                | specify the colors.                               |                        |                                  |
917
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
918
919
920
921
922
923
        | dash_style     | Dash pattern is specified by an array of positive | sequence of ``floats`` | ``[]``                           |
        |                | values. Each value provides the length of         |                        |                                  |
        |                | alternate "on" and "off" portions of the stroke.  |                        |                                  |
        |                | The last value specifies an offset into the       |                        |                                  |
        |                | pattern at which the stroke begins.               |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
        | text           | Text to draw next to the edges.                   | ``str``                | ``""``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_color     | Color used to draw the text.                      | ``str`` or list of     | ``[0., 0., 0., 1.]``             |
        |                |                                                   | ``floats``             |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_distance  | Distance from the edge and its text.              | ``float`` or ``int``   | ``4``                            |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_parallel  | If ``True`` the text will be drawn parallel to    | ``bool``               | ``True``                         |
        |                | the edges.                                        |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_family    | Font family used to draw the text.                | ``str``                | ``"serif"``                      |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_slant     | Font slant used to draw the text.                 | ``cairo.FONT_SLANT_*`` | :data:`cairo.FONT_SLANT_NORMAL`  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_weight    | Font weight used to draw the text.                | ``cairo.FONT_WEIGHT_*``| :data:`cairo.FONT_WEIGHT_NORMAL` |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | font_size      | Font size used to draw the text.                  | ``float`` or ``int``   | ``12``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
942
943
944

    Examples
    --------
945
946
947
948
949
950
951
    .. testcode::
       :hide:

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

952
953
954
    >>> g = gt.price_network(1500)
    >>> deg = g.degree_property_map("in")
    >>> deg.a = 4 * (sqrt(deg.a) * 0.5 + 0.4)
955
956
    >>> ebet = gt.betweenness(g)[1]
    >>> ebet.a /= ebet.a.max() / 10.
957
958
959
960
961
962
963
964
965
966
    >>> eorder = ebet.copy()
    >>> eorder.a *= -1
    >>> pos = gt.sfdp_layout(g)
    >>> control = g.new_edge_property("vector<double>")
    >>> for e in g.edges():
    ...     d = sqrt(sum((pos[e.source()].a - pos[e.target()].a) ** 2)) / 5
    ...     control[e] = [0.3, d, 0.7, d]
    >>> gt.graph_draw(g, pos=pos, vertex_size=deg, vertex_fill_color=deg, vorder=deg,
    ...               edge_color=ebet, eorder=eorder, edge_pen_width=ebet,
    ...               edge_control_points=control, # some curvy edges
967
968
969
    ...               output="graph-draw.pdf")
    <...>

970
971
972
973
974
975
976
977
978
    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, vertex_size=deg, vertex_fill_color=deg, vorder=deg,
                     edge_color=ebet, eorder=eorder, edge_pen_width=ebet,
                     edge_control_points=control,
                     output="graph-draw.png")


979
980
981
    .. figure:: graph-draw.*
        :align: center

982
983
        SFDP force-directed layout of a Price network with 1500 nodes. The
        vertex size and color indicate the degree, and the edge color and width
984
        the edge betweenness centrality.
985
986
987

    """

Tiago Peixoto's avatar
Tiago Peixoto committed
988
989
990
991
    vprops = vprops.copy() if vprops is not None else {}
    eprops = eprops.copy() if eprops is not None else {}

    props, kwargs = parse_props("vertex", kwargs)
992
    props = _convert_props(props, "v", g, kwargs.get("vcmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
993
994
    vprops.update(props)
    props, kwargs = parse_props("edge", kwargs)
995
    props = _convert_props(props, "e", g, kwargs.get("ecmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
996
997
998
    eprops.update(props)

    if pos is None:
999
        if (g.num_vertices() > 2 and output is None and
1000
            not inline and kwargs.get("update_layout", True)):