cairo_draw.py 101 KB
Newer Older
1001
1002
1003
1004
1005

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

1006
1007
1008
    >>> g = gt.price_network(1500)
    >>> deg = g.degree_property_map("in")
    >>> deg.a = 4 * (sqrt(deg.a) * 0.5 + 0.4)
1009
1010
    >>> ebet = gt.betweenness(g)[1]
    >>> ebet.a /= ebet.a.max() / 10.
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
    >>> 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
1021
1022
1023
    ...               output="graph-draw.pdf")
    <...>

1024
1025
1026
1027
1028
1029
1030
1031
1032
    .. 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")


1033
1034
1035
    .. figure:: graph-draw.*
        :align: center

1036
1037
        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
1038
        the edge betweenness centrality.
1039
1040
1041

    """

Tiago Peixoto's avatar
Tiago Peixoto committed
1042
1043
1044
1045
    vprops = vprops.copy() if vprops is not None else {}
    eprops = eprops.copy() if eprops is not None else {}

    props, kwargs = parse_props("vertex", kwargs)
1046
    props = _convert_props(props, "v", g, kwargs.get("vcmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
1047
1048
    vprops.update(props)
    props, kwargs = parse_props("edge", kwargs)
1049
    props = _convert_props(props, "e", g, kwargs.get("ecmap", default_cm))
Tiago Peixoto's avatar
Tiago Peixoto committed
1050
1051
1052
    eprops.update(props)

    if pos is None:
1053
        if (g.num_vertices() > 2 and output is None and
1054
1055
            not inline and kwargs.get("update_layout", True) and
            mplfig is None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
            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)
1065
1066
    else:
        _check_prop_vector(pos, name="pos", floating=True)
1067
        if output is None and not inline:
1068
1069
1070
1071
            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
1072

1073
1074
1075
    if "pen_width" in eprops and "marker_size" not in eprops:
        pw = eprops["pen_width"]
        if isinstance(pw, PropertyMap):
1076
            pw = pw.copy("double")
1077
            pw.fa *= 2.75
1078
1079
1080
            eprops["marker_size"] = pw
        else:
            eprops["marker_size"] = pw * 2.75
1081

1082
1083
1084
    if "text" in eprops and "text_distance" not in eprops and "pen_width" in eprops:
        pw = eprops["pen_width"]
        if isinstance(pw, PropertyMap):
1085
            pw = pw.copy("double")
1086
            pw.fa *= 2
1087
1088
1089
1090
            eprops["text_distance"] = pw
        else:
            eprops["text_distance"] = pw * 2

1091
    if "text" in vprops and ("text_color" not in vprops or vprops["text_color"] == "auto"):
1092
        vcmap = kwargs.get("vcmap", default_cm)
1093
1094
1095
1096
        bg = _convert(vertex_attrs.fill_color,
                      vprops.get("fill_color", _vdefaults["fill_color"]),
                      vcmap)
        bg_color = kwargs.get("bg_color", [1., 1., 1., 1.])
1097
1098
1099
1100
1101
        vprops["text_color"] = auto_colors(g, bg,
                                           vprops.get("text_position",
                                                      _vdefaults["text_position"]),
                                           bg_color)

1102
    if mplfig is not None:
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
        ax = None
        if isinstance(mplfig, matplotlib.figure.Figure):
            ctr = ax = mplfig.gca()
        elif isinstance(mplfig, matplotlib.axes.Axes):
            ctr = ax = mplfig
        else:
            ctr = mplfig

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

1115
1116
1117
1118
1119
1120
1121
1122
1123
        if fit_view != False and ax is not None:
            try:
                x, y, w, h = fit_view
            except TypeError:
                x, y = ungroup_vector_property(pos, [0, 1])
                l, r = x.a.min(), x.a.max()
                b, t = y.a.min(), y.a.max()
                w = r - l
                h = t - b
1124
1125
1126
            if fit_view != True:
                w *= float(fit_view)
                h *= float(fit_view)
1127
1128
1129
1130
            ax.set_xlim(l - w * .1, r + w * .1)
            ax.set_ylim(b - h * .1, t + h * .1)

        return pos
1131

1132
1133
    output_file = output
    if inline and output is None:
1134
        if fmt == "auto":
1135
1136
1137
1138
            if output is None:
                fmt = "png"
            else:
                fmt = get_file_fmt(output)
1139
1140
        output = io.BytesIO()

1141
    if output is None:
Tiago Peixoto's avatar
Tiago Peixoto committed
1142
        return interactive_window(g, pos, vprops, eprops, vorder, eorder,
1143
                                  nodesfirst, geometry=output_size,
1144
                                  fit_view=fit_view, **kwargs)
Tiago Peixoto's avatar
Tiago Peixoto committed
1145
    else:
1146
        if isinstance(output, (str, unicode)):
1147
1148
1149
1150
1151
            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
1152
1153

        if fmt == "auto":
1154
            fmt = auto_fmt
Tiago Peixoto's avatar
Tiago Peixoto committed
1155
1156
1157
1158
        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
1159
1160
1161
        elif fmt == "eps":
            srf = cairo.PSSurface(out, output_size[0], output_size[1])
            srf.set_eps(True)
Tiago Peixoto's avatar
Tiago Peixoto committed
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
        elif fmt == "svg":
            srf = cairo.SVGSurface(out, output_size[0], output_size[1])
        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)

        adjust_default_sizes(g, output_size, vprops, eprops)
1173
1174
1175
        if fit_view != False:
            try:
                x, y, w, h = fit_view
1176
1177
                zoom = min(output_size[0] / w, output_size[1] / h)
                offset = (x * zoom, y * zoom)
1178
            except TypeError:
1179
                pad = fit_view if fit_view != True else 0.95
1180
1181
1182
1183
1184
1185
1186
                offset, zoom = fit_to_view(g, pos, output_size, vprops["size"],
                                           vprops["pen_width"], None,
                                           vprops.get("text", None),
                                           vprops.get("font_family",
                                                      _vdefaults["font_family"]),
                                           vprops.get("font_size",
                                                      _vdefaults["font_size"]),
1187
                                           pad, cr)
1188
            fit_view = False
Tiago Peixoto's avatar
Tiago Peixoto committed
1189
1190
1191
1192
1193
1194
1195
1196
1197
        else:
            offset, zoom = [0, 0], 1

        if "bg_color" in kwargs:
            bg_color = kwargs["bg_color"]
            del  kwargs["bg_color"]
            cr.set_source_rgba(bg_color[0], bg_color[1],
                               bg_color[2], bg_color[3])
            cr.paint()
1198

Tiago Peixoto's avatar
Tiago Peixoto committed
1199
1200
1201
1202
        cr.translate(offset[0], offset[1])
        cr.scale(zoom, zoom)

        cairo_draw(g, pos, cr, vprops, eprops, vorder, eorder,
1203
                   nodesfirst, fit_view=fit_view, **kwargs)
1204

1205
        srf.flush()
1206
        if fmt == "png":
Tiago Peixoto's avatar
Tiago Peixoto committed
1207
            srf.write_to_png(out)
1208
1209
        elif fmt == "svg":
            srf.finish()
1210
1211
1212

        del cr

1213
        if inline and output_file is None:
1214
1215
1216
            img = None
            if fmt == "png":
                img = IPython.display.Image(data=out.getvalue())
1217
            elif fmt == "svg":
1218
                img = IPython.display.SVG(data=out.getvalue())
1219
            elif img is None:
1220
1221
                inl_out = io.BytesIO()
                inl_srf = cairo.ImageSurface(cairo.FORMAT_ARGB32,
Pietro Battiston's avatar
Pietro Battiston committed
1222
1223
                                             output_size[0],
                                             output_size[1])
1224
1225
1226
1227
1228
1229
                inl_cr = cairo.Context(inl_srf)
                inl_cr.set_source_surface(srf, 0, 0)
                inl_cr.paint()
                inl_srf.write_to_png(inl_out)
                del inl_srf
                img = IPython.display.Image(data=inl_out.getvalue())
1230
            srf.finish()
1231
            IPython.display.display(img)
1232
        del srf
Tiago Peixoto's avatar
Tiago Peixoto committed
1233
        return pos
1234
1235
1236
1237
1238


def adjust_default_sizes(g, geometry, vprops, eprops, force=False):
    if "size" not in vprops or force:
        A = geometry[0] * geometry[1]
Tiago Peixoto's avatar
Tiago Peixoto committed
1239
1240
        N = max(g.num_vertices(), 1)
        vprops["size"] = np.sqrt(A / N) / 3.5
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263

    if "pen_width" not in vprops or force:
        size = vprops["size"]
        if isinstance(vprops["size"], PropertyMap):
            size = vprops["size"].fa.mean()
        vprops["pen_width"] = size / 10
        if "pen_width" not in eprops or force:
            eprops["pen_width"] = size / 10
        if "marker_size" not in eprops or force:
            eprops["marker_size"] = size * 0.8


def scale_ink(scale, vprops, eprops):
    if "size" not in vprops:
        vprops["size"] = _vdefaults["size"]
    if "pen_width" not in vprops:
        vprops["pen_width"] = _vdefaults["pen_width"]
    if "font_size" not in vprops:
        vprops["font_size"] = _vdefaults["font_size"]
    if "pen_width" not in eprops:
        eprops["pen_width"] = _edefaults["pen_width"]
    if "marker_size" not in eprops:
        eprops["marker_size"] = _edefaults["marker_size"]
1264
1265
1266
1267
    if "font_size" not in eprops:
        eprops["font_size"] = _edefaults["font_size"]
    if "text_distance" not in eprops:
        eprops["text_distance"] = _edefaults["text_distance"]
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285

    for props in [vprops, eprops]:
        if isinstance(props["pen_width"], PropertyMap):
            props["pen_width"].fa *= scale
        else:
            props["pen_width"] *= scale
    if isinstance(vprops["size"], PropertyMap):
        vprops["size"].fa *= scale
    else:
        vprops["size"] *= scale
    if isinstance(vprops["font_size"], PropertyMap):
        vprops["font_size"].fa *= scale
    else:
        vprops["font_size"] *= scale
    if isinstance(eprops["marker_size"], PropertyMap):
        eprops["marker_size"].fa *= scale
    else:
        eprops["marker_size"] *= scale
1286
1287
1288
1289
1290
1291
1292
1293
    if isinstance(eprops["font_size"], PropertyMap):
        eprops["font_size"].fa *= scale
    else:
        eprops["font_size"] *= scale
    if isinstance(eprops["text_distance"], PropertyMap):
        eprops["text_distance"].fa *= scale
    else:
        eprops["text_distance"] *= scale
1294
1295
1296

def get_bb(g, pos, size, pen_width, size_scale=1, text=None, font_family=None,
           font_size=None, cr=None):
1297
    size = size.fa if isinstance(size, PropertyMap) else size
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
    pen_width = pen_width.fa if isinstance(pen_width, PropertyMap) else pen_width
    pos_x, pos_y = ungroup_vector_property(pos, [0, 1])
    if text is not None and text != "":
        if not isinstance(size, PropertyMap):
            uniform = (not isinstance(font_size, PropertyMap) and
                       not isinstance(font_family, PropertyMap))
            size = np.ones(len(pos_x.fa)) * size
        else:
            uniform = False
        for i, v in enumerate(g.vertices()):
            ff = font_family[v] if isinstance(font_family, PropertyMap) \
               else font_family
            cr.select_font_face(ff)
1311
            fs = font_size[v] if isinstance(font_size, PropertyMap) \
1312
               else font_size
1313
1314
            if not isinstance(font_size, PropertyMap):
                cr.set_font_size(fs)
1315
            t = text[v] if isinstance(text, PropertyMap) else text
1316
            if not isinstance(t, (str, unicode)):
1317
1318
1319
1320
1321
1322
1323
                t = str(t)
            extents = cr.text_extents(t)
            s = max(extents[2], extents[3]) * 1.4
            size[i] = max(size[i] * size_scale, s) / size_scale
            if uniform:
                size[:] = size[i]
                break
1324
    sl = label_self_loops(g)
1325
    slm = sl.fa.max() * 0.75 if g.num_edges() > 0 else 0
1326
    delta = (size * size_scale * (slm + 1)) / 2 + pen_width * 2
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
    x_range = [pos_x.fa.min(), pos_x.fa.max()]
    y_range = [pos_y.fa.min(), pos_y.fa.max()]
    x_delta = [x_range[0] - (pos_x.fa - delta).min(),
               (pos_x.fa + delta).max() - x_range[1]]
    y_delta = [y_range[0] - (pos_y.fa - delta).min(),
               (pos_y.fa + delta).max() - y_range[1]]
    return x_range, y_range, x_delta, y_delta


def fit_to_view(g, pos, geometry, size, pen_width, M=None, text=None,
1337
                font_family=None, font_size=None, pad=0.95, cr=None):
1338
1339
    if g.num_vertices() == 0:
        return [0, 0], 1
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
    if M is not None:
        pos_x, pos_y = ungroup_vector_property(pos, [0, 1])
        P = np.zeros((2, len(pos_x.fa)))
        P[0, :] = pos_x.fa
        P[1, :] = pos_y.fa
        T = np.zeros((2, 2))
        O = np.zeros(2)
        T[0, 0], T[1, 0], T[0, 1], T[1, 1], O[0], O[1] = M
        P = np.dot(T, P)
        P[0] += O[0]
        P[1] += O[1]
        pos_x.fa = P[0, :]
        pos_y.fa = P[1, :]
        pos = group_vector_property([pos_x, pos_y])
    x_range, y_range, x_delta, y_delta = get_bb(g, pos, size, pen_width,
                                                1, text, font_family,
                                                font_size, cr)
1357
1358
1359
1360
1361
1362
1363
1364
    dx = (x_range[1] - x_range[0])
    dy = (y_range[1] - y_range[0])
    if dx == 0:
        dx = 1
    if dy == 0:
        dy = 1
    zoom_x = (geometry[0] - sum(x_delta)) / dx
    zoom_y = (geometry[1] - sum(y_delta)) / dy
1365
1366
1367
1368
1369
    if np.isnan(zoom_x) or np.isinf(zoom_x) or zoom_x == 0:
        zoom_x = 1
    if np.isnan(zoom_y) or np.isinf(zoom_y) or zoom_y == 0:
        zoom_y = 1
    zoom = min(zoom_x, zoom_y) * pad
1370
1371
    empty_x = (geometry[0] - sum(x_delta)) - dx * zoom
    empty_y = (geometry[1] - sum(y_delta)) - dy * zoom
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
    offset = [-x_range[0] * zoom + empty_x / 2 + x_delta[0],
              -y_range[0] * zoom + empty_y / 2 + y_delta[0]]
    return offset, zoom


def transform_scale(M, scale):
    p = M.transform_distance(scale / np.sqrt(2),
                             scale / np.sqrt(2))
    return np.sqrt(p[0] ** 2 + p[1] ** 2)

1382
1383
def get_hierarchy_control_points(g, t, tpos, beta=0.8, cts=None, is_tree=True,
                                 max_depth=None):
Tiago Peixoto's avatar
Tiago Peixoto committed
1384
    r"""Return the Bézier spline control points for the edges in ``g``, given the hierarchical structure encoded in graph `t`.
