cairo_draw.py 99.7 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-2020 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
21
22
#
# 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/>.

import os
import warnings
23
import numpy
Tiago Peixoto's avatar
Tiago Peixoto committed
24

25
from .. topology import shortest_distance, is_bipartite
26
from .. import _check_prop_scalar, perfect_prop_hash
27

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

Tiago Peixoto's avatar
Tiago Peixoto committed
35
default_cm = None
Tiago Peixoto's avatar
Tiago Peixoto committed
36
try:
37
38
    import matplotlib.artist
    import matplotlib.backends.backend_cairo
39
40
    import matplotlib.cm
    import matplotlib.colors
41
    from matplotlib.cbook import flatten
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    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)
56
    is_draw_inline = 'inline' in matplotlib.get_backend()
57
    color_converter = matplotlib.colors.ColorConverter()
Tiago Peixoto's avatar
Tiago Peixoto committed
58
except ImportError:
59
    msg = "Error importing matplotlib module. Graph drawing will not work."
60
    warnings.warn(msg, RuntimeWarning)
61
    raise
Tiago Peixoto's avatar
Tiago Peixoto committed
62

63
64
try:
    import IPython.display
Tiago Peixoto's avatar
Tiago Peixoto committed
65
except ImportError:
66
67
    pass

Tiago Peixoto's avatar
Tiago Peixoto committed
68
69
70
71
import numpy as np
import gzip
import bz2
import zipfile
72
import copy
73
import io
Tiago Peixoto's avatar
Tiago Peixoto committed
74
75
from collections import defaultdict

76
from .. import Graph, GraphView, PropertyMap, ungroup_vector_property,\
77
     group_vector_property, _prop, _check_prop_vector, map_property_values
78

Tiago Peixoto's avatar
Tiago Peixoto committed
79
80
81
from .. stats import label_parallel_edges, label_self_loops

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

from .. draw import sfdp_layout, random_layout, _avg_edge_distance, \
92
93
94
95
    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
96
97
98

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

_edefaults = {
126
    "color": (0.1796875, 0.203125, 0.2109375, 0.8),
Tiago Peixoto's avatar
Tiago Peixoto committed
127
128
129
130
131
    "pen_width": 1,
    "start_marker": "none",
    "mid_marker": "none",
    "end_marker": "none",
    "marker_size": 4.,
132
    "mid_marker_pos": .5,
Tiago Peixoto's avatar
Tiago Peixoto committed
133
    "control_points": [],
Tiago Peixoto's avatar
Tiago Peixoto committed
134
    "gradient": [],
135
    "dash_style": [],
136
    "text": "",
137
    "text_color": (0., 0., 0., 1.),
138
139
    "text_distance": 5,
    "text_parallel": True,
140
141
    "text_out_width": .1,
    "text_out_color": [0., 0., 0., 0.],
142
143
144
145
    "font_family": "serif",
    "font_slant": cairo.FONT_SLANT_NORMAL,
    "font_weight": cairo.FONT_WEIGHT_NORMAL,
    "font_size": 12.,
146
    "sloppy": False,
147
    "seamless": True
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
    "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>",
167
168
    "text_out_width": "double",
    "text_out_color": "vector<double>",
169
170
171
    "font_family": "string",
    "font_slant": "int",
    "font_weight": "int",
172
    "font_size": "double",
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
    "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",
193
194
    "text_out_width": "double",
    "text_out_color": "vector<double>",
195
196
197
198
199
200
201
202
203
204
205
206
207
208
    "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
209
210
211

def shape_from_prop(shape, enum):
    if isinstance(shape, PropertyMap):
212
        g = shape.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
213
        if shape.key_type() == "v":
214
215
            prop = g.new_vertex_property("int")
            descs = g.vertices()
Tiago Peixoto's avatar
Tiago Peixoto committed
216
        else:
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
            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
232
        return prop
233
    if isinstance(shape, str):
234
        return int(getattr(enum, shape))
Tiago Peixoto's avatar
Tiago Peixoto committed
235
236
237
238
239
240
    else:
        return shape

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

241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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(".", "")
256
    return out, fmt
257

258
259
260
261
262
263
264
265
266
267
268
269
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

270
271
272
273
274
275
276
277
278
279
280
281
282
283
284

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
285
                prop[v] = surface_map[surface[v]]
286
287
288
            elif surface.value_type() == "python::object":
                if isinstance(surface[v], cairo.Surface):
                    prop[v] = surface[v]
289
                elif surface[v] is not None:
290
291
292
293
294
295
296
                    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

297
    if isinstance(surface, str):
298
299
300
301
302
303
        return gen_surface(surface)
    elif isinstance(surface, cairo.Surface) or surface is None:
        return surface

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

304
305
306
307
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]
308
    dy = y.fa - cm[1]
309
310
311
312
313
314
315
316
317
318
319
320
    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
321

322
def _convert(attr, val, cmap, pmap_default=False, g=None, k=None):
323
324
325
326
327
    try:
        cmap, alpha = cmap
    except TypeError:
        alpha = None

Tiago Peixoto's avatar
Tiago Peixoto committed
328
    if attr == vertex_attrs.shape:
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
        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]:
345
346
347
        if isinstance(val, PropertyMap):
            if val.value_type() in ["vector<double>", "vector<long double>"]:
                return val
348
            if val.value_type() in ["vector<int32_t>", "vector<int64_t>", "vector<bool>"]:
349
350
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
351
                rg = [numpy.inf, -numpy.inf]
352
353
                for v in g.vertices():
                    for x in val[v]:
354
355
                        rg[0] = min(x, rg[0])
                        rg[1] = max(x, rg[1])
356
357
                if rg[0] == rg[1]:
                    rg[1] = 1
358
                map_property_values(val, new_val,
359
360
                                    lambda y: flatten([cmap((x - rg[0]) / (rg[1] - rg[0]),
                                                            alpha=alpha) for x in y]))
361
                return new_val
362
363
364
            if val.value_type() == "vector<string>":
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
365
366
                map_property_values(val, new_val,
                                    lambda y: flatten([color_converter.to_rgba(x) for x in y]))
367
368
369
370
371
                return new_val
            if val.value_type() == "python::object":
                try:
                    g = val.get_graph()
                    new_val = g.new_vertex_property("vector<double>")
372
                    def conv(y):
373
                        try:
374
                            new_val[v] = [float(x) for x in flatten(y)]
375
                        except ValueError:
376
377
                            new_val[v] = flatten([color_converter.to_rgba(x) for x in y])
                    map_property_values(val, new_val, conv)
378
379
380
381
382
                    return new_val
                except ValueError:
                    pass
        else:
            try:
383
                new_val = [float(x) for x in flatten(val)]
384
385
            except ValueError:
                try:
386
                    new_val = flatten(color_converter.to_rgba(x) for x in val)
387
                    new_val = list(new_val)
388
389
                except ValueError:
                    pass
390
391
392
393
394
395
396
397
            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,
398
399
400
                  vertex_attrs.text_color, vertex_attrs.text_out_color,
                  vertex_attrs.halo_color, edge_attrs.color,
                  edge_attrs.text_color, edge_attrs.text_out_color]:
Tiago Peixoto's avatar
Tiago Peixoto committed
401
        if isinstance(val, list):
402
403
404
            new_val = val
        elif isinstance(val, (tuple, np.ndarray)):
            new_val = list(val)
405
        elif isinstance(val, str):
406
407
            new_val = list(color_converter.to_rgba(val))
        elif isinstance(val, PropertyMap):
Tiago Peixoto's avatar
Tiago Peixoto committed
408
            if val.value_type() in ["vector<double>", "vector<long double>"]:
409
410
                new_val = val
            elif val.value_type() in ["int32_t", "int64_t", "double",
411
412
                                      "long double", "unsigned long",
                                      "unsigned int", "bool"]:
413
                g = val.get_graph()
414
415
416
417
418
                if val.value_type() in ["int32_t", "int64_t", "unsigned long",
                                        "unsigned int"]:
                    nval = perfect_prop_hash([val])[0]
                else:
                    nval = val
Tiago Peixoto's avatar
Tiago Peixoto committed
419
                try:
420
421
                    vrange = [nval.fa.min(), nval.fa.max()]
                except (AttributeError, ValueError):
422
423
424
425
                    #vertex index
                    vrange = [int(g.vertex(0, use_index=False)),
                              int(g.vertex(g.num_vertices() - 1,
                                           use_index=False))]
426
                cnorm = matplotlib.colors.Normalize(vmin=vrange[0],
Tiago Peixoto's avatar
Tiago Peixoto committed
427
                                                    vmax=vrange[1])
428
                g = val.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
429
                if val.key_type() == "v":
430
                    prop = g.new_vertex_property("vector<double>")
Tiago Peixoto's avatar
Tiago Peixoto committed
431
                else:
432
                    prop = g.new_edge_property("vector<double>")
433
434
                map_property_values(nval, prop, lambda x: cmap(cnorm(x),
                                                               alpha=alpha))
435
436
437
                new_val = prop
            elif val.value_type() == "string":
                g = val.get_graph()
Tiago Peixoto's avatar
Tiago Peixoto committed
438
                if val.key_type() == "v":
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                    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):
464
465
        if k == "v":
            new_val = g.new_vertex_property(_vtypes[attr], val=val)
466
        else:
467
            new_val = g.new_edge_property(_etypes[attr], val=val)
468
        return new_val
469

Tiago Peixoto's avatar
Tiago Peixoto committed
470
471
472
473
474
475
    return val


def _attrs(attrs, d, g, cmap):
    nattrs = {}
    defaults = {}
476
    for k, v in attrs.items():
Tiago Peixoto's avatar
Tiago Peixoto committed
477
478
        try:
            if d == "v":
479
                attr = getattr(vertex_attrs, k)
Tiago Peixoto's avatar
Tiago Peixoto committed
480
            else:
481
482
                attr = getattr(edge_attrs, k)
        except AttributeError:
483
            warnings.warn("Unknown attribute: " + str(k), UserWarning)
Tiago Peixoto's avatar
Tiago Peixoto committed
484
485
486
487
488
489
490
            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

491
492
493
494
495
def _convert_props(props, d, g, cmap, pmap_default=False):
    nprops = {}
    for k, v in props.items():
        try:
            if d == "v":
496
                attr = getattr(vertex_attrs, k)
497
            else:
498
                attr = getattr(edge_attrs, k)
499
500
            nprops[k] = _convert(attr, v, cmap, pmap_default=pmap_default,
                                 g=g, k=d)
501
        except AttributeError:
502
503
504
505
            warnings.warn("Unknown attribute: " + str(k), UserWarning)
            continue
    return nprops

Tiago Peixoto's avatar
Tiago Peixoto committed
506
507
508
509
510
511
512
513
514
515
516
517

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


518
519
def position_parallel_edges(g, pos, loop_angle=float("nan"),
                            parallel_distance=1):
Tiago Peixoto's avatar
Tiago Peixoto committed
520
521
    lp = label_parallel_edges(GraphView(g, directed=False))
    ll = label_self_loops(g)
522
523
524
    if isinstance(loop_angle, PropertyMap):
        angle = loop_angle
    else:
525
        angle = g.new_vertex_property("double", float(loop_angle))
526

Tiago Peixoto's avatar
Tiago Peixoto committed
527
    g = GraphView(g, directed=True)
528
529
    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