1385
1386
1387
1388
1389
1390
1391
1392
1393

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be drawn.
    t : :class:`~graph_tool.Graph`
        Directed graph containing the hierarchy of ``g``. It must be a directed
        tree with a single root. The direction of the edges point from the root
        to the leaves, and the vertices in ``t`` with index in the range
Tiago Peixoto's avatar
Tiago Peixoto committed
1394
        :math:`[0, N-1]`, with :math:`N` being the number of vertices in ``g``,
1395
        must correspond to the respective vertex in ``g``.
1396
    tpos : :class:`~graph_tool.VertexPropertyMap`
1397
1398
        Vector-valued vertex property map containing the x and y coordinates of
        the vertices in graph ``t``.
1399
    beta : ``float`` (optional, default: ``0.8`` or :class:`~graph_tool.EdgePropertyMap`)
1400
        Edge bundling strength. For ``beta == 0`` the edges are straight lines,
1401
1402
1403
        and for ``beta == 1`` they strictly follow the hierarchy. This can be
        optionally an edge property map, which specified a different bundling
        strength for each edge.
1404
    cts : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``)
1405
1406
        Edge property map of type ``vector<double>`` where the control points
        will be stored.
1407
1408
1409
    is_tree : ``bool`` (optional, default: ``True``)
        If ``True``, ``t`` must be a directed tree, otherwise it can be any
        connected graph.
1410
1411
1412
    max_depth : ``int`` (optional, default: ``None``)
        If supplied, only the first ``max_depth`` bottom levels of the hierarchy
        will be used.
1413

1414
1415
1416
1417

    Returns
    -------

1418
    cts : :class:`~graph_tool.EdgePropertyMap`
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
        Vector-valued edge property map containing the Bézier spline control
        points for the edges in ``g``.

    Notes
    -----
    This is an implementation of the edge-bundling algorithm described in
    [holten-hierarchical-2006]_.


    Examples
    --------
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
    .. testsetup:: nested_cts

       gt.seed_rng(42)
       np.random.seed(42)

    .. doctest:: nested_cts

       >>> g = gt.collection.data["netscience"]
       >>> g = gt.GraphView(g, vfilt=gt.label_largest_component(g))
       >>> g.purge_vertices()
1440
       >>> state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
1441
       >>> t = gt.get_hierarchy_tree(state)[0]
1442
1443
1444
       >>> tpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1), weighted=True)
       >>> cts = gt.get_hierarchy_control_points(g, t, tpos)
       >>> pos = g.own_property(tpos)
1445
       >>> b = state.levels[0].b
Tiago Peixoto's avatar
Tiago Peixoto committed
1446
1447
1448
       >>> shape = b.copy()
       >>> shape.a %= 14
       >>> gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=shape, edge_control_points=cts,