530
531
532
533
        return []
    else:
        spline = g.new_edge_property("vector<double>")
        libgraph_tool_draw.put_parallel_splines(g._Graph__graph,
534
                                                _prop("v", g, pos),
Tiago Peixoto's avatar
Tiago Peixoto committed
535
                                                _prop("e", g, lp),
536
                                                _prop("e", g, spline),
537
                                                _prop("v", g, angle),
538
                                                parallel_distance)
Tiago Peixoto's avatar
Tiago Peixoto committed
539
540
541
542
543
544
        return spline


def parse_props(prefix, args):
    props = {}
    others = {}
545
    for k, v in list(args.items()):
546
547
        if v is None:
            continue
Tiago Peixoto's avatar
Tiago Peixoto committed
548
549
550
551
552
553
554
555
        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,
556
               nodesfirst=False, vcmap=default_cm, ecmap=default_cm,
557
558
               loop_angle=numpy.nan, parallel_distance=None, res=0,
               max_render_time=-1, **kwargs):
559
    r"""Draw a graph to a :mod:`cairo` context.
560
561
562
563
564

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
565
    pos : :class:`~graph_tool.VertexPropertyMap`
566
567
568
569
570
571
572
573
574
        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``)
575
        Dictionary with the edge properties. Individual properties may also be
576
577
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
578
    vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
579
        If provided, defines the relative order in which the vertices are drawn.
580
    eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
581
582
583
        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.
584
    vcmap : :class:`matplotlib.colors.Colormap` or tuple (optional, default: :obj:`~graph_tool.draw.default_cm`)
585
586
        Vertex color map. Optionally, this may be a
        (:class:`matplotlib.colors.Colormap`, alpha) tuple.
587
    ecmap : :class:`matplotlib.colors.Colormap` or tuple (optional, default: :obj:`~graph_tool.draw.default_cm`)
588
589
        Edge color map. Optionally, this may be a
        (:class:`matplotlib.colors.Colormap`, alpha) tuple.
590
    loop_angle : float or :class:`~graph_tool.EdgePropertyMap` (optional, default: ``nan``)
591
592
593
594
595
        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.
596
597
    bg_color : str or sequence (optional, default: ``None``)
        Background color. The default is transparent.
598
599
600
    res : float (optional, default: ``0.``):
        If shape sizes fall below this value, simplified drawing is used.
    max_render_time : int (optional, default: ``-1``):
601
602
603
        If nonnegative, this function will return an iterator that will perform
        part of the drawing at each step, so that each iteration takes at most
        ``max_render_time`` milliseconds.
604
    vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``)
605
606
607
        Parameters following the pattern ``vertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``vprops`` parameter.
608
    edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``)
609
610
611
        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
612

613
614
    Returns
    -------
615
616
617
618
    iterator :
        If ``max_render_time`` is nonnegative, this will be an iterator that will
        perform part of the drawing at each step, so that each iteration takes
        at most ``max_render_time`` milliseconds.
619

Tiago Peixoto's avatar
Tiago Peixoto committed
620
621
    """

622
623
624
    if vorder is not None:
        _check_prop_scalar(vorder, name="vorder")

625
626
    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
627
628
629
630
631
632
633
634

    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)

635
636
    cr.save()

Tiago Peixoto's avatar
Tiago Peixoto committed
637
    if "control_points" not in eprops:
638
639
640
641
642
643
644
645
646
647
        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
648
649
    if g.is_directed() and "end_marker" not in eprops:
        eprops["end_marker"] = "arrow"
650

651
652
653
654
    if vprops.get("text_position", None) == "centered":
        angle, tpos = centered_rotation(g, pos, text_pos=True)
        vprops["text_position"] = tpos
        vprops["text_rotation"] = angle