1449
1450
1451
1452
1453
       ...               edge_color=[0, 0, 0, 0.3], vertex_anchor=0, output="netscience_nested_mdl.pdf")
       <...>

    .. testcleanup:: nested_cts

Tiago Peixoto's avatar
Tiago Peixoto committed
1454
       gt.graph_draw(g, pos=pos, vertex_fill_color=b, vertex_shape=shape, edge_control_points=cts, edge_color=[0, 0, 0, 0.3], vertex_anchor=0, output="netscience_nested_mdl.png")
1455
1456
1457
1458
1459
1460
1461

    .. figure:: netscience_nested_mdl.*
       :align: center

       Block partition of a co-authorship network, which minimizes the description
       length of the network according to the nested (degree-corrected) stochastic blockmodel.

1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472


    References
    ----------

    .. [holten-hierarchical-2006] Holten, D. "Hierarchical Edge Bundles:
       Visualization of Adjacency Relations in Hierarchical Data.", IEEE
       Transactions on Visualization and Computer Graphics 12, no. 5, 741–748
       (2006). :doi:`10.1109/TVCG.2006.147`
    """

1473
1474
1475
1476
    if cts is None:
        cts = g.new_edge_property("vector<double>")
    if cts.value_type() != "vector<double>":
        raise ValueError("cts property map must be of type 'vector<double>' not '%s' " % cts.value_type())
1477
1478
1479
1480

    u = GraphView(g, directed=True)
    tu = GraphView(t, directed=True)

1481
1482
1483
1484
1485
    if not isinstance(beta, PropertyMap):
        beta = u.new_edge_property("double", beta)
    else:
        beta = beta.copy("double")

1486
1487
1488
    if max_depth is None:
        max_depth = t.num_vertices()

1489
    tu = GraphView(tu, skip_vfilt=True)
1490
    tpos = tu.own_property(tpos)
1491
1492
    libgraph_tool_draw.get_cts(u._Graph__graph,
                               tu._Graph__graph,
1493
1494
                               _prop("v", tu, tpos),
                               _prop("e", u, beta),
1495
                               _prop("e", u, cts),
1496
                               is_tree, max_depth)
1497
    return cts
1498
1499
1500
1501
1502
1503
1504

#
# The functions and classes below depend on GTK
# =============================================
#

try:
1505
1506
    import gi
    gi.require_version('Gtk', '3.0')
1507
    from gi.repository import Gtk, Gdk, GdkPixbuf
1508
    from gi.repository import GObject as gobject
1509
1510
    from .gtk_draw import *
except (ImportError, RuntimeError) as e:
1511
    msg = "Error importing Gtk module: %s; GTK+ drawing will not work." % str(e)
1512
    warnings.warn(msg, RuntimeWarning)
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526

def gen_surface(name):
    fobj, fmt = open_file(name)
    if fmt in ["png", "PNG"]:
        sfc = cairo.ImageSurface.create_from_png(fobj)
        return sfc
    else:
        pixbuf = GdkPixbuf.Pixbuf.new_from_file(name)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, pixbuf.get_width(),
                                     pixbuf.get_height())
        cr = cairo.Context(surface)
        Gdk.cairo_set_source_pixbuf(cr, pixbuf, 0, 0)
        cr.paint()
        return surface
1527
#
1528
1529
# matplotlib
# ==========
1530
#
1531

1532
1533
1534
1535
1536
1537
1538
class GraphArtist(matplotlib.artist.Artist):
    """:class:`matplotlib.artist.Artist` specialization that draws
       :class:`graph_tool.Graph` instances.

    .. warning::

        Only Cairo-based backends are supported.
1539
1540
1541
1542

    """

    def __init__(self, g, pos, vprops, eprops, vorder, eorder,
1543
                nodesfirst, ax=None, **kwargs):
1544
1545
1546
1547
1548
1549
1550
1551
        matplotlib.artist.Artist.__init__(self)
        self.g = g
        self.pos = pos
        self.vprops = vprops
        self.eprops = eprops
        self.vorder = vorder
        self.eorder = eorder
        self.nodesfirst = nodesfirst
1552
        self.ax = ax
1553
1554
1555
1556
1557
        self.kwargs = kwargs

    def draw(self, renderer):
        if not isinstance(renderer, matplotlib.backends.backend_cairo.RendererCairo):
            raise NotImplementedError("graph plotting is supported only on Cairo backends")
1558
1559

        ctx = renderer.gc.ctx
1560
1561
1562
1563

        if not isinstance(ctx, cairo.Context):
            ctx = _UNSAFE_cairocffi_context_to_pycairo(ctx)

1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
        ctx.save()

        if self.ax is not None:
            m = self.ax.transData.get_affine().get_matrix()
            m = cairo.Matrix(m[0,0], m[1, 0], m[0, 1], m[1, 1], m[0, 2], m[1,2])
            ctx.set_matrix(m)

            l, r = self.ax.get_xlim()
            b, t = self.ax.get_ylim()
            ctx.rectangle(l, b, r-l, t-b)
            ctx.clip()

1576
1577
        # flip y direction
        x, y = ungroup_vector_property(self.pos, [0, 1])
1578
1579
        l, t, r, b = ctx.clip_extents()
        y.fa = b + t - y.fa
1580
        pos = group_vector_property([x, y])
1581

1582
        cairo_draw(self.g, pos, ctx, self.vprops, self.eprops,
Tiago Peixoto's avatar
Tiago Peixoto committed
1583
                   self.vorder, self.eorder, self.nodesfirst, **self.kwargs)
1584
1585

        ctx.restore()
1586
1587
1588
1589
1590
1591
1592


#
# Drawing hierarchies
# ===================
#

1593
1594
def draw_hierarchy(state, pos=None, layout="radial", beta=0.8, node_weight=None,
                   vprops=None, eprops=None, hvprops=None, heprops=None,
1595
                   subsample_edges=None, rel_order="degree", deg_size=True,
1596
                   vsize_scale=1, hsize_scale=1, hshortcuts=0, hide=0,
1597
                   bip_aspect=1., empty_branches=False, **kwargs):
1598
1599
1600
1601
1602
    r"""Draw a nested block model state in a circular hierarchy layout with edge
    bundling.

    Parameters
    ----------
1603
    state : :class:`~graph_tool.inference.nested_blockmodel.NestedBlockState`
1604
        Nested block state to be drawn.
1605
    pos : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``)
1606
1607
        If supplied, this specifies a vertex property map with the positions of
        the vertices in the layout.
1608
    layout : ``str`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``"radial"``)
1609
1610
        If ``layout == "radial"`` :func:`~graph_tool.draw.radial_tree_layout`
        will be used. If ``layout == "sfdp"``, the hierarchy tree will be
1611
1612
        positioned using :func:`~graph_tool.draw.sfdp_layout`. If ``layout ==
        "bipartite"`` a bipartite layout will be used. If instead a
1613
        :class:`~graph_tool.VertexPropertyMap` is provided, it must correspond to the
1614
1615
1616
        position of the hierarchy tree.
    beta : ``float`` (optional, default: ``.8``)
        Edge bundling strength.
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
    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. See :func:`~graph_tool.draw.graph_draw` for
        details.
    eprops : dict (optional, default: ``None``)
        Dictionary with the edge properties. Individual properties may also be
        given via the ``edge_<prop-name>`` parameters, where ``<prop-name>`` is
        the name of the property. See :func:`~graph_tool.draw.graph_draw` for
        details.
    hvprops : dict (optional, default: ``None``)
        Dictionary with the vertex properties for the *hierarchy tree*.
        Individual properties may also be given via the ``hvertex_<prop-name>``
        parameters, where ``<prop-name>`` is the name of the property. See
        :func:`~graph_tool.draw.graph_draw` for details.
    heprops : dict (optional, default: ``None``)
        Dictionary with the edge properties for the *hierarchy tree*. Individual
        properties may also be given via the ``hedge_<prop-name>`` parameters,
        where ``<prop-name>`` is the name of the property. See
        :func:`~graph_tool.draw.graph_draw` for details.
1637
1638
1639
    subsample_edges : ``int`` or list of :class:`~graph_tool.Edge` instances (optional, default: ``None``)
        If provided, only this number of random edges will be drawn. If the
        value is a list, it should include the edges that are to be drawn.
1640
    rel_order : ``str`` or ``None`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``"degree"``)
1641
1642
        If ``degree``, the vertices will be ordered according to degree inside
        each group, and the relative ordering of the hierarchy branches. If
1643
        instead a :class:`~graph_tool.VertexPropertyMap` is provided, its value will