655
656
657
658
659
660
661
662
        toffset = vprops.get("text_offset", None)
        if toffset is not None:
            if not isinstance(toffset, PropertyMap):
                toffset = g.new_vp("vector<double>", val=toffset)
            xo, yo = ungroup_vector_property(toffset, [0, 1])
            xo.a[tpos.a == numpy.pi] *= -1
            toffset = group_vector_property([xo, yo])
            vprops["text_offset"] = toffset
663

Tiago Peixoto's avatar
Tiago Peixoto committed
664
665
666
667
668
669
    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)
670
671
672
673
674
675

    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)
676
677
678
679
    generator = libgraph_tool_draw.cairo_draw(g._Graph__graph,
                                              _prop("v", g, pos),
                                              _prop("v", g, vorder),
                                              _prop("e", g, eorder),
680
681
682
                                              nodesfirst, vattrs, eattrs, vdefs, edefs, res,
                                              max_render_time, cr)
    if max_render_time >= 0:
Tiago Peixoto's avatar
Tiago Peixoto committed
683
684
685
686
687
        def gen():
            for count in generator:
                yield count
            cr.restore()
        return gen()
688
689
690
    else:
        for count in generator:
            pass
Tiago Peixoto's avatar
Tiago Peixoto committed
691
        cr.restore()
Tiago Peixoto's avatar
Tiago Peixoto committed
692

693
694
def color_contrast(color):
    c = np.asarray(color)
695
696
    y = c[0] * .299 + c[1] * .587 + c[2] * .114
    if y < .5:
697
698
699
700
701
702
        c[:3] = 1
    else:
        c[:3] = 0
    return c

def auto_colors(g, bg, pos, back):
703
    if not isinstance(bg, PropertyMap):
704
        if isinstance(bg, str):
705
            bg = color_converter.to_rgba(bg)
706
        bg = g.new_vertex_property("vector<double>", val=bg)
707
708
709
710
711
712
713
714
715
716
717
718
719
    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]
720
        if p < 0:
721
            return color_contrast(bgc)
722
        else:
723
724
725
            return color_contrast(back)
    c = g.new_vertex_property("vector<double>")
    map_property_values(bgc_pos, c, conv)
726
727
    return c

728
729


Tiago Peixoto's avatar
Tiago Peixoto committed
730
731
def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None,
               nodesfirst=False, output_size=(600, 600), fit_view=True,
732
               adjust_aspect=True, ink_scale=1, inline=is_draw_inline,
733
734
               inline_scale=2, mplfig=None, output=None, fmt="auto",
               bg_color=None, **kwargs):