1644
        be used for the relative ordering.
1645
1646
1647
    deg_size : ``bool`` (optional, default: ``True``)
        If ``True``, the (total) node degrees will be used for the default
        vertex sizes..
1648
    vsize_scale : ``float`` (optional, default: ``1.``)
1649
        Multiplicative factor for the default vertex sizes.
1650
    hsize_scale : ``float`` (optional, default: ``1.``)
1651
        Multiplicative factor for the default sizes of the hierarchy nodes.
1652
1653
1654
1655
1656
    hshortcuts : ``int`` (optional, default: ``0``)
        Include shortcuts to the number of upper layers in the hierarchy
        determined by this parameter.
    hide : ``int`` (optional, default: ``0``)
        Hide upper levels of the hierarchy.
1657
1658
    bip_aspect : ``float`` (optional, default: ``1.``)
        If ``layout == "bipartite"``, this will define the aspect ratio of layout.
1659
    empty_branches : ``bool`` (optional, default: ``False``)
1660
1661
        If ``empty_branches == False``, dangling branches at the upper layers
        will be pruned.
1662
    vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``)
1663
1664
1665
1666
        Parameters following the pattern ``vertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``vprops`` parameter. See :func:`~graph_tool.draw.graph_draw` for
        details.
1667
    edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``)
1668
1669
1670
        Parameters following the pattern ``edge_<prop-name>`` specify the edge
        property with name ``<prop-name>``, as an alternative to the ``eprops``
        parameter. See :func:`~graph_tool.draw.graph_draw` for details.
1671
    hvertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``)
1672
1673
1674
1675
        Parameters following the pattern ``hvertex_<prop-name>`` specify the
        vertex property with name ``<prop-name>``, as an alternative to the
        ``hvprops`` parameter. See :func:`~graph_tool.draw.graph_draw` for
        details.
1676
    hedge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``)
1677
1678
1679
        Parameters following the pattern ``hedge_<prop-name>`` specify the edge
        property with name ``<prop-name>``, as an alternative to the ``heprops``
        parameter. See :func:`~graph_tool.draw.graph_draw` for details.
1680
    **kwargs :
1681
1682
        All remaining keyword arguments will be passed to the
        :func:`~graph_tool.draw.graph_draw` function.
1683
1684
1685

    Returns
    -------
1686
    pos : :class:`~graph_tool.VertexPropertyMap`
1687
1688
1689
1690
        This is a vertex property map with the positions of
        the vertices in the layout.
    t : :class:`~graph_tool.Graph`
        This is a the hierarchy tree used in the layout.
1691
    tpos : :class:`~graph_tool.VertexPropertyMap`
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
        This is a vertex property map with the positions of
        the hierarchy tree in the layout.

    Examples
    --------
    .. testsetup:: draw_hierarchy

       gt.seed_rng(42)
       np.random.seed(42)

    .. doctest:: draw_hierarchy

       >>> g = gt.collection.data["celegansneural"]
       >>> state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
       >>> gt.draw_hierarchy(state, output="celegansneural_nested_mdl.pdf")
       (...)

    .. testcleanup:: draw_hierarchy

       gt.draw_hierarchy(state, output="celegansneural_nested_mdl.png")

    .. figure:: celegansneural_nested_mdl.*
       :align: center

       Hierarchical block partition of the C. elegans neural network, which
       minimizes the description length of the network according to the nested
       (degree-corrected) stochastic blockmodel.


    References
    ----------
    .. [holten-hierarchical-2006] Holten, D. "Hierarchical Edge Bundles:
       Visualization of Adjacency Relations in Hierarchical Data.", IEEE
       Transactions on Visualization and Computer Graphics 12, no. 5, 741–748
       (2006). :doi:`10.1109/TVCG.2006.147`
1727

1728
1729
1730
1731
    """

    g = state.g

1732
1733
    overlap = state.levels[0].overlap
    if overlap:
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
        ostate = state.levels[0]
        bv, bcin, bcout, bc = ostate.get_overlap_blocks()
        be = ostate.get_edge_blocks()
        orig_state = state
        state = state.copy()
        b = ostate.get_majority_blocks()
        state.levels[0] = BlockState(g, b=b)
    else:
        b = state.levels[0].b

    if subsample_edges is not None:
        emask = g.new_edge_property("bool", False)
        if isinstance(subsample_edges, int):
            eidx = g.edge_index.copy("int").fa.copy()
            numpy.random.shuffle(eidx)
            emask = g.new_edge_property("bool")
            emask.a[eidx[:subsample_edges]] = True
        else:
            for e in subsample_edges:
                emask[e] = True
        g = GraphView(g, efilt=emask)

1756
1757
    t, tb, tvorder = get_hierarchy_tree(state,
                                        empty_branches=empty_branches)
1758
1759

    if layout == "radial":
1760
1761
1762
        if rel_order == "degree":
            rel_order = g.degree_property_map("total")
        vorder = t.own_property(rel_order.copy())
1763
1764
        if pos is not None:
            x, y = ungroup_vector_property(pos, [0, 1])
1765
1766
            x.fa -= x.fa.mean()
            y.fa -= y.fa.mean()
1767
            angle = g.new_vertex_property("double")
1768
            angle.fa = (numpy.arctan2(y.fa, x.fa) + 2 * numpy.pi) % (2 * numpy.pi)
1769
            vorder = t.own_property(angle)
1770
1771
1772
        if node_weight is not None:
            node_weight = t.own_property(node_weight.copy())
            node_weight.a[node_weight.a == 0] = 1
1773
        tpos = radial_tree_layout(t, root=t.vertex(t.num_vertices() - 1,
1774
                                                   use_index=False),
1775
                                  node_weight=node_weight,
1776
1777
                                  rel_order=vorder,
                                  rel_order_leaf=True)
1778
    elif layout == "bipartite":
1779
        tpos = get_bip_hierachy_pos(state, aspect=bip_aspect,
1780
1781
                                    node_weight=node_weight)
        tpos = t.own_property(tpos)
1782
1783
1784
1785
1786
    elif layout == "sfdp":
        if pos is None:
            tpos = sfdp_layout(t)
        else:
            x, y = ungroup_vector_property(pos, [0, 1])
1787
1788
1789
            x.fa -= x.fa.mean()
            y.fa -= y.fa.mean()
            K = numpy.sqrt(x.fa.std() + y.fa.std()) / 10
1790
1791
            tpos = t.new_vertex_property("vector<double>")
            for v in t.vertices():
1792
                if int(v) < g.num_vertices(True):
1793
1794
1795
1796
                    tpos[v] = [x[v], y[v]]
                else:
                    tpos[v] = [0, 0]
            pin = t.new_vertex_property("bool")
1797
            pin.a[:g.num_vertices(True)] = True
1798
1799
1800
1801
            tpos = sfdp_layout(t, K=K, pos=tpos, pin=pin, multilevel=False)
    else:
        tpos = t.own_property(layout)

1802
1803
    hvvisible = t.new_vertex_property("bool", True)
    if hide > 0:
1804
        root = t.vertex(t.num_vertices(True) - 1)
1805
1806
1807
        dist = shortest_distance(t, source=root)
        hvvisible.fa = dist.fa >= hide

1808
1809
    pos = g.own_property(tpos.copy())

1810
    cts = get_hierarchy_control_points(g, t, tpos, beta,
1811
                                       max_depth=len(state.levels) - hshortcuts)
1812

1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
    vprops_orig = vprops
    eprops_orig = eprops
    hvprops_orig = vprops
    heprops_orig = eprops
    kwargs_orig = kwargs

    vprops = vprops.copy() if vprops is not None else {}
    eprops = eprops.copy() if eprops is not None else {}

    props, kwargs = parse_props("vertex", kwargs)
    vprops.update(props)
    vprops.setdefault("fill_color", b)
    vprops.setdefault("color", b)
1826
    vprops.setdefault("shape", _vdefaults["shape"] if not overlap else "pie")
1827
1828
    s = max(200 / numpy.sqrt(g.num_vertices()), 5)
    vprops.setdefault("size", prop_to_size(g.degree_property_map("total"), s/5, s))
1829
1830
1831
1832
1833

    if vprops.get("text_position", None) == "centered":
        angle, text_pos = centered_rotation(g, pos, text_pos=True)
        vprops["text_position"] = text_pos
        vprops["text_rotation"] = angle
1834
1835
1836
1837
1838
1839
1840
1841
        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[text_pos.a == numpy.pi] *= -1
            toffset = group_vector_property([xo, yo])
            vprops["text_offset"] = toffset
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854

    self_loops = label_self_loops(g, mark_only=True)
    if self_loops.fa.max() > 0:
        parallel_distance = vprops.get("size", _vdefaults["size"])
        if isinstance(parallel_distance, PropertyMap):
            parallel_distance = parallel_distance.fa.mean()
        cts_p = position_parallel_edges(g, pos, numpy.nan,
                                        parallel_distance)
        gu = GraphView(g, efilt=self_loops)
        for e in gu.edges():
            cts[e] = cts_p[e]


1855
1856
1857
1858
1859
1860
1861
    vprops = _convert_props(vprops, "v", g, kwargs.get("vcmap", default_cm),
                            pmap_default=True)

    props, kwargs = parse_props("edge", kwargs)
    eprops.update(props)
    eprops.setdefault("control_points", cts)
    eprops.setdefault("pen_width", _edefaults["pen_width"])
1862
    eprops.setdefault("color", list(_edefaults["color"][:-1]) + [.6])
1863
    eprops.setdefault("end_marker", "arrow" if g.is_directed() else "none")
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
    eprops = _convert_props(eprops, "e", g, kwargs.get("ecmap", default_cm),
                            pmap_default=True)

    hvprops = hvprops.copy() if hvprops is not None else {}
    heprops = heprops.copy() if heprops is not None else {}

    props, kwargs = parse_props("hvertex", kwargs)
    hvprops.update(props)

    blue = list(color_converter.to_rgba("#729fcf"))
    blue[-1] = .6
    hvprops.setdefault("fill_color", blue)
    hvprops.setdefault("color", [1, 1, 1, 0])
    hvprops.setdefault("shape", "square")
    hvprops.setdefault("size", 10)

1880
1881
1882
1883
    if hvprops.get("text_position", None) == "centered":
        angle, text_pos = centered_rotation(t, tpos, text_pos=True)
        hvprops["text_position"] = text_pos
        hvprops["text_rotation"] = angle
1884
1885
1886
1887
1888
1889
1890
1891
        toffset = hvprops.get("text_offset", None)
        if toffset is not None:
            if not isinstance(toffset, PropertyMap):
                toffset = t.new_vp("vector<double>", val=toffset)
            xo, yo = ungroup_vector_property(toffset, [0, 1])
            xo.a[text_pos.a == numpy.pi] *= -1
            toffset = group_vector_property([xo, yo])
            hvprops["text_offset"] = toffset
1892

1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
    hvprops = _convert_props(hvprops, "v", t, kwargs.get("vcmap", default_cm),
                             pmap_default=True)

    props, kwargs = parse_props("hedge", kwargs)
    heprops.update(props)

    heprops.setdefault("color", blue)
    heprops.setdefault("end_marker", "arrow")
    heprops.setdefault("marker_size", 8.)
    heprops.setdefault("pen_width", 1.)

    heprops = _convert_props(heprops, "e", t, kwargs.get("ecmap", default_cm),
                             pmap_default=True)
1906

1907
1908
    vcmap = kwargs.get("vcmap", default_cm)
    ecmap = kwargs.get("ecmap", vcmap)
1909
1910
1911

    B = state.levels[0].B

1912
    if overlap and "pie_fractions" not in vprops:
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
        vprops["pie_fractions"] = bc.copy("vector<double>")
        if "pie_colors" not in vprops:
            vertex_pie_colors = g.new_vertex_property("vector<double>")
            nodes = defaultdict(list)
            def conv(k):
                clrs = [vcmap(r / (B - 1) if B > 1 else 0) for r in k]
                return [item for l in clrs for item in l]
            map_property_values(bv, vertex_pie_colors, conv)
            vprops["pie_colors"] = vertex_pie_colors

    gradient = eprops.get("gradient", None)
1924
1925
    if gradient is None:
        gradient = g.new_edge_property("double")
1926
        gradient = group_vector_property([gradient])
1927
1928
        ecolor = eprops.get("ecolor", _edefaults["color"])
        eprops["gradient"] = gradient
1929
        if overlap:
1930
            for e in g.edges():                       # ******** SLOW *******
1931
                r, s = be[e]
1932
                if not g.is_directed() and e.source() > e.target():
1933
1934
1935
                    r, s = s, r
                gradient[e] = [0] + list(vcmap(r / (B - 1))) + \
                              [1] + list(vcmap(s / (B - 1)))
1936
1937
1938
1939
                if isinstance(ecolor, PropertyMap):
                    gradient[e][4] = gradient[e][9] = ecolor[e][3]
                else:
                    gradient[e][4] = gradient[e][9] = ecolor[3]
1940
1941
1942


    t_orig = t
1943
    t = GraphView(t,
1944
                  vfilt=lambda v: int(v) >= g.num_vertices(True) and hvvisible[v])
1945

1946
1947
    t_vprops = {}
    t_eprops = {}
1948

1949
1950
1951
1952
1953
1954
1955
    props = []
    for k in set(list(vprops.keys()) + list(hvprops.keys())):
        t_vprops[k] = (vprops.get(k, None), hvprops.get(k, None))
        props.append(t_vprops[k])
    for k in set(list(eprops.keys()) + list(heprops.keys())):
        t_eprops[k] = (eprops.get(k, None), heprops.get(k, None))
        props.append(t_eprops[k])
1956

1957
1958
1959
    props.append((pos, tpos))
    props.append((g.vertex_index, tb))
    props.append((b, None))
1960
1961
1962
1963
1964
    if "eorder" in kwargs:
        eorder = kwargs["eorder"]
        props.append((eorder,
                      t.new_ep(eorder.value_type(),
                               eorder.fa.max() + 1)))
1965

1966
    u, props = graph_union(g, t, props=props)
1967

1968
1969
1970
1971
1972
1973
1974
    for k in set(list(vprops.keys()) + list(hvprops.keys())):
        t_vprops[k] = props.pop(0)
    for k in set(list(eprops.keys()) + list(heprops.keys())):
        t_eprops[k] = props.pop(0)
    pos = props.pop(0)
    tb = props.pop(0)
    b = props.pop(0)
1975
1976
    if "eorder" in kwargs:
        eorder = props.pop(0)
1977
1978
1979

    def update_cts(widget, gg, picked, pos, vprops, eprops):
        vmask = gg.vertex_index.copy("int")
1980
        u = GraphView(gg, directed=False, vfilt=vmask.fa < g.num_vertices(True))
1981
        cts = eprops["control_points"]
1982
        get_hierarchy_control_points(u, t_orig, pos, beta, cts=cts,
1983
                                     max_depth=len(state.levels) - hshortcuts)
1984
1985
1986

    def draw_branch(widget, gg, key_id, picked, pos, vprops, eprops):
        if key_id == ord('b'):
1987
1988
            if picked is not None and not isinstance(picked, PropertyMap) and int(picked) > g.num_vertices(True):
                p = shortest_path(t_orig, source=t_orig.vertex(t_orig.num_vertices(True) - 1),
1989
1990
1991
1992
1993
1994
1995
                                  target=picked)[0]
                l = len(state.levels) - max(len(p), 1)

                bstack = state.get_bstack()
                bs = [s.vp["b"].a for s in bstack[:l+1]]
                bs[-1][:] = 0

1996
                if not overlap:
1997
1998
1999
2000
                    b = state.project_level(l).b
                    u = GraphView(g, vfilt=b.a == tb[picked])
                    u.vp["b"] = state.levels[0].b
                    u = Graph(u, prune=True)