735
736
737
738
739
740
    r"""Draw a graph to screen or to a file using :mod:`cairo`.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
741
    pos : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
742
743
744
745
746
747
748
        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``)
749
        Dictionary with the edge properties. Individual properties may also be
750
751
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property.
752
    vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
753
        If provided, defines the relative order in which the vertices are drawn.
754
    eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
755
756
757
758
759
760
        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).
761
762
763
764
765
766
    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.
767
768
769
770
771
    adjust_aspect : bool (optional, default: ``True``)
        If ``True``, and ``fit_view == True`` the output size will be decreased
        in the width or height to remove empty spaces.
    ink_scale : float (optional, default: ``1.``)
        Scale all sizes and widths by this factor.
772
773
774
    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.
775
776
    inline_scale : float (optional, default: ``2.``):
        Resolution scaling factor for inline images.
777
778
779
780
781
    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')``.
782
783
    output : string or file object (optional, default: ``None``)
        Output file name (or object). If not given, the graph will be displayed via
784
785
786
787
788
        :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.
789
790
    bg_color : str or sequence (optional, default: ``None``)
        Background color. The default is transparent.
791
    vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``)
792
793
794
        Parameters following the pattern ``vertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``vprops`` parameter.
795
    edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``)
796
797
798
799
800
801
802
803
804
805
        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
    -------
806
    pos : :class:`~graph_tool.VertexPropertyMap`
807
        Vector vertex property map with the x and y coordinates of the vertices.
808
    selected : :class:`~graph_tool.VertexPropertyMap` (optional, only if ``output is None``)
809
810
811
812
813
814
815
816
        Boolean-valued vertex property map marking the vertices which were
        selected interactively.

    Notes
    -----

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

817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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",              |                        |                                  |
        |                | "double_octagon", "pie", "none".                  |                        |                                  |
        |                | 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).                                          |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | aspect         | The aspect ratio of the vertex.                   | ``float`` or ``int``   | ``1.0``                          |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | rotation       | Angle (in radians) to rotate the vertex.          | ``float``              | ``0.``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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.                    |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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``             |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | halo_size      | Relative size of the halo.                        | ``float``              | ``1.5``                          |
        |                |                                                   |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text           | Text to draw together with the vertex.            | ``str``                | ``""``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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.                  |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_position  | Position of the text relative to the vertex.      | ``float`` or ``int``   | ``-1``                           |
        |                | If the passed value is positive, it will          |  or ``"centered"``     |                                  |
        |                | 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    |                        |                                  |
        |                | will be placed inside the vertex. If the value is |                        |                                  |
        |                | ``-1``, the vertex size will be automatically     |                        |                                  |
        |                | increased to accommodate the text. The special    |                        |                                  |
        |                | value ``"centered"`` positions the texts rotated  |                        |                                  |
        |                | radially around the center of mass.               |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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.                                           |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_out_color | Color used to draw the text outline.              | ``str`` or list of     | ``[0,0,0,0]``                    |
        |                |                                                   | ``floats``             |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | text_out_width | Width of the text outline.                        | ``float``              | ``1.``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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``             |                                  |
        |                | as an image file name to be loaded.               |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
        | 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``.             |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
907
908
909
910
911
912
913
914
915
916
917
918
919
920


    .. 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).                         |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
921
        | start_marker,  | Edge markers. Can be one of "none", "arrow",      | ``str`` or ``int``     | ``none``                         |
922
923
924
925
        | mid_marker,    | "circle", "square", "diamond", or "bar".          |                        |                                  |
        | end_marker     | Optionally, this might take a numeric value       |                        |                                  |
        |                | corresponding to position in the list above.      |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
926
927
        | mid_marker_pos | Relative position of the middle marker.           | ``float``              | ``0.5``                          |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
928
929
930
931
        | 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
932
933
934
935
936
937
938
939
940
        |                | 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.                               |                        |                                  |
941
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
942
943
944
945
946
947
        | 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.               |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
948
949
950
951
952
953
954
955
956
957
        | 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.                                        |                        |                                  |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
958
959
960
961
962
        | text_out_color | Color used to draw the text outline.              | ``str`` or list of     | ``[0,0,0,0]``                    |
        |                |                                                   | ``floats``             |                                  |
        +--------------- +---------------------------------------------------+------------------------+----------------------------------+
        | text_out_width | Width of the text outline.                        | ``float``              | ``1.``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
963
964
965
966
967
968
969
970
        | 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``                           |
        +----------------+---------------------------------------------------+------------------------+----------------------------------+
971
972
973

    Examples
    --------
974
975
976
977
978
979
980
    .. testcode::
       :hide:

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

981
982
983
    >>> g = gt.price_network(1500)
    >>> deg = g.degree_property_map("in")
    >>> deg.a = 4 * (sqrt(deg.a) * 0.5 + 0.4)
984
985
    >>> ebet = gt.betweenness(g)[1]
    >>> ebet.a /= ebet.a.max() / 10.
986
987
988
989
990
991
992
993
994
995
    >>> 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
996
997
998
    ...               output="graph-draw.pdf")
    <...>

999
    .. testcleanup::
1000

1001
       conv_png("graph-draw.pdf")
1002

1003
1004
1005
    .. figure:: graph-draw.png
       :align: center
       :width: 80%
1006

1007
1008
1009
       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
       the edge betweenness centrality.
1010
1011
1012

    """

Tiago Peixoto's avatar
Tiago Peixoto committed
1013
1014
1015
1016
    vprops = vprops.copy() if vprops is not None else {}
    eprops = eprops.copy() if eprops is not None else {}

    props, kwargs = parse_props("vertex", kwargs)
1017
    props = _convert_props(props, "v", g, kwargs.get("vcmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
1018
1019
    vprops.update(props)
    props, kwargs = parse_props("edge", kwargs)
1020
    props = _convert_props(props, "e", g, kwargs.get("ecmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
1021
1022
1023
    eprops.update(props)

    if pos is None:
1024
        if (g.num_vertices() > 2 and output is None and
1025
1026
            not inline and kwargs.get("update_layout", True) and
            mplfig is None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
            L = np.sqrt(g.num_vertices())
            pos = random_layout(g, [L, L])
            if g.num_vertices() > 1000:
                if "multilevel" not in kwargs:
                    kwargs["multilevel"] = True
            if "layout_K" not in kwargs:
                kwargs["layout_K"] = _avg_edge_distance(g, pos) / 10
        else:
            pos = sfdp_layout(g)
1036
1037
    else:
        _check_prop_vector(pos, name="pos", floating=True)
1038
        if output is None and not inline and mplfig is None:
1039
1040
1041
1042
            if "layout_K" not in kwargs:
                kwargs["layout_K"] = _avg_edge_distance(g, pos)
            if "update_layout" not in kwargs:
                kwargs["update_layout"] = False
Tiago Peixoto's avatar
Tiago Peixoto committed
1043

1044
1045
1046
    if "pen_width" in eprops and "marker_size" not in eprops:
        pw = eprops["pen_width"]
        if isinstance(pw, PropertyMap):
1047
            pw = pw.copy("double")
1048
            pw.fa *= 2.75
1049
1050
1051
            eprops["marker_size"] = pw
        else:
            eprops["marker_size"] = pw * 2.75
1052

1053
1054
1055
    if "text" in eprops and "text_distance" not in eprops and "pen_width" in eprops:
        pw = eprops["pen_width"]
        if isinstance(pw, PropertyMap):
1056
            pw = pw.copy("double")
1057
            pw.fa *= 2
1058
1059
1060
1061
            eprops["text_distance"] = pw
        else:
            eprops["text_distance"] = pw * 2

1062
    if "text" in vprops and ("text_color" not in vprops or vprops["text_color"] == "auto"):
1063
        vcmap = kwargs.get("vcmap", default_cm)
1064
1065
1066
        bg = _convert(vertex_attrs.fill_color,
                      vprops.get("fill_color", _vdefaults["fill_color"]),
                      vcmap)
1067
1068
1069
        vprops["text_color"] = auto_colors(g, bg,
                                           vprops.get("text_position",
                                                      _vdefaults["text_position"]),
1070
                                           bg_color if bg_color is not None else [1., 1., 1., 1.])
1071

1072
    if mplfig is not None:
1073
1074
1075
1076
1077
1078
1079
1080
        ax = None
        if isinstance(mplfig, matplotlib.figure.Figure):
            ctr = ax = mplfig.gca()
        elif isinstance(mplfig, matplotlib.axes.Axes):
            ctr = ax = mplfig
        else:
            ctr = mplfig

1081
1082
1083
1084
1085
1086
1087
1088
1089
        x, y = ungroup_vector_property(pos, [0, 1])
        l, r = x.a.min(), x.a.max()
        b, t = y.a.min(), y.a.max()

        adjust_default_sizes(g, (r - l, t - b), vprops, eprops)

        artist = GraphArtist(g, pos, vprops, eprops, ax, vorder=vorder,
                             eorder=eorder, nodesfirst=nodesfirst, **kwargs)

1090
1091
        ctr.artists.append(artist)

1092
1093
1094
1095
1096
1097
        if fit_view != False and ax is not None:
            try:
                x, y, w, h = fit_view
            except TypeError:
                w = r - l
                h = t - b
1098
1099
1100
            if fit_view != True:
                w *= float(fit_view)
                h *= float(fit_view)
1101
            ax.set_xlim(l - w * .1, r + w * .1)
1102
            ax.set_ylim(t + h * .1, b - h * .1)
1103
1104

        return pos
1105

1106
1107
    output_file = output
    if inline and output is None:
1108
        if fmt == "auto":
1109
1110
1111
1112
            if output is None:
                fmt = "png"
            else:
                fmt = get_file_fmt(output)
1113
1114
        output = io.BytesIO()

1115
    if output is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1116
        return interactive_window(g, pos, vprops, eprops, vorder, eorder,
1117
                                  nodesfirst, geometry=output_size,
1118
                                  fit_view=fit_view, **kwargs)
Tiago Peixoto's avatar
Tiago Peixoto committed
1119
    else:
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
        adjust_default_sizes(g, output_size, vprops, eprops)

        if ink_scale != 1:
            scale_ink(ink_scale, vprops, eprops)

        if inline and fmt != "svg":
            output_size = [int(x * inline_scale) for x in output_size]
            scale_ink(inline_scale, vprops, eprops)

        if fit_view != False:
            try:
                x, y, w, h = fit_view
                zoom = min(output_size[0] / w, output_size[1] / h)
            except TypeError:
                pad = fit_view if fit_view is not True else 0.9
                output_size = list(output_size)
                x, y, zoom = fit_to_view_ink(g, pos, output_size, vprops,
                                             eprops, adjust_aspect, pad=pad)
        else:
1139
            x, y, zoom = 0, 0, 1
1140
1141


1142
        if isinstance(output, str):
1143
1144
1145
1146
1147
            out, auto_fmt = open_file(output, mode="wb")
        else:
            out = output
            if fmt == "auto":
                raise ValueError("File format must be specified.")
Tiago Peixoto's avatar
Tiago Peixoto committed
1148
1149

        if fmt == "auto":
1150
            fmt = auto_fmt
Tiago Peixoto's avatar
Tiago Peixoto committed
1151
1152
1153
1154
        if fmt == "pdf":
            srf = cairo.PDFSurface(out, output_size[0], output_size[1])
        elif fmt == "ps":
            srf = cairo.PSSurface(out, output_size[0], output_size[1])
Tiago Peixoto's avatar
Tiago Peixoto committed
1155
1156
1157
        elif fmt == "eps":
            srf = cairo.PSSurface(out, output_size[0], output_size[1])
            srf.set_eps(True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1158
1159
        elif fmt == "svg":
            srf = cairo.SVGSurface(out, output_size[0], output_size[1])
1160
            srf.restrict_to_version(cairo.SVG_VERSION_1_2)
Tiago Peixoto's avatar
Tiago Peixoto committed
1161
1162
1163
1164
1165
1166
1167
1168
1169
        elif fmt == "png":
            srf = cairo.ImageSurface(cairo.FORMAT_ARGB32, output_size[0],
                                     output_size[1])
        else:
            raise ValueError("Invalid format type: " + fmt)

        cr = cairo.Context(srf)

        cr.scale(zoom, zoom)
1170
        cr.translate(-x, -y)
Tiago Peixoto's avatar
Tiago Peixoto committed
1171

1172
1173
1174
1175
1176
        if bg_color is not None:
            cr.set_source_rgba(bg_color[0], bg_color[1],
                               bg_color[2], bg_color[3])
            cr.paint()

Tiago Peixoto's avatar
Tiago Peixoto committed
1177
        cairo_draw(g, pos, cr, vprops, eprops, vorder, eorder,
1178
                   nodesfirst, **kwargs)
1179

1180
        srf.flush()