Source code for graph_tool.draw.cairo_draw

#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# graph_tool -- a general graph manipulation python module
#
# Copyright (C) 2006-2026 Tiago de Paula Peixoto <tiago@skewed.de>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import os
import warnings
import numpy
from collections.abc import Iterable

from .. structure import shortest_distance, is_bipartite
from .. util import find_vertex
from .. import _check_prop_scalar, perfect_prop_hash

try:
    import cairo
except ImportError:
    msg = "Error importing cairo. Graph drawing will not work."
    warnings.warn(msg, RuntimeWarning)
    raise

default_cm = None
try:
    import matplotlib.artist
    import matplotlib.backends.backend_cairo
    import matplotlib.cm
    import matplotlib.colors
    from matplotlib.cbook import flatten
    default_clrs = list(matplotlib.cm.tab20.colors) + \
        list(matplotlib.cm.tab20b.colors)
    default_cm = matplotlib.cm.colors.ListedColormap(default_clrs)
    default_cm_bin = matplotlib.cm.colors.ListedColormap([[1, 1, 1, 1],
                                                          [0, 0, 0, 1]])
    has_draw_inline = 'inline' in matplotlib.get_backend()
    color_converter = matplotlib.colors.ColorConverter()
except ImportError:
    msg = "Error importing matplotlib module. Graph drawing will not work."
    warnings.warn(msg, RuntimeWarning)
    raise

try:
    import IPython.display
except ImportError:
    pass

import numpy as np
import gzip
import bz2
import zipfile
import copy
import io
from collections import defaultdict
from scipy.stats import rankdata

from .. import Graph, GraphView, PropertyMap, ungroup_vector_property,\
     group_vector_property, _check_prop, _check_props, _check_prop_vector, \
     map_property_values

from .. generation import label_parallel_edges, label_self_loops

from .. dl_import import dl_import
dl_import("from . import libgraph_tool_draw")
try:
    from .libgraph_tool_draw import vertex_attrs, edge_attrs, vertex_shape,\
        edge_marker, edge_gradient_type, edge_gradient_render, \
        vertex_attr_types, edge_attr_types
except ImportError:
    msg = "Error importing cairo-based drawing library. " + \
        "Was graph-tool compiled with cairomm support?"
    warnings.warn(msg, RuntimeWarning)

from .. draw import sfdp_layout, hfd_layout, random_layout, \
    _avg_edge_distance, radial_tree_layout, prop_to_size

from .. generation import graph_merge
from .. structure import shortest_path

_vdefaults = {
    "shape": "circle",
    "color": (0.6, 0.6, 0.6, 0.8),
    "fill_color": (0.6470588235294118, 0.058823529411764705, 0.08235294117647059, 0.8),
    "size": 5,
    "aspect": 1.,
    "rotation": 0.,
    "anchor": 1,
    "pen_width": 0.8,
    "halo": 0,
    "halo_color": [0., 0., 1., 0.5],
    "halo_size": 1.5,
    "text": "",
    "text_color": [0., 0., 0., 1.],
    "text_position": -1.,
    "text_rotation": 0.,
    "text_offset": [0., 0.],
    "text_out_width": 1.,
    "text_out_color": [0., 0., 0., 0.],
    "font_family": "serif",
    "font_slant": cairo.FONT_SLANT_NORMAL,
    "font_weight": cairo.FONT_WEIGHT_NORMAL,
    "font_size": 12.,
    "surface": None,
    "pie_fractions": [0.75, 0.25],
    "pie_colors": [default_cm(x) for x in range(10)],
    "zorder": 0.,
    "text_zorder": numpy.nan
    }

_edefaults = {
    "color": (0.1796875, 0.203125, 0.2109375, 0.8),
    "pen_width": 1,
    "start_marker": "none",
    "mid_marker": "none",
    "end_marker": "none",
    "marker_size": 4.,
    "mid_marker_pos": .5,
    "control_points": [],
    "gradient": [],
    "gradient_type": "path",
    "gradient_render": "native",
    "dash_style": [],
    "text": "",
    "text_color": (0., 0., 0., 1.),
    "text_distance": 5,
    "text_parallel": True,
    "text_out_width": 1.,
    "text_out_color": [0., 0., 0., 0.],
    "font_family": "serif",
    "font_slant": cairo.FONT_SLANT_NORMAL,
    "font_weight": cairo.FONT_WEIGHT_NORMAL,
    "font_size": 12.,
    "sloppy": False,
    "seamless": False,
    "trim": False,
    "zorder": 0.,
    "text_zorder": numpy.nan
    }

_vtypes = dict(vertex_attr_types)
_etypes = dict(edge_attr_types)

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]


def _check_enum(val, enum, name):
    # Validates the string values of an enumerated attribute.
    if isinstance(val, PropertyMap):
        if val.value_type() != "string":
            return
        g = val.get_graph()
        vals = set(val[x] for x in (g.vertices() if val.key_type() == "v"
                                    else g.edges()))
    elif isinstance(val, str):
        vals = [val]
    elif isinstance(val, (int, numpy.integer)):
        if int(val) not in enum.values:
            raise ValueError("Invalid value for %s: %s (valid values: %s)" %
                             (name, repr(val),
                              ", ".join('"%s"' % x for x in enum.names)))
        return
    else:
        return
    for v in vals:
        if v not in enum.names:
            raise ValueError("Invalid value for %s: %s (valid values: %s)" %
                             (name, repr(v),
                              ", ".join('"%s"' % x for x in enum.names)))

def _check_svg_gradient_render(eprops):
    # Mesh patterns are not supported in SVG output (they are only used for
    # path gradients).
    gradient = eprops.get("gradient", [])
    if not isinstance(gradient, PropertyMap) and len(gradient) == 0:
        return
    if eprops.get("gradient_type", "path") in ["linear",
                                               int(edge_gradient_type.linear)]:
        return
    val = eprops.get("gradient_render", _edefaults["gradient_render"])
    mesh = int(edge_gradient_render.mesh)
    if isinstance(val, PropertyMap):
        if val.value_type() == "string":
            is_mesh = any(val[e] == "mesh" for e in val.get_graph().edges())
        else:
            is_mesh = (val.fa == mesh).any()
    elif isinstance(val, str):
        is_mesh = val == "mesh"
    else:
        is_mesh = int(val) == mesh
    if is_mesh:
        raise ValueError("edge_gradient_render='mesh' is not supported in " +
                         "SVG output, which has no mesh patterns; use " +
                         "'strips', 'patches', 'raster', or 'native' " +
                         "(an image in SVG) instead")

def shape_from_prop(shape, enum):
    if isinstance(shape, PropertyMap):
        g = shape.get_graph()
        if shape.key_type() == "v":
            prop = g.new_vertex_property("int")
            descs = g.vertices()
        else:
            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 len(prop.fa) > 0 and prop.fa.min() < rg[0]:
                prop.fa += rg[0]
            prop.fa -= rg[0]
            prop.fa %= rg[1] - rg[0] + 1
            prop.fa += rg[0]
        return prop
    if isinstance(shape, str):
        return int(getattr(enum, shape))
    else:
        return shape

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

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(".", "")
    return out, fmt

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


def surface_from_prop(surface):
    if isinstance(surface, PropertyMap):
        prop = surface.get_graph().new_property(surface.key_type(), "object")
        if surface.value_type() == "string":
            # (the surfaces are generated once for each distinct value)
            map_property_values(surface, prop, gen_surface)
        elif surface.value_type() == "python::object":
            def check(x):
                if x is not None and not isinstance(x, cairo.Surface):
                    raise ValueError("Invalid value type for surface property: " +
                                     str(type(x)))
                return x
            map_property_values(surface, prop, check)
        else:
            raise ValueError("Invalid value type for surface property: " +
                             surface.value_type())
        return prop

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

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

def centered_rotation(g, pos, text_pos=True):
    x, y = ungroup_vector_property(pos, [0, 1])
    cm = (x.fa.mean(), y.fa.mean())
    dx = x.fa - cm[0]
    dy = y.fa - cm[1]
    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

def choose_cm(prop, cm):
    is_bin = False
    if prop.value_type() in ["double", "long double"]:
        is_seq = True
    else:
        ph = perfect_prop_hash([prop])[0].fa
        m = ph.max() if len(ph) > 0 else 0
        if m >= default_cm.N:
            is_seq = True
        else:
            is_seq = False
            if m == 1:
                is_bin = True

    if cm is not None:
        # integer values are categories only for a qualitative colormap (a
        # short list of colors); otherwise they are mapped like the
        # continuous values
        if prop.value_type() not in ["double", "long double"]:
            is_seq = not (isinstance(cm, matplotlib.colors.ListedColormap)
                          and cm.N < 256)
        return cm, is_seq

    if prop.key_type() == "e":
        if is_bin:
            cm = matplotlib.cm.RdGy
            is_seq = True
        elif not is_seq:
            cm = default_cm
        else:
            cm = matplotlib.cm.binary
    else:
        if is_bin:
            cm = default_cm_bin
        elif not is_seq:
            cm = default_cm
        else:
            cm = matplotlib.cm.magma
    return cm, is_seq

def _convert(attr, val, cmap, vnorm, pmap_default=False, g=None, k=None):
    try:
        cmap, alpha = cmap
    except TypeError:
        alpha = None

    if attr == vertex_attrs.shape:
        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 [edge_attrs.gradient_type, edge_attrs.gradient_render]:
        if attr == edge_attrs.gradient_type:
            enum, name = edge_gradient_type, "edge_gradient_type"
        else:
            enum, name = edge_gradient_render, "edge_gradient_render"
        _check_enum(val, enum, name)
        new_val = shape_from_prop(val, enum)
        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]:
        if isinstance(val, PropertyMap):
            if val.value_type() in ["vector<double>", "vector<long double>"]:
                return val
            if val.value_type() in ["vector<int16_t>", "vector<int32_t>",
                                    "vector<int64_t>", "vector<bool>"]:
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
                counts, x = _get_vector_values(g, val)
                if len(x) == 0:
                    return new_val
                rg = [x.min(), x.max()]
                if rg[0] == rg[1]:
                    rg[1] = 1
                if cmap is None:
                    cmap = default_cm
                c = np.asarray(cmap((x - rg[0]) / (rg[1] - rg[0]),
                                    alpha=alpha), dtype="float")
                _set_vector_values(g, new_val, counts * 4, c.ravel())
                return new_val
            if val.value_type() == "vector<string>":
                g = val.get_graph()
                new_val = g.new_vertex_property("vector<double>")
                map_property_values(val, new_val,
                                    lambda y: flatten([color_converter.to_rgba(x) for x in y]))
                return new_val
            if val.value_type() == "python::object":
                try:
                    g = val.get_graph()
                    new_val = g.new_vertex_property("vector<double>")
                    def conv(y):
                        try:
                            return [float(x) for x in flatten(y)]
                        except ValueError:
                            return list(flatten([color_converter.to_rgba(x)
                                                 for x in y]))
                    map_property_values(val, new_val, conv)
                    return new_val
                except ValueError:
                    pass
        else:
            try:
                new_val = [float(x) for x in flatten(val)]
            except ValueError:
                try:
                    new_val = flatten(color_converter.to_rgba(x) for x in val)
                    new_val = list(new_val)
                except ValueError:
                    pass
            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.text_color, edge_attrs.text_color] and \
         _is_auto(val):
        # resolved later, by _auto_text_colors()
        return val
    elif attr in [vertex_attrs.color, vertex_attrs.fill_color,
                  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]:
        if isinstance(val, list):
            new_val = val
        elif isinstance(val, (tuple, np.ndarray)):
            new_val = list(val)
        elif isinstance(val, str):
            new_val = list(color_converter.to_rgba(val))
        elif isinstance(val, PropertyMap):
            if not val.is_writable():
                val = val.copy()
            if val.value_type() in ["vector<double>", "vector<long double>"]:
                new_val = val
            elif val.value_type() in ["int16_t", "int32_t", "int64_t", "double",
                                      "long double", "bool"]:
                cmap, is_seq = choose_cm(val, cmap)
                g = val.get_graph()
                if val.value_type() in ["int16_t", "int32_t", "int64_t"]:
                    if not is_seq and vnorm is None:
                        nval = val.copy()
                        nval.fa = rankdata(val.fa, method='dense') - 1
                    else:
                        nval = val
                else:
                    nval = val

                if len(nval.fa) > 0:
                    vrange = [nval.fa.min(), nval.fa.max()]
                else:
                    vrange = [0, 1]

                if vnorm is None:
                    if not is_seq:
                        def cnorm(x):
                            # bool values are uint8, for which cmap.N
                            # (e.g. 256) is out of bounds
                            return numpy.asarray(x, dtype="int64") % cmap.N
                    else:
                        cnorm = matplotlib.colors.Normalize(vmin=vrange[0],
                                                            vmax=vrange[1])
                else:
                    cnorm = vnorm
                    cnorm(vrange)  # for auto-scale, if needed

                g = val.get_graph()
                if val.key_type() == "v":
                    prop = g.new_vertex_property("vector<double>")
                else:
                    prop = g.new_edge_property("vector<double>")
                colors = numpy.asarray(cmap(cnorm(nval.fa), alpha=alpha))
                prop.set_2d_array(colors.reshape(-1, 4).T)
                new_val = prop
            elif val.value_type() == "string":
                g = val.get_graph()
                if val.key_type() == "v":
                    prop = g.new_vertex_property("vector<double>")
                else:
                    prop = g.new_edge_property("vector<double>")
                map_property_values(val, prop, color_converter.to_rgba)
                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]:
                return g.new_vertex_property("vector<double>", val=new_val)
            else:
                return g.new_edge_property("vector<double>", val=new_val)
        else:
            return new_val

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

    return val


def _attrs(attrs, d, g, cmap, vnorm):
    nattrs = {}
    defaults = {}
    for k, v in attrs.items():
        try:
            if d == "v":
                attr = getattr(vertex_attrs, k)
            else:
                attr = getattr(edge_attrs, k)
        except AttributeError:
            warnings.warn("Unknown attribute: " + str(k), UserWarning)
            continue
        if isinstance(v, PropertyMap):
            nattrs[int(attr)] = _check_prop(d, g,
                                            _convert(attr, v, cmap, vnorm))
        else:
            defaults[int(attr)] = _convert(attr, v, cmap, vnorm)
    return nattrs, defaults

def _convert_props(props, d, g, cmap, vnorm, pmap_default=False):
    nprops = {}
    for k, v in props.items():
        try:
            if d == "v":
                attr = getattr(vertex_attrs, k)
            else:
                attr = getattr(edge_attrs, k)
        except AttributeError:
            kind = "vertex" if d == "v" else "edge"
            warnings.warn(f"Unknown {kind} attribute: " + str(k), UserWarning)
            continue
        nprops[k] = _convert(attr, v, cmap, vnorm, pmap_default=pmap_default,
                             g=g, k=d)
    return nprops


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


@_check_props(v=("pos",))
def position_parallel_edges(g, pos, loop_angle=float("nan"),
                            parallel_distance=1):
    lp = label_parallel_edges(GraphView(g, directed=False))
    ll = label_self_loops(g)
    if isinstance(loop_angle, PropertyMap):
        angle = loop_angle
    else:
        angle = g.new_vertex_property("double", float(loop_angle))

    g = GraphView(g, directed=True)
    if ((len(lp.fa) == 0 or lp.fa.max() == 0) and
        (len(ll.fa) == 0 or ll.fa.max() == 0)):
        return []
    else:
        spline = g.new_edge_property("vector<double>")
        libgraph_tool_draw.put_parallel_splines(g,
                                                pos,
                                                lp,
                                                spline,
                                                angle,
                                                parallel_distance)
        return spline


def _get_vector_values(g, p):
    """Return the lengths of the vectors of the vector-valued property map
    ``p`` and their concatenated values, in the order of the vertices or edges
    of ``g`` (as given by :meth:`~graph_tool.Graph.get_vertices` or
    :meth:`~graph_tool.Graph.get_edges`)."""
    k = p.key_type()
    return libgraph_tool_draw.get_vector_values(g, p, k == "e")


def _set_vector_values(g, p, counts, vals):
    """Inverse of :func:`_get_vector_values`."""
    k = p.key_type()
    libgraph_tool_draw.set_vector_values(g, p, k == "e",
                                         np.ascontiguousarray(counts,
                                                              dtype="int64"),
                                         np.ascontiguousarray(vals,
                                                              dtype="float"))


def _segments(counts):
    """Return, for vectors with the given lengths that are concatenated, the
    index of the vector of each value and the position of the value within its
    vector."""
    counts = np.asarray(counts, dtype="int64")
    idx = np.repeat(np.arange(len(counts)), counts)
    start = np.cumsum(counts) - counts
    return idx, np.arange(len(idx)) - start[idx]


def _transform_control_points(g, cp, P, tP, transform):
    """Transform in place the control points ``cp`` of the edges of ``g`` with
    the function ``transform``, where ``P`` and ``tP`` are the vertex positions
    (indexed by vertex) before and after the transformation. Self-loops are
    skipped."""
    counts, vals = _get_vector_values(g, cp)
    edges = g.get_edges()
    if len(edges) == 0:
        return
    s, t = edges[:, 0], edges[:, 1]

    # Each edge has len // 2 points (an odd trailing value is left alone),
    # whose x coordinates are relative to the length of the edge, in its own
    # frame of reference, and whose y coordinates are absolute.
    eidx, k = _segments(counts // 2)
    xi = (np.cumsum(counts) - counts)[eidx] + 2 * k
    m = s[eidx] != t[eidx]
    eidx, xi = eidx[m], xi[m]
    x = np.stack([vals[xi], vals[xi + 1]], axis=1)

    def frame(P):
        d = P[t] - P[s]
        return P[s][eidx], np.arctan2(d[:, 1], d[:, 0])[eidx], \
            np.sqrt((d ** 2).sum(axis=1))[eidx]

    o, a, l = frame(P)
    x[:, 0] *= l
    c, sn = np.cos(a), np.sin(a)
    x = np.stack([c * x[:, 0] - sn * x[:, 1],
                  sn * x[:, 0] + c * x[:, 1]], axis=1) + o

    x = transform(x)

    o, a, l = frame(tP)
    x -= o
    c, sn = np.cos(a), np.sin(a)
    x = np.stack([(c * x[:, 0] + sn * x[:, 1]) / np.where(l > 0, l, 1),
                  -sn * x[:, 0] + c * x[:, 1]], axis=1)

    vals[xi] = x[:, 0]
    vals[xi + 1] = x[:, 1]
    _set_vector_values(g, cp, counts, vals)


def _put_self_loop_splines(g, pos, cts, parallel_distance):
    """Set the control points of the self-loops of ``g`` in ``cts``, as
    :func:`position_parallel_edges` does, leaving the other edges untouched."""
    loops = label_self_loops(g, mark_only=True)
    if len(loops.fa) == 0 or loops.fa.max() == 0:
        return
    u = GraphView(g, efilt=loops, directed=True)
    lp = u.new_edge_property("int")  # not used for self-loops
    angle = u.new_vertex_property("double", float("nan"))
    libgraph_tool_draw.put_parallel_splines(u, pos, lp, cts, angle,
                                            parallel_distance)


def parse_props(prefix, args):
    props = {}
    others = {}
    for k, v in list(args.items()):
        if v is None:
            continue
        if k.startswith(prefix + "_"):
            props[k.replace(prefix + "_", "")] = v
        else:
            others[k] = v
    return props, others

[docs] @_check_props(v=("pos", "vorder"), e=("eorder",)) def cairo_draw(g, pos, cr, vprops=None, eprops=None, vorder=None, eorder=None, nodesfirst=False, vcmap=None, vcnorm=None, ecmap=None, ecnorm=None, loop_angle=numpy.nan, parallel_distance=None, res=0, size_units="output", max_render_time=-1, **kwargs): r"""Draw a graph to a :class:`cairo.Context`. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be drawn. pos : :class:`~graph_tool.VertexPropertyMap` Vector-valued vertex property map containing the x and y coordinates of the vertices. cr : :class:`~cairo.Context` A :class:`~cairo.Context` instance. The raster images that are embedded in vector output (see ``gradient_render`` in the edge properties of :func:`~graph_tool.draw.graph_draw`) have the fallback resolution of its target surface, which is 300 ppi by default, and can be changed with :meth:`cairo.Surface.set_fallback_resolution`. 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``) 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. vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) If provided, defines the relative order in which the vertices are drawn. eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) If provided, defines the relative order in which the edges are drawn. nodesfirst : bool (optional, default: ``False``) If ``True``, the vertices are drawn first, otherwise the edges are. vcmap : :class:`matplotlib.colors.Colormap` or tuple (optional, default: ``None``) Vertex color map. Optionally, this may be a (:class:`matplotlib.colors.Colormap`, alpha) tuple. The values of scalar property maps are normalized to :math:`[0, 1]` (see ``vcnorm``), except for integer or boolean values with a :class:`matplotlib.colors.ListedColormap` of fewer than 256 colors (a qualitative colormap), in which case the distinct values are assigned the colors of the list in turn. vcnorm : :class:`matplotlib.colors.Normalize` (optional, default: ``None``) An object which, when called, normalizes vertex property values into the :math:`[0.0, 1.0]` interval, before passing to the ``vcmap`` colormap. ecmap : :class:`matplotlib.colors.Colormap` or tuple (optional, default: ``None``) Edge color map. Optionally, this may be a (:class:`matplotlib.colors.Colormap`, alpha) tuple. The values are mapped as for ``vcmap``. ecnorm : :class:`matplotlib.colors.Normalize` (optional, default: ``None``) An object which, when called, normalizes edge property values into the :math:`[0.0, 1.0]` interval, before passing to the ``ecmap`` colormap. loop_angle : float or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``numpy.nan``) 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. res : float (optional, default: ``0.``) If shape sizes fall below this value, simplified drawing is used. size_units : ``"output"`` or ``"layout"`` (optional, default: ``"output"``) Units of the vertex and edge sizes (vertex and marker sizes, pen widths, font sizes, text distances and offsets, dash patterns). If ``"output"``, they are in units of the output (e.g. pixels or points), independently of the transformation matrix of ``cr``. If ``"layout"``, they are in the same units as the positions, and are scaled together with them. The value of ``res`` is always in output units. max_render_time : int (optional, default: ``-1``) 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. vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``vertex_<prop-name>`` specify the vertex property with name ``<prop-name>``, as an alternative to the ``vprops`` parameter. edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``edge_<prop-name>`` specify the edge property with name ``<prop-name>``, as an alternative to the ``eprops`` parameter. Returns ------- 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. See Also -------- graph_draw: Draw a graph to a file or an interactive window draw_hierarchy: Draw a nested block model hierarchy """ if vorder is not None: _check_prop_scalar(vorder, name="vorder") if size_units not in ["output", "layout"]: raise ValueError("Invalid size_units: " + str(size_units)) vprops = {} if vprops is None else copy.copy(vprops) eprops = {} if eprops is None else copy.copy(eprops) 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) cr.save() if "control_points" not in eprops: if parallel_distance is None: parallel_distance = vprops.get("size", _vdefaults["size"]) if isinstance(parallel_distance, PropertyMap): parallel_distance = parallel_distance.fa.mean() # not in place, since it may be the value given in vprops parallel_distance = parallel_distance / 1.5 if size_units == "output": M = cr.get_matrix() scale = transform_scale(M, 1,) parallel_distance = parallel_distance / scale eprops["control_points"] = position_parallel_edges(g, pos, loop_angle, parallel_distance) if g.is_directed() and "end_marker" not in eprops: eprops["end_marker"] = "arrow" if vprops.get("text_position", None) == "centered": angle, tpos = centered_rotation(g, pos, text_pos=True) vprops["text_position"] = tpos vprops["text_rotation"] = angle 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 # the background is unknown here, and assumed to be white _auto_text_colors(g, vprops, eprops, vcmap=vcmap, vcnorm=vcnorm) vattrs, vdefaults = _attrs(vprops, "v", g, vcmap, vcnorm) eattrs, edefaults = _attrs(eprops, "e", g, ecmap, ecnorm) vdefs = _attrs(_vdefaults, "v", g, vcmap, vcnorm)[1] vdefs.update(vdefaults) edefs = _attrs(_edefaults, "e", g, ecmap, ecnorm)[1] edefs.update(edefaults) generator = libgraph_tool_draw.cairo_draw(g, pos, vorder, eorder, nodesfirst, vattrs, eattrs, vdefs, edefs, res, size_units == "layout", max_render_time, cr) if max_render_time >= 0: def gen(): for count in generator: yield count cr.restore() return gen() else: for count in generator: pass cr.restore()
def _rgba_array(color): """Colors (a single color, or an array of them) as an RGBA array.""" if isinstance(color, str): color = color_converter.to_rgba(color) c = np.array(color, dtype="float") if c.shape[-1] == 3: c = np.concatenate([c, np.ones(c.shape[:-1] + (1,))], axis=-1) return c def _over(color, back): """Composites the colors over the (opaque) background colors.""" a = color[..., 3:] c = color[..., :3] * a + back[..., :3] * (1 - a) return np.concatenate([c, np.ones(c.shape[:-1] + (1,))], axis=-1) def color_contrast(color): r"""Returns opaque black or white, whichever has the largest contrast (as defined by WCAG, i.e. the ratio of the relative luminances) with the given color (or array of colors), whose opacity is ignored.""" c = _rgba_array(color)[..., :3] c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) L = c @ [0.2126, 0.7152, 0.0722] white = 1.05 / (L + 0.05) > (L + 0.05) / 0.05 out = np.zeros(L.shape + (4,)) out[..., :3] = white[..., None] out[..., 3] = 1 return out def _is_auto(color): return isinstance(color, str) and color == "auto" def _auto_text_colors(g, vprops, eprops, bg_color=None, vcmap=None, vcnorm=None): r"""Replaces the text colors that are ``"auto"`` by black or white, whichever contrasts most with what is drawn behind the text: for the texts inside the vertices, their fill color (or the average color of their pie) over the background; otherwise the background, i.e. ``bg_color``, or white if it is not given (or transparent).""" back = _over(_rgba_array(bg_color if bg_color is not None else [1., 1., 1., 1.]), np.ones(4)) if _is_auto(eprops.get("text_color", None)): eprops["text_color"] = color_contrast(back).tolist() if not _is_auto(vprops.get("text_color", None)): return def get(k): val = vprops.get(k, _vdefaults[k]) if isinstance(val, PropertyMap): val = g.own_property(val) return val N = g.num_vertices() fill = _convert(vertex_attrs.fill_color, get("fill_color"), vcmap, vcnorm) if isinstance(fill, PropertyMap): fill = fill.get_2d_array(range(4)).T behind = np.broadcast_to(_rgba_array(fill), (N, 4)).copy() shape = _convert(vertex_attrs.shape, get("shape"), None, None) shape = shape.fa if isinstance(shape, PropertyMap) else np.full(N, shape) pie = np.nonzero(shape == int(vertex_shape.pie))[0] if len(pie) > 0: fracs = get("pie_fractions") colors = _convert(vertex_attrs.pie_colors, get("pie_colors"), None, None) def values(x): if isinstance(x, PropertyMap): return _get_vector_values(g, x) x = np.asarray(x, dtype="float").ravel() return np.full(N, len(x)), np.tile(x, N) # The mean of the pie colors, weighted by the fractions, with the # colors repeated cyclically if there are fewer colors than fractions. fcounts, f = values(fracs) ccounts, c = values(colors) vidx, k = _segments(fcounts) nc = (ccounts // 4)[vidx] ci = ((np.cumsum(ccounts) - ccounts)[vidx] + 4 * (k % np.maximum(nc, 1))) ci = np.where(nc > 0, ci, 0) f = np.where(nc > 0, f, 0) fsum = np.bincount(vidx, weights=f, minlength=N) mean = np.array([np.bincount(vidx, weights=f * c[ci + j], minlength=N) for j in range(4)]).T if len(c) > 0 else 0 sel = np.zeros(N, dtype="bool") sel[pie] = True sel &= fsum != 0 behind[sel] = mean[sel] / fsum[sel, None] behind = _over(behind, back[None, :]) tpos = get("text_position") if isinstance(tpos, PropertyMap): inside = tpos.fa < 0 else: inside = np.full(N, not isinstance(tpos, str) and tpos < 0) inside &= shape != int(vertex_shape.none) behind[~inside] = back c = g.new_vertex_property("vector<double>") c.set_2d_array(color_contrast(behind).T) vprops["text_color"] = c
[docs] def graph_draw(g, pos=None, vprops=None, eprops=None, vorder=None, eorder=None, nodesfirst=False, output_size=(600, 600), fit_view=True, fit_view_ink=None, adjust_aspect=True, ink_scale=1, inline=has_draw_inline, inline_scale=2, mplfig=None, yflip=True, output=None, fmt="auto", bg_color=None, antialias=None, raster_resolution=300, **kwargs): r"""Draw a graph to screen or to a file using :doc:`cairo <cairo:index>`. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be drawn. pos : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) Vector-valued vertex property map containing the x and y coordinates of the vertices. If not given, it will be computed using :func:`hfd_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``) 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. vorder : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) If provided, defines the relative order in which the vertices are drawn. eorder : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) If provided, defines the relative order in which the edges are drawn. nodesfirst : bool (optional, default: ``False``) If ``True``, the vertices are drawn first, otherwise the edges are. output_size : tuple of scalars (optional, default: ``(600,600)``) Size of the drawing canvas. The units will depend on the output format (pixels for the screen, points for PDF, etc). 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. This option is ignored if ``mplfig`` is given, in which case the axis limits are set by :mod:`matplotlib`'s autoscaling, or by calling :meth:`~graph_tool.draw.GraphArtist.fit_view` on the returned object. fit_view_ink : bool (optional, default: ``None``) If ``True``, and ``fit_view == True`` the drawing will be performed once to figure out the bounding box, before the actual drawing is made. Otherwise, only the vertex positions will be used for this purpose. If the value is ``None``, then it will be assumed ``True`` for networks of size 1,000 nodes or less, otherwise it will be assumed ``False``. 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. inline : bool (optional, default: ``has_draw_inline``) If ``True`` and an `IPython notebook <http://ipython.org/notebook>`_ is being used, an inline version of the drawing will be returned. By default, this is ``True`` only if an inline :mod:`matplotlib` backend is active. inline_scale : float (optional, default: ``2.``) Resolution scaling factor for inline images. mplfig : :mod:`matplotlib` container object (optional, default: ``None``) The ``mplfig`` object needs to have an ``add_artist()`` function. 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')``. If this option is used, a :class:`~graph_tool.draw.GraphArtist` object is returned. yflip : bool (optional, default: ``True``) If ``True`` and ``mplfig`` is given, the y axis of the :mod:`matplotlib` axes will be inverted (if it is not already), which reproduces the orientation of the output when ``mplfig is None``. The axis limits can then be set with :meth:`~graph_tool.draw.GraphArtist.fit_view`, which also sets the direction of the y axis. output : string or file object (optional, default: ``None``) Output file name (or object). If not given, the graph will be displayed via :func:`interactive_window`. fmt : string (optional, default: ``"auto"``) Output file format. Possible values are ``"auto"``, ``"ps"``, ``"eps"``, ``"pdf"``, ``"svg"``, and ``"png"``. If the value is ``"auto"``, the format is guessed from the ``output`` parameter. bg_color : str or sequence (optional, default: ``None``) Background color. The default is transparent. antialias : :class:`cairo.Antialias` (optional, default: ``None``) If supplied, this will set the antialiasing mode of the cairo context. raster_resolution : float (optional, default: ``300``) Resolution, in pixels per inch, of the raster images embedded in vector output (PDF, PostScript, EPS, and SVG): the gradients along curved edges with ``edge_gradient_render == "raster"`` (or ``"native"`` in SVG and PostScript), and the parts that cairo itself rasterizes. It is the fallback resolution of the cairo surface (see :meth:`cairo.Surface.set_fallback_resolution`), whose default is the same. The images of the gradients are limited to 8192 pixels along each side, beyond which their resolution is reduced. With ``mplfig``, the fallback resolution of the surface of matplotlib is used instead. res : float (optional, default: ``2.``) If both endpoints of an edge are smaller than this size (in units of the output format, normally pixels or points), the edge is drawn as if ``edge_sloppy == True``; likewise, ``edge_seamless`` is ignored for markers smaller than this size. This speeds up the drawing of large networks considerably, with hardly any visible difference. This default only applies when ``output`` is given; for the interactive window, the value is ``5`` pixels. size_units : ``"output"`` or ``"layout"`` (optional, default: ``"output"``) Units of the vertex and edge sizes (vertex and marker sizes, pen widths, font sizes, text distances and offsets, dash patterns). If ``"output"``, they are in units of the output format (normally pixels or points), so that they do not depend on the extent of the layout or the zoom level. If ``"layout"``, they are in the same units as the positions, so that they scale with the drawing; in this case the default sizes are computed from the extent of the layout, rather than from ``output_size``, and in the interactive window the sizes follow the zoom. The value of ``res`` is always in output units. vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``vertex_<prop-name>`` specify the vertex property with name ``<prop-name>``, as an alternative to the ``vprops`` parameter. edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``edge_<prop-name>`` specify the edge property with name ``<prop-name>``, as an alternative to the ``eprops`` parameter. **kwargs Any extra parameters are passed to :func:`~graph_tool.draw.interactive_window`, :class:`~graph_tool.draw.GraphWindow`, :class:`~graph_tool.draw.GraphWidget`, and :func:`~graph_tool.draw.cairo_draw`. Returns ------- pos : :class:`~graph_tool.VertexPropertyMap` Vector vertex property map with the x and y coordinates of the vertices. selected : :class:`~graph_tool.VertexPropertyMap` (optional, only if ``output is None``) Boolean-valued vertex property map marking the vertices which were selected interactively. See Also -------- cairo_draw: Draw a graph to a Cairo context draw_hierarchy: Draw a nested block model hierarchy interactive_window: Interactive window for drawing a graph sfdp_layout: Multilevel force-directed layout Notes ----- .. rubric:: List of vertex properties .. table:: +----------------+---------------------------------------------------+------------------------+----------------------------------+ | 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.6, 0.6, 0.6, 0.8]`` | | | | ``floats`` | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | fill_color | Color used to fill the interior of the vertex. | ``str`` or list of | ``[0.647, 0.059, 0.082, 0.8]`` | | | | ``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 black or white, whichever | ``floats`` | | | | has the largest contrast with what is drawn | | | | | behind the text: the fill color (or the pie | | | | | colors) over the background for texts inside | | | | | the vertex, otherwise the background | | | | | (``bg_color``, or white if it is not given). | | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | 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, in the units given by | list of ``float`` | ``[0.0, 0.0]`` | | | ``size_units``. | | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | 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, which is drawn around | ``float`` | ``1.`` | | | the glyphs (only visible if ``text_out_color`` | | | | | is not transparent). | | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | 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 | First 10 colors of | | | ``shape=="pie"``. | ``float``. | ``default_cm`` | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | zorder | Order in which the vertex is drawn, relative to | ``float`` | ``0`` | | | all vertices and edges: the ones with larger | | | | | values are drawn on top. Ties are drawn in the | | | | | order given by ``nodesfirst``, ``vorder``, and | | | | | ``eorder``. | | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ | text_zorder | If given, the text of the vertex is drawn | ``float`` | ``nan`` | | | separately from it, with this z-order (see | | | | | ``zorder``). For instance, a large value draws | | | | | it on top of all vertices and edges. If ``nan``, | | | | | the text is drawn together with the vertex. | | | +----------------+---------------------------------------------------+------------------------+----------------------------------+ .. rubric:: List of edge properties .. table:: +------------------+---------------------------------------------------+------------------------+----------------------------------+ | 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). | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | start_marker, | Edge markers. Can be one of "none", "arrow", | ``str`` or ``int`` | ``none`` | | mid_marker, | "circle", "square", "diamond", or "bar". | | | | end_marker | Optionally, this might take a numeric value | | | | | corresponding to position in the list above. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | mid_marker_pos | Relative position of the middle marker. | ``float`` | ``0.5`` | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | 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`` | ``[]`` | | | 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 color 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. The offsets go from the | | | | | source to the target, and they are interpreted as | | | | | given by ``gradient_type``. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | gradient_type | How the offsets of the gradient are interpreted: | ``str`` or ``int`` | ``"path"`` | | | with ``"path"``, they are fractions of the length | | | | | along the edge, also for curved edges; with | | | | | ``"linear"``, they are fractions of the distance | | | | | between the end points, as in a linear gradient | | | | | between them, which follows the path only for | | | | | straight edges (for which both values are | | | | | equivalent). | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | gradient_render | How a ``"path"`` gradient along a curved edge is | ``str`` or ``int`` | ``"native"`` | | | rendered. It has no effect for straight edges and | | | | | ``"linear"`` gradients, which are always drawn as | | | | | a linear gradient, a vector pattern in every | | | | | format (including SVG and PostScript, also with | | | | | ``"native"``). With ``"mesh"``, the gradient is a | | | | | mesh pattern, which is exact and independent of | | | | | the resolution, but makes PDF files larger (about | | | | | 3 times for the edges of | | | | | :func:`~graph_tool.draw.draw_hierarchy`); it is | | | | | not supported in SVG output, which has no | | | | | displayable mesh patterns (a ``ValueError`` is | | | | | raised), and cairo renders translucent mesh | | | | | patterns incorrectly in PostScript. With | | | | | ``"raster"``, it is an image of the mesh at the | | | | | resolution of the output (for vector formats, the | | | | | ``raster_resolution`` of | | | | | :func:`~graph_tool.draw.graph_draw`, 300 ppi by | | | | | default), in every format. With ``"native"``, it | | | | | is the mesh, except in SVG and PostScript output, | | | | | where it is the image of ``"raster"``, for the | | | | | reasons above. With ``"strips"``, it is made of | | | | | strips with a linear gradient along each segment | | | | | of the flattened curve, which is vector output | | | | | also in SVG, at the cost of files 3 to 5 times | | | | | larger than with linear gradients, and of a | | | | | slower rendering of translucent gradients (about | | | | | 20 times with librsvg). With ``"patches"``, it is | | | | | made of pieces of solid color, short enough that | | | | | consecutive pieces differ by at most one level of | | | | | 8-bit color, as when Inkscape converts mesh | | | | | patterns, which avoids gradients at the cost of | | | | | even larger files. With ``"strips"`` and | | | | | ``"patches"``, an opacity that varies along the | | | | | edge may show faint seams between the pieces. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | 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. | | | | | The lengths are in the units given by | | | | | ``size_units``. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | text | Text to draw next to the edges. | ``str`` | ``""`` | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | text_color | Color used to draw the text. If the value is | ``str`` or list of | ``"auto"`` | | | ``"auto"``, it will be black or white, whichever | ``floats`` | | | | has the largest contrast with the background | | | | | (``bg_color``, or white if it is not given). | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | text_distance | Distance from the edge and its text. | ``float`` or ``int`` | ``5`` | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | text_parallel | If ``True`` the text will be drawn parallel to | ``bool`` | ``True`` | | | the edges. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | 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, which is drawn around | ``float`` | ``1.`` | | | the glyphs (only visible if ``text_out_color`` | | | | | is not transparent). | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | 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`` | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | sloppy | If ``False``, the parts of the edge line that lie | ``bool`` | ``False`` | | | inside the source and target vertices, or below | | | | | the edge markers, are clipped away, so that they | | | | | do not show through translucent vertices and | | | | | markers. If ``True``, the clipping is skipped, | | | | | which is significantly faster. See also the | | | | | ``res`` parameter. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | seamless | If ``True``, the edge line and its markers are | ``bool`` | ``False`` | | | composed as a single shape with uniform opacity, | | | | | without seams between them. This is | | | | | significantly slower, unless ``trim == True``. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | trim | If ``True``, the hidden parts of the edge line | ``bool`` | ``False`` | | | (see ``sloppy``) are cut off geometrically, | | | | | instead of being clipped, which is significantly | | | | | faster, and yields smaller vector output. The | | | | | result differs from clipping only at the scale of | | | | | the line width, where the line is cut. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | zorder | Order in which the edge is drawn, relative to | ``float`` | ``0`` | | | all vertices and edges: the ones with larger | | | | | values are drawn on top. Ties are drawn in the | | | | | order given by ``nodesfirst``, ``vorder``, and | | | | | ``eorder``. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ | text_zorder | If given, the text of the edge is drawn | ``float`` | ``nan`` | | | separately from it, with this z-order (see | | | | | ``zorder``). For instance, a large value draws | | | | | it on top of all vertices and edges. If ``nan``, | | | | | the text is drawn together with the edge. | | | +------------------+---------------------------------------------------+------------------------+----------------------------------+ With the default ``edge_gradient_render == "native"``, the edge gradients are rendered according to the shape of the edge, ``edge_gradient_type``, and the output format, as follows: .. csv-table:: :header: "Edge", "``edge_gradient_type``", "Output", "Rendering" "curved", "``""path""``", "SVG, PostScript, and EPS", "image as with ``""raster""``, at the resolution ``raster_resolution``" "curved", "``""path""``", "PDF, PNG, and other surfaces", "mesh pattern" "straight", "any", "any", "linear gradient" "curved", "``""linear""``", "any", "linear gradient" Examples -------- .. testcode:: :hide: np.random.seed(42) gt.seed_rng(42) from numpy import sqrt >>> g = gt.price_network(1500) >>> deg = g.degree_property_map("in") >>> deg.a = 4 * (sqrt(deg.a) * 0.5 + 0.4) >>> ebet = gt.betweenness(g)[1] >>> ebet.a /= ebet.a.max() / 10. >>> eorder = ebet.copy() >>> eorder.a *= -1 >>> pos = gt.hfd_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 ... output="graph-draw.pdf") <...> .. testcleanup:: conv_png("graph-draw.pdf") .. figure:: graph-draw.png :align: center :width: 80% 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. By default, all edges are drawn below all vertices. With ``edge_zorder`` and ``vertex_zorder`` they can be interleaved, and with ``vertex_text_zorder`` and ``edge_text_zorder`` the texts can be drawn separately, e.g. on top of everything else: >>> g = gt.collection.data["football"] >>> vlist, elist = gt.shortest_path(g, g.vertex(9), g.vertex(110)) >>> ecolor = g.new_ep("string", val="#aaaaaa") >>> ewidth = g.new_ep("double", val=1) >>> ez = g.new_ep("double") >>> vtext = g.new_vp("string") >>> for e in elist: ... ecolor[e] = "#cc0000" ... ewidth[e] = 6 ... ez[e] = 1 >>> for v in vlist: ... vtext[v] = g.vp.label[v] >>> gt.graph_draw(g, g.vp.pos, vertex_text=vtext, vertex_text_zorder=2, ... vertex_text_position=0, vertex_font_size=12, ... edge_color=ecolor, edge_pen_width=ewidth, edge_zorder=ez, ... output="graph-draw-zorder.pdf") <...> .. testcleanup:: conv_png("graph-draw-zorder.pdf") .. figure:: graph-draw-zorder.png :align: center :width: 80% A shortest path in the network of American football games, drawn on top of all vertices (``edge_zorder=1``), with the names of the teams on top of everything (``vertex_text_zorder=2``). For large graphs with edge markers, or for vector output, ``edge_trim`` draws the same figure considerably faster, and with smaller files, than the default clipping of the edges: >>> g = gt.collection.data["polblogs"] >>> g = gt.extract_largest_component(g, directed=False, prune=True) >>> gt.graph_draw(g, g.vp.pos, vertex_fill_color=g.vp.value, ... edge_marker_size=4, edge_pen_width=0.5, ... edge_color=[0, 0, 0, .3], edge_trim=True, ... output="graph-draw-trim.pdf") <...> .. testcleanup:: conv_png("graph-draw-trim.pdf") .. figure:: graph-draw-trim.png :align: center :width: 80% Network of hyperlinks between political blogs, drawn with ``edge_trim=True``. The PDF file is about three times smaller than with the default clipping. """ vprops = vprops.copy() if vprops is not None else {} eprops = eprops.copy() if eprops is not None else {} props, kwargs = parse_props("vertex", kwargs) props = _convert_props(props, "v", g, kwargs.get("vcmap", None), kwargs.get("vcnorm", None)) vprops.update(props) props, kwargs = parse_props("edge", kwargs) props = _convert_props(props, "e", g, kwargs.get("ecmap", None), kwargs.get("ecnorm", None)) eprops.update(props) if pos is None: if (g.num_vertices() > 2 and output is None and not inline and kwargs.get("update_layout", True) and mplfig is None): # the layout is obtained interactively, with the coarse graphs of # the hierarchical layout shown while they are laid out L = np.sqrt(g.num_vertices()) pos = random_layout(g, [L, L]) if "multilevel" not in kwargs: kwargs["multilevel"] = True else: pos = hfd_layout(g) else: pos = g.own_property(pos) _check_prop_vector(pos, name="pos", floating=True) if output is None and not inline and mplfig is None: if "update_layout" not in kwargs: kwargs["update_layout"] = False if "pen_width" in eprops and "marker_size" not in eprops: pw = eprops["pen_width"] if isinstance(pw, PropertyMap): pw = pw.copy("double") pw.fa *= 2.75 eprops["marker_size"] = pw else: eprops["marker_size"] = pw * 2.75 if "text" in eprops and "text_distance" not in eprops and "pen_width" in eprops: pw = eprops["pen_width"] if isinstance(pw, PropertyMap): pw = pw.copy("double") pw.fa *= 2 eprops["text_distance"] = pw else: eprops["text_distance"] = pw * 2 if "text" in vprops: vprops.setdefault("text_color", "auto") if "text" in eprops: eprops.setdefault("text_color", "auto") _auto_text_colors(g, vprops, eprops, bg_color, kwargs.get("vcmap", None), kwargs.get("vcnorm", None)) if mplfig is not None: ax = None if isinstance(mplfig, matplotlib.figure.Figure): ax = mplfig.gca() elif isinstance(mplfig, matplotlib.axes.Axes): ax = mplfig else: ax = mplfig adjust_default_sizes(g, get_bb(g, pos)[2:], vprops, eprops, min_pen_width=0) if ink_scale != 1: scale_ink(ink_scale, vprops, eprops, min_pen_width=0) artist = GraphArtist(g, pos, ax, vprops, eprops, vorder=vorder, eorder=eorder, nodesfirst=nodesfirst, **kwargs) ax.add_artist(artist) if (yflip and hasattr(ax, "yaxis_inverted") and not ax.yaxis_inverted()): ax.invert_yaxis() return artist output_file = output if inline and output is None: if fmt == "auto": if output is None: fmt = "png" else: fmt = get_file_fmt(output) output = io.BytesIO() layout_units = kwargs.get("size_units", "output") == "layout" min_pen_width = 0 if layout_units else 0.05 if output is None: if ink_scale != 1: scale_ink(ink_scale, vprops, eprops, min_pen_width=min_pen_width) return interactive_window(g, pos, vprops, eprops, vorder, eorder, nodesfirst, geometry=output_size, fit_view=fit_view, bg_color=bg_color, **kwargs) else: kwargs.setdefault("res", 2.) if layout_units: adjust_default_sizes(g, get_bb(g, pos)[2:], vprops, eprops, min_pen_width=0) else: adjust_default_sizes(g, output_size, vprops, eprops) if ink_scale != 1: scale_ink(ink_scale, vprops, eprops, min_pen_width=min_pen_width) if inline and fmt != "svg": output_size = [int(x * inline_scale) for x in output_size] if not layout_units: 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) if fit_view_ink is None: fit_view_ink = g.num_vertices() <= 1000 if fit_view_ink: x, y, zoom = fit_to_view_ink(g, pos, output_size, vprops, eprops, adjust_aspect, pad=pad, size_units=kwargs.get("size_units", "output")) else: x, y, zoom = fit_to_view(get_bb(g, pos), output_size, adjust_aspect=adjust_aspect, pad=pad) else: x, y, zoom = 0, 0, 1 if fmt == "svg" or (fmt == "auto" and isinstance(output, str) and get_file_fmt(output) == "svg"): _check_svg_gradient_render(eprops) if not raster_resolution > 0: raise ValueError("raster_resolution must be positive: " + repr(raster_resolution)) if isinstance(output, str): out, auto_fmt = open_file(output, mode="wb") else: out = output if fmt == "auto": raise ValueError("File format must be specified.") if fmt == "auto": fmt = auto_fmt 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]) elif fmt == "eps": srf = cairo.PSSurface(out, output_size[0], output_size[1]) srf.set_eps(True) elif fmt == "svg": srf = cairo.SVGSurface(out, output_size[0], output_size[1]) srf.restrict_to_version(cairo.SVG_VERSION_1_2) elif fmt == "png": srf = cairo.ImageSurface(cairo.FORMAT_ARGB32, output_size[0], output_size[1]) else: raise ValueError("Invalid format type: " + fmt) if fmt != "png": srf.set_fallback_resolution(raster_resolution, raster_resolution) cr = cairo.Context(srf) if antialias is not None: cr.set_antialias(antialias) cr.scale(zoom, zoom) cr.translate(-x, -y) if bg_color is not None: if isinstance(bg_color, str): bg_color = matplotlib.colors.to_rgba(bg_color) cr.set_source_rgba(bg_color[0], bg_color[1], bg_color[2], bg_color[3]) cr.paint() cairo_draw(g, pos, cr, vprops, eprops, vorder, eorder, nodesfirst, **kwargs) srf.flush() if fmt == "png": srf.write_to_png(out) elif fmt == "svg": srf.finish() del cr if inline and output_file is None: img = None if fmt == "png": img = IPython.display.Image(data=out.getvalue(), width=int(output_size[0]/inline_scale), height=int(output_size[1]/inline_scale)) elif fmt == "svg": img = IPython.display.SVG(data=out.getvalue()) elif img is None: inl_out = io.BytesIO() inl_srf = cairo.ImageSurface(cairo.FORMAT_ARGB32, output_size[0], output_size[1]) 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(), width=int(output_size[0]/inline_scale), height=int(output_size[1]/inline_scale)) srf.finish() IPython.display.display(img) del srf return pos
def adjust_default_sizes(g, geometry, vprops, eprops, force=False, min_pen_width=0.05): if "size" not in vprops or force: A = float(geometry[0]) * float(geometry[1]) N = max(g.num_vertices(), 1) vprops["size"] = np.sqrt(A / N) / 3.5 if "pen_width" not in vprops or force: size = vprops["size"] if isinstance(vprops["size"], PropertyMap): size = vprops["size"].fa.mean() vprops["pen_width"] = max(size / 10, min_pen_width) if "pen_width" not in eprops or force: eprops["pen_width"] = max(size / 10, min_pen_width) if "marker_size" not in eprops or force: eprops["marker_size"] = size * 0.8 if "font_size" not in vprops or force: size = vprops["size"] if isinstance(vprops["size"], PropertyMap): size = vprops["size"].fa.mean() vprops["font_size"] = size * .6 if "font_size" not in eprops or force: size = vprops["size"] if isinstance(vprops["size"], PropertyMap): size = vprops["size"].fa.mean() eprops["font_size"] = size * .6 def scale_ink(scale, vprops, eprops, copy=True, min_pen_width=0.05): vink_props = ["size", "pen_width", "font_size", "text_out_width"] eink_props = ["marker_size", "pen_width", "font_size", "text_distance", "text_out_width"] for ink_props, props, defaults in zip([vink_props, eink_props], [vprops, eprops], [_vdefaults, _edefaults]): for p in ink_props: if p not in props: props[p] = defaults[p] if isinstance(props[p], PropertyMap): if copy: props[p] = props[p].copy() props[p].fa *= scale if p == "pen_width": x = props[p].fa x[x<min_pen_width] = min_pen_width props[p].fa = x else: if copy: props[p] = props[p] * scale else: props[p] *= scale if p == "pen_width": props[p] = max(props[p], min_pen_width) # vector-valued lengths for p, props, defaults in [("text_offset", vprops, _vdefaults), ("dash_style", eprops, _edefaults)]: x = props.get(p, defaults[p]) if isinstance(x, PropertyMap): if copy or x.value_type() != "vector<double>": x = x.copy("vector<double>") g = x.get_graph() counts, vals = _get_vector_values(g, x) _set_vector_values(g, x, counts, vals * scale) else: x = [float(y) * scale for y in x] props[p] = x def get_bb(g, pos): if g.num_vertices() == 0: return 0, 0, 0, 0 pos_x, pos_y = ungroup_vector_property(pos, [0, 1]) x_range = [pos_x.fa.min(), pos_x.fa.max()] y_range = [pos_y.fa.min(), pos_y.fa.max()] return x_range[0], y_range[0], x_range[1] - x_range[0], y_range[1] - y_range[0] def fit_to_view(rec, output_size, adjust_aspect=False, pad=.9): x, y, w, h = rec if adjust_aspect and max(w, h) > 0: if h > w: output_size[0] = int(round(float(output_size[1] * w / h))) else: output_size[1] = int(round(float(output_size[0] * h / w))) zoom = max(w / output_size[0], h / output_size[1]) if zoom == 0: zoom = 1 else: zoom = 1 / zoom x -= (output_size[0] / zoom - w) / 2 y -= (output_size[1] / zoom - h) / 2 zoom *= pad x -= (1-pad) / 2 * output_size[0] / zoom y -= (1-pad) / 2 * output_size[1] / zoom return x, y, zoom def fit_to_view_ink(g, pos, output_size, vprops, eprops, adjust_aspect=False, pad=0.9, size_units="output", min_fill=0.5): # The ink extent in device units along each axis, as a function of the # zoom z, is max_i (z x_i + b_i) - min_j (z x_j - a_j), where the x_i are # positions in layout units (vertices, control points) and a_i, b_i the # sizes in output units of what is drawn around them (vertices, # self-loops, labels, markers). This is a convex, piecewise linear # function of z, and so is h(z), the largest ratio of the ink extent to # the available space over both axes. We seek the largest zoom with # h(z) <= 1, with secant steps that are exact on a linear piece. (A # single rescaling of the ink measured at one zoom fails when the fixed # sizes are not small compared to the scaled extent, e.g. with a single # vertex and its self-loops.) # # If the sizes in output units are so large that the positions would # span less than a fraction min_fill of the view (or the ink does not # fit at all, e.g. for a single vertex), they are scaled down in place # in vprops and eprops, so that the ink fits with the positions # spanning this fraction. T = [pad * output_size[0], pad * output_size[1]] def min_lw(lw, s): # work around cairo bug with small line widths (in output units) if isinstance(lw, PropertyMap): lw = lw.copy() x = lw.fa x[x < 0.05 * s] = 0.1 * s lw.fa = x else: lw = max(lw, 0.1 * s) return lw cache = {} def ink(zoom): if zoom not in cache: srf = cairo.RecordingSurface(cairo.Content.COLOR_ALPHA, None) cr = cairo.Context(srf) cr.scale(zoom, zoom) s = 1 / zoom if size_units == "layout" else 1 vp = dict(vprops, pen_width=min_lw(vprops.get("pen_width", 0.), s)) ep = dict(eprops, pen_width=min_lw(eprops.get("pen_width", 0.), s)) cairo_draw(g, pos, cr, vp, ep, size_units=size_units) ext = srf.ink_extents() cache[zoom] = (ext, max(ext[2] / T[0], ext[3] / T[1])) return cache[zoom] w, h = (float(x) for x in get_bb(g, pos)[2:]) degenerate = not (w > 0 or h > 0) if degenerate: z0 = 1. else: z0 = min(T[i] / d for i, d in enumerate([w, h]) if d > 0) # the ink extents are measured in whole device units tol = 1 / min(T) feasible = lambda hz: hz <= 1 + tol def solve(): # returns the zoom, and whether the ink fits h0 = ink(z0)[1] if h0 > 1: # The slope of h(z) is at most that of the positions alone, # hence this step does not overshoot, unless curved edges go # beyond the positions. z1 = (z0 - (h0 - 1) / max(w / T[0], h / T[1]) if not degenerate else 0) if z1 <= 0: z1 = z0 / 2 elif degenerate: z1 = 2 * z0 # the ink may grow with the zoom (layout units) else: return z0, True # the positions alone fill the view lo = z0 if feasible(h0) else None # largest feasible zoom hi = None if feasible(h0) else z0 # smallest infeasible zoom za, ha = z0, h0 zb = z1 for it in range(50): hb = ink(zb)[1] if feasible(hb): if lo is None or zb > lo: lo = zb if hb >= 1 - 2 * tol: break elif hi is None or zb < hi: hi = zb if lo is not None and hi is not None and hi - lo <= 1e-6 * hi: break s = (hb - ha) / (zb - za) if abs(s) * abs(zb) <= 1e-9 * max(hb, 1): # the ink does not change with the zoom return z0, lo is not None zn = zb + (1 - hb) / s if lo is not None and hi is not None: if not (lo < zn < hi): zn = np.sqrt(lo * hi) elif hi is not None: if zn <= 0 or zn >= hi: # by convexity, no zoom fits the ink in the view break elif zn <= lo: zn = 2 * lo za, ha, zb = zb, hb, zn if lo is None: return z0, False return lo, True for attempt in range(5): zoom, fits = solve() zt = z0 if degenerate else min_fill * z0 if fits and (degenerate or zoom >= zt * (1 - tol)): break # Shrink the sizes in output units by a factor c such that the ink # fits at zoom zt, assuming that the extent is the sum of the # positions' and the shrunk sizes' parts. p = 0 if degenerate else min_fill M = ink(zt)[1] - p if M <= 0 or size_units == "layout": break c = (1 - p) / M if c >= 1: break scale_ink(c, vprops, eprops) cache.clear() ext = ink(zoom)[0] if adjust_aspect: # shrink the axis with the smaller ink extent relative to the view r = [ext[2] / T[0], ext[3] / T[1]] i = 1 if r[1] < r[0] else 0 if ext[2 + i] > 0: output_size[i] = min(output_size[i], max(int(round(ext[2 + i] / pad)), 1)) # center the ink x = (ext[0] + ext[2] / 2 - output_size[0] / 2) / zoom y = (ext[1] + ext[3] / 2 - output_size[1] / 2) / zoom return x, y, 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)
[docs] @_check_props(e=("beta", "cts")) @_check_props(graph="t", v=("tpos",)) def get_hierarchy_control_points(g, t, tpos, beta=0.8, cts=None, is_tree=True, max_depth=None): r"""Return the Bézier spline control points for the edges in ``g``, given the hierarchical structure encoded in graph `t`. 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 points from the root to the leaves, and the vertices in ``t`` with index in the range :math:`[0, N-1]`, with :math:`N` being the number of vertices in ``g``, must correspond to the respective vertex in ``g``. tpos : :class:`~graph_tool.VertexPropertyMap` Vector-valued vertex property map containing the x and y coordinates of the vertices in graph ``t``. beta : ``float`` or :class:`~graph_tool.EdgePropertyMap` (optional, default: ``0.8``) Edge bundling strength. For ``beta == 0`` the edges are straight lines, and for ``beta == 1`` they strictly follow the hierarchy. This can be optionally an edge property map, which specifies a different bundling strength for each edge. cts : :class:`~graph_tool.EdgePropertyMap` (optional, default: ``None``) Edge property map of type ``vector<double>`` where the control points will be stored. is_tree : ``bool`` (optional, default: ``True``) If ``True``, ``t`` must be a directed tree, otherwise it can be any connected graph. max_depth : ``int`` (optional, default: ``None``) If supplied, only the first ``max_depth`` bottom levels of the hierarchy will be used. Returns ------- cts : :class:`~graph_tool.EdgePropertyMap` Vector-valued edge property map containing the Bézier spline control points for the edges in ``g``. See Also -------- draw_hierarchy: Draw a nested block model hierarchy radial_tree_layout: Radial layout of a tree graph_tool.inference.get_hierarchy_tree: Hierarchy tree of a nested model Notes ----- This is an implementation of the edge-bundling algorithm described in [holten-hierarchical-2006]_. Examples -------- .. 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)) >>> state = gt.minimize_nested_blockmodel_dl(g) >>> t = gt.get_hierarchy_tree(state)[0] >>> tpos = pos = gt.radial_tree_layout(t, t.vertex(t.num_vertices() - 1, use_index=False), weighted=True) >>> cts = gt.get_hierarchy_control_points(g, t, tpos) >>> pos = g.own_property(tpos) >>> b = state.levels[0].b >>> shape = b.copy() >>> shape.a %= 14 >>> 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.pdf") <...> .. testcleanup:: nested_cts conv_png("netscience_nested_mdl.pdf") .. figure:: netscience_nested_mdl.png :align: center :width: 80% Block partition of a co-authorship 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` """ return _hierarchy_control_points(g, t, tpos, beta, cts, is_tree, max_depth)
def _hierarchy_control_points(g, t, tpos, beta=0.8, cts=None, is_tree=True, max_depth=None, skip=None): # The optional vertex property map ``skip`` of ``t`` marks the vertices # that are removed from the edge paths. 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()) u = GraphView(g, directed=True) tu = GraphView(t, directed=True) if not isinstance(beta, PropertyMap): beta = u.new_edge_property("double", beta) else: beta = beta.copy("double") if max_depth is None: max_depth = t.num_vertices() tu = GraphView(tu, skip_vfilt=True) tpos = tu.own_property(tpos) if skip is None: skip = tu.new_vertex_property("bool") else: skip = tu.own_property(skip) libgraph_tool_draw.get_cts(u, tu, tpos, beta, cts, skip, is_tree, max_depth) return cts # # The functions and classes below depend on GTK # ============================================= # # Importing Gtk initializes it, which sets the C locale of the whole process # from the environment (e.g. the decimal comma of LC_NUMERIC=de_DE breaks the # number parsing of C libraries), so the locale is restored afterwards. import locale _locale = locale.setlocale(locale.LC_ALL) try: import gi try: gi.require_version('Gtk', '3.0') except ValueError: raise ImportError from gi.repository import Gtk, Gdk, GdkPixbuf from gi.repository import GObject as gobject from .gtk_draw import * except (ImportError, RuntimeError) as e: msg = "Error importing Gtk module: %s; GTK+ drawing will not work." % str(e) warnings.warn(msg, RuntimeWarning) finally: locale.setlocale(locale.LC_ALL, _locale) del _locale def gen_surface(name): if get_file_fmt(name) in ["png", "PNG"]: fobj, fmt = open_file(name, mode="rb") with fobj: return cairo.ImageSurface.create_from_png(fobj) 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 # # matplotlib # ========== #
[docs] class GraphArtist(matplotlib.artist.Artist): def __init__(self, g, pos, ax, vprops=None, eprops=None, raster=False, **kwargs): """:class:`matplotlib.artist.Artist` specialization that draws :class:`~graph_tool.Graph` instances in a :mod:`matplotlib` figure. .. warning:: Vector drawing is available only on cairo-based backends. For other backends, rasterization will be used. Parameters ---------- g : :class:`~graph_tool.Graph` Graph to be drawn. pos : :class:`~graph_tool.VertexPropertyMap` Vector-valued vertex property map containing the x and y coordinates of the vertices. ax : :class:`matplotlib.axes.Axes` A :class:`matplotlib.axes.Axes` instance where the graph will be drawn. vprops : dict (optional, default: ``None``) Dictionary with the vertex properties. eprops : dict (optional, default: ``None``) Dictionary with the edge properties. raster : bool (optional, default: ``False``) If ``True``, the graph will be rasterized even if a cairo-based backend is being used. **kwargs : dict (optional, default: ``None``) Remaining options to pass to :func:`~graph_tool.draw.cairo_draw`. """ matplotlib.artist.Artist.__init__(self) self.g = g self.pos = pos self.ax = ax self.vprops = vprops if vprops is not None else {} self.eprops = eprops if eprops is not None else {} self.raster = raster self.kwargs = kwargs.copy() self.set_zorder(1) self.ax.update_datalim(self.get_extents()) self.ax.autoscale()
[docs] def set_raster(self, raster=True): """If ``raster == True``, then the graph will be rasterized even if a cairo-based backend is being used.""" self.raster = raster
[docs] def fit_view(self, scale=1, margin=.1, yflip=False, keep_aspect=True, set_axis_aspect=False): """Set axis limits to fit the graph, optionally scaling it via the ``scale`` parameter, and adding a relative margin given by ``margin``. If ``yflip is True``, the y axis is flipped upside down. If ``keep_aspect is True``, the aspect ratio is preserved via the data limits. Otherwise, if ``set_axis_aspect is True``, the aspect of the axis will be changed to match the data aspect. """ x, y = ungroup_vector_property(self.pos, [0, 1]) l, r = x.fa.min(), x.fa.max() b, t = y.fa.min(), y.fa.max() w = r - l h = t - b if keep_aspect: ll, ur = (self.ax.get_position() * self.ax.get_figure().get_size_inches()) dw, dh = ur - ll a = dh / dw ar = h / w if ar > a: nw = h / a l -= (nw - w) / 2 r += (nw - w) / 2 w = nw else: nh = w * a b -= (nh - h) / 2 t += (nh - h) / 2 h = nh elif set_axis_aspect: self.ax.set_aspect(h / w) w *= scale h *= scale self.ax.set_xlim(l - w * margin, r + w * margin) if yflip: self.ax.set_ylim(t + h * margin, b - h * margin) else: self.ax.set_ylim(b - h * margin, t + h * margin)
[docs] def draw_to_cairo(self, ctx, transform, mag=1): """Draw to a cairo context.""" ctx.save() eprops = dict(self.eprops) vprops = dict(self.vprops) # clip region l, r = self.ax.get_xlim() b, t = self.ax.get_ylim() l, b = transform((l, b)) r, t = transform((r, t)) ctx.new_path() ctx.rectangle(min(l, r), min(b, t), abs(r-l), abs(t-b)) ctx.clip() # The sizes are in data units, converted with the scale of the # transformation at the center of the view, since it varies along # nonlinear (e.g. logarithmic) axes. bb = self.ax.bbox c = self.ax.transData.inverted().transform(((bb.x0 + bb.x1) / 2, (bb.y0 + bb.y1) / 2)) w = np.abs([self.ax.get_xlim()[1] - self.ax.get_xlim()[0], self.ax.get_ylim()[1] - self.ax.get_ylim()[0]]) h = 1e-6 * np.where(c != 0, np.abs(c), w) h[h == 0] = 1e-6 d = (self.ax.transData.transform(c + h) - self.ax.transData.transform(c)) / h scale_ink(np.mean(np.abs(d)) * mag, vprops, eprops, min_pen_width=0) x, y = ungroup_vector_property(self.pos, [0, 1]) P = np.stack([x.a, y.a], axis=1) tP = transform(P) x.a, y.a = tP[:, 0], tP[:, 1] pos = group_vector_property([x, y]) # transform edge control points, if present cp = eprops.get("control_points", None) if isinstance(cp, PropertyMap): cp = cp.copy() _transform_control_points(self.g, cp, P, tP, transform) parallel_distance = vprops.get("size") if isinstance(parallel_distance, PropertyMap): parallel_distance = parallel_distance.fa.mean() _put_self_loop_splines(self.g, pos, cp, parallel_distance) eprops["control_points"] = cp cairo_draw(self.g, pos, ctx, vprops, eprops, **self.kwargs) ctx.restore()
[docs] def draw(self, renderer): width, height = renderer.get_canvas_width_height() if (isinstance(renderer, matplotlib.backends.backend_cairo.RendererCairo) and not self.raster): ctx = renderer.gc.ctx if not isinstance(ctx, cairo.Context): ctx = _UNSAFE_cairocffi_context_to_pycairo(ctx) # Cairo coordinates are flipped in the y direction def transform(x): x = np.array(self.ax.transData.transform(x), dtype="float") x[..., 1] = height - x[..., 1] return x self.draw_to_cairo(ctx, transform) else: l, r = self.ax.get_xlim() b, t = self.ax.get_ylim() l, b = self.ax.transData.transform((l, b)) r, t = self.ax.transData.transform((r, t)) mag = renderer.get_image_magnification() width, height = int(abs(r-l) * mag), int(abs(t-b) * mag) img = cairo.ImageSurface(cairo.Format.ARGB32, width, height) ctx = cairo.Context(img) def transform(x): x = np.array(self.ax.transData.transform(x), dtype="float") x[..., 0] = (x[..., 0] - l) * width / (r - l) x[..., 1] = height - (x[..., 1] - b) * height / (t - b) return x self.draw_to_cairo(ctx, transform, mag) img.flush() buf = img.get_data() im = np.ndarray(shape=(height, width, 4), dtype=np.uint8, buffer=buf) im[:, :, [0, 2]] = im[:, :, [2, 0]] # fix endianess (swap R and B) im = im[::-1, :, :] # flip y direction gc = renderer.new_gc() renderer.draw_image(gc, l, b, im)
[docs] def get_extents(self): """Return a :class:`matplotlib.transforms.Bbox` with the node position limits.""" x, y = ungroup_vector_property(self.pos, [0, 1]) return matplotlib.transforms.Bbox([[x.fa.min(), y.fa.min()], [x.fa.max(), y.fa.max()]])
# # Drawing hierarchies # =================== #
[docs] def draw_hierarchy(state, pos=None, layout="radial", beta=0.8, node_weight=None, vprops=None, eprops=None, hvprops=None, heprops=None, subsample_edges=None, rel_order="degree", deg_size=True, vsize_scale=1, hsize_scale=1, hshortcuts=0, hide=0, bip_aspect=1., bip_left=0, empty_branches=False, **kwargs): r"""Draw a nested block model state in a circular or bipartite hierarchy layout with edge bundling. Parameters ---------- state : :class:`~graph_tool.inference.NestedBlockState` Nested block state to be drawn. pos : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) If supplied, this specifies a vertex property map with the positions of the vertices in the layout. layout : ``str`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``"radial"``) If ``layout == "radial"`` :func:`~graph_tool.draw.radial_tree_layout` will be used. If ``layout == "sfdp"``, the hierarchy tree will be positioned using :func:`~graph_tool.draw.sfdp_layout`. If ``layout == "bipartite"``, the two partitions of a bipartite network will be placed on the left and right sides, with their hierarchies between them (see the notes below). If instead a :class:`~graph_tool.VertexPropertyMap` is provided, it must correspond to the position of the hierarchy tree. beta : ``float`` (optional, default: ``.8``) Edge bundling strength. node_weight : :class:`~graph_tool.VertexPropertyMap` (optional, default: ``None``) If provided, this specifies a vertex property map with the relative angular section that each vertex occupies. This value is ignored unless ``layout`` is ``"radial"`` or ``"bipartite"``. 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. 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. rel_order : ``str`` or ``None`` or :class:`~graph_tool.VertexPropertyMap` (optional, default: ``"degree"``) If ``"degree"``, the vertices will be ordered according to degree inside each group, and the relative ordering of the hierarchy branches. With ``layout == "bipartite"``, this order is then changed to reduce the number of edge crossings between the two sides. If instead a :class:`~graph_tool.VertexPropertyMap` is provided, its value will be used for the relative ordering of the vertices. If ``None``, the vertices and branches are ordered by their indices. deg_size : ``bool`` (optional, default: ``True``) If ``True``, the default vertex sizes will increase with the (total) node degrees, otherwise they will all be equal. vsize_scale : ``float`` (optional, default: ``1.``) Multiplicative factor for the default vertex sizes. hsize_scale : ``float`` (optional, default: ``1.``) Multiplicative factor for the default sizes of the hierarchy nodes, and of the arrow markers of the hierarchy edges. hshortcuts : ``int`` (optional, default: ``0``) Include shortcuts to the number of upper layers in the hierarchy determined by this parameter. hide : ``int`` or ``None`` (optional, default: ``0``) Hide upper levels of the hierarchy. If ``None`` is given, the upper levels with no groups are hidden. bip_aspect : ``float`` (optional, default: ``1.``) If ``layout == "bipartite"``, this will define the aspect ratio (width over height) of the layout. bip_left : ``int`` or ``str`` (optional, default: ``0``) If ``layout == "bipartite"``, this determines which partition is drawn on the left side, with the other one on the right. If an integer is given, it is the label of the partition, i.e. its value of the ``pclabel`` property map of the state, or, if the state has no ``pclabel`` with two values, of the bipartition returned by :func:`~graph_tool.structure.is_bipartite`. If ``"smaller"`` or ``"larger"``, the partition with the smaller or larger total node weight (see ``node_weight``) is drawn on the left. Before this parameter existed, the partition with the smaller total node weight was always drawn on the left, i.e. ``bip_left="smaller"`` gives the previous behavior. empty_branches : ``bool`` (optional, default: ``False``) If ``empty_branches == False``, dangling branches at the upper layers will be pruned. vertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``vertex_<prop-name>`` specify the vertex property with name ``<prop-name>``, as an alternative to the ``vprops`` parameter. See :func:`~graph_tool.draw.graph_draw` for details. edge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``) Parameters following the pattern ``edge_<prop-name>`` specify the edge property with name ``<prop-name>``, as an alternative to the ``eprops`` parameter. See :func:`~graph_tool.draw.graph_draw` for details. hvertex_* : :class:`~graph_tool.VertexPropertyMap` or arbitrary types (optional, default: ``None``) 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. hedge_* : :class:`~graph_tool.EdgePropertyMap` or arbitrary types (optional, default: ``None``) 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. **kwargs : All remaining keyword arguments will be passed to the :func:`~graph_tool.draw.graph_draw` function. Returns ------- pos : :class:`~graph_tool.VertexPropertyMap` This is a vertex property map with the positions of the vertices in the layout. t : :class:`~graph_tool.Graph` This is the hierarchy tree used in the layout. For ``layout == "bipartite"`` this is the tree with one branch per side, as described in the notes below. tpos : :class:`~graph_tool.VertexPropertyMap` This is a vertex property map with the positions of the hierarchy tree in the layout. See Also -------- graph_draw: Draw a graph with Cairo get_hierarchy_control_points: Edge bundling along a hierarchy radial_tree_layout: Radial layout of a tree graph_tool.inference.NestedBlockState: Nested stochastic block model Notes ----- The edges are drawn as splines whose control points follow the path between their endpoints in the hierarchy tree, as described in [holten-hierarchical-2006]_, with a bundling strength given by ``beta``. With ``layout == "bipartite"``, the vertices of the two partitions are placed on two vertical lines, and the groups of the hierarchy between them, at a horizontal position given by their level. The partitions are given by the ``pclabel`` property map of the state, if it has two values (as is the case when the bipartite structure is imposed in the inference), and otherwise by the bipartition of the network. The hierarchy tree is split into one tree per side: a group that contains vertices of both partitions appears on both sides, and the groups at the top of each side that contain all of its vertices are merged into a single one. The vertical space occupied by a group is proportional to the total node weight of its vertices. The edges go from the top groups of one side directly to those of the other, so that they are bundled according to the pair of groups they connect. With the default ``rel_order``, the order of the branches and vertices is chosen to reduce the number of edge crossings between the two sides, by alternating barycenter sweeps [sugiyama-methods-1981]_. The computation of the layout and of the control points takes time :math:`O(V + E L)`, where :math:`L` is the number of hierarchy levels, plus, with the bipartite layout, :math:`O(E\log E + V\log V)` for each of at most 20 sweeps. The time it takes to draw the edges is typically dominated by the rendering of the color gradients of the edges between different groups. 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) >>> gt.draw_hierarchy(state, output="celegansneural_nested_mdl.pdf") (...) .. testcleanup:: draw_hierarchy conv_png("celegansneural_nested_mdl.pdf") .. figure:: celegansneural_nested_mdl.png :align: center :width: 80% 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. For a bipartite network, the two partitions can be kept separate in the inference with the ``pclabel`` parameter, and drawn on opposite sides with the bipartite layout. In the following example, the partition of the countries (label ``1``) is drawn on the left. .. testsetup:: draw_hierarchy_bip gt.seed_rng(42) np.random.seed(42) .. doctest:: draw_hierarchy_bip >>> g = gt.collection.ns["unicodelang"] >>> g = gt.extract_largest_component(g, prune=True) >>> kind = gt.is_bipartite(g, partition=True)[1] >>> state = gt.minimize_nested_blockmodel_dl(g, state_args=dict(pclabel=kind)) >>> gt.draw_hierarchy(state, layout="bipartite", bip_left=1, ... output="unicodelang_nested_mdl.pdf") (...) .. testcleanup:: draw_hierarchy_bip conv_png("unicodelang_nested_mdl.pdf") .. figure:: unicodelang_nested_mdl.png :align: center :width: 80% Hierarchical block partition of the bipartite network of countries (left) and the languages spoken in them (right), which minimizes the description length of the nested (degree-corrected) stochastic blockmodel, with the two partitions kept separate. 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` .. [sugiyama-methods-1981] Sugiyama, K., Tagawa, S., Toda, M. "Methods for Visual Understanding of Hierarchical System Structures", IEEE Transactions on Systems, Man, and Cybernetics 11, no. 2, 109–125 (1981). :doi:`10.1109/TSMC.1981.4308636` """ g = state.g if g.num_vertices() == 0: # there is no hierarchy to draw return graph_draw(g, pos=pos, vprops=vprops, eprops=eprops, **kwargs) overlap = isinstance(state.levels[0], OverlapBlockState) if overlap: bv, bcin, bcout, bc = state.levels[0].get_overlap_groups() b = state.levels[0].get_majority_groups() 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) t, tb, tvorder = get_hierarchy_tree(state, empty_branches=empty_branches) tskip = None troot = None max_depth = max(len(state.levels) - hshortcuts, 1) if layout == "radial": if isinstance(rel_order, str) and rel_order == "degree": rel_order = g.degree_property_map("total") if rel_order is None: vorder = None else: vorder = t.own_property(rel_order.copy()) if pos is not None: x, y = ungroup_vector_property(pos, [0, 1]) x.fa -= x.fa.mean() y.fa -= y.fa.mean() angle = g.new_vertex_property("double") angle.fa = (numpy.arctan2(y.fa, x.fa) + 2 * numpy.pi) % (2 * numpy.pi) vorder = t.own_property(angle) if node_weight is not None: node_weight = t.own_property(node_weight.copy()) node_weight.a[node_weight.a == 0] = 1 tpos = radial_tree_layout(t, root=t.vertex(t.num_vertices() - 1, use_index=False), node_weight=node_weight, rel_order=vorder, rel_order_leaf=True) elif layout == "bipartite": t, tb, tvorder, tpos, tskip = \ _bip_hierarchy_layout(state, g, t, tb, tvorder, left=bip_left, aspect=bip_aspect, node_weight=node_weight, rel_order=rel_order) # The root comes right after the leaves. The edge paths do not pass # through it nor through the side tops, so that the shortcuts start # below them. troot = g.num_vertices(True) dist = shortest_distance(t, source=t.vertex(troot)).a[:troot] max_depth = max(dist[dist <= troot].max() - 1 - hshortcuts, 1) elif layout == "sfdp": if pos is None: tpos = sfdp_layout(t) else: x, y = ungroup_vector_property(pos, [0, 1]) x.fa -= x.fa.mean() y.fa -= y.fa.mean() K = numpy.sqrt(x.fa.std() + y.fa.std()) / 10 N = g.num_vertices(True) xy = numpy.zeros((2, t.num_vertices(True))) xy[0, :N] = x.a[:N] xy[1, :N] = y.a[:N] tpos = t.new_vertex_property("vector<double>") tpos.set_2d_array(xy[:, t.get_vertices()]) pin = t.new_vertex_property("bool") pin.a[:N] = True tpos = sfdp_layout(t, K=K, pos=tpos, pin=pin, multilevel=False) else: tpos = t.own_property(layout) hvvisible = t.new_vertex_property("bool", True) if hide is None: L = len([s for s in state.levels if s.get_B() > 0]) hide = len(state.levels) - L if hide > 0: root = t.vertex(t.num_vertices(True) - 1 if troot is None else troot) dist = shortest_distance(t, source=root) hvvisible.fa = dist.fa >= hide pos = g.own_property(tpos.copy()) cts = _hierarchy_control_points(g, t, tpos, beta, max_depth=max_depth, skip=tskip) vprops_orig = vprops eprops_orig = eprops hvprops_orig = hvprops heprops_orig = heprops 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) vprops.setdefault("shape", _vdefaults["shape"] if not overlap else "pie") output_size = kwargs.get("output_size", (600, 600)) if kwargs.get("mplfig", None) is not None: x, y = ungroup_vector_property(pos, [0, 1]) w = x.a.max() - x.a.min() h = y.a.max() - y.a.min() output_size = (w, h) s = numpy.mean(output_size) / (4 * numpy.sqrt(g.num_vertices())) if "size" not in vprops: if deg_size: vsize = prop_to_size(g.degree_property_map("total"), s/5, s) vsize.fa *= vsize_scale else: # the middle of the range of the degree-based sizes vsize = s * 3/5 * vsize_scale vprops["size"] = vsize adjust_default_sizes(g, output_size, vprops, eprops) if vprops.get("text_position", None) == "centered": angle, text_pos = _hierarchy_text_rotation(g, pos, layout) vprops["text_position"] = text_pos vprops["text_rotation"] = angle 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 parallel_distance = vprops.get("size", _vdefaults["size"]) if isinstance(parallel_distance, PropertyMap): parallel_distance = parallel_distance.fa.mean() _put_self_loop_splines(g, pos, cts, parallel_distance) vprops = _convert_props(vprops, "v", g, kwargs.get("vcmap", None), kwargs.get("vcnorm", None), pmap_default=True) props, kwargs = parse_props("edge", kwargs) eprops.update(props) eprops.setdefault("control_points", cts) eprops.setdefault("pen_width", _edefaults["pen_width"]) eprops.setdefault("color", list(_edefaults["color"][:-1]) + [.6]) eprops.setdefault("end_marker", "arrow" if g.is_directed() else "none") eprops = _convert_props(eprops, "e", g, kwargs.get("ecmap", None), kwargs.get("ecnorm", None), 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", s * hsize_scale) if hvprops.get("text_position", None) == "centered": angle, text_pos = _hierarchy_text_rotation(t, tpos, layout) hvprops["text_position"] = text_pos hvprops["text_rotation"] = angle 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 hvprops = _convert_props(hvprops, "v", t, kwargs.get("vcmap", None), kwargs.get("vcnorm", None), 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", s * .8 * hsize_scale) heprops.setdefault("pen_width", s / 10) heprops = _convert_props(heprops, "e", t, kwargs.get("ecmap", None), kwargs.get("ecnorm", None), pmap_default=True) vcmap = kwargs.get("vcmap", default_cm) ecmap = kwargs.get("ecmap", vcmap) B = state.levels[0].get_B() if overlap and "pie_fractions" not in vprops: 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) if gradient is None: gradient = g.new_edge_property("double") gradient = group_vector_property([gradient]) ecolor = eprops.get("ecolor", _edefaults["color"]) eprops["gradient"] = gradient t_orig = t t = GraphView(t, vfilt=lambda v: int(v) >= g.num_vertices(True) and hvvisible[v]) # automatic text colors are the default of graph_draw(), and computed # there for the merged graph for ps in [vprops, hvprops, eprops, heprops]: if _is_auto(ps.get("text_color", None)): del ps["text_color"] t_vprops = {} t_eprops = {} 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]) props.append((pos, tpos)) props.append((g.vertex_index, tb)) props.append((b, None)) # vertex of the hierarchy tree that corresponds to each merged vertex props.append((g.vertex_index.copy("int64_t"), t.vertex_index.copy("int64_t"))) if "eorder" in kwargs: eorder = kwargs["eorder"] props.append((eorder, t.new_ep(eorder.value_type(), eorder.fa.max() + 1))) u, props = graph_merge(GraphView(g, directed=True), t, props={"set": props}, vmap=None, multiset=True) props = props["set"] 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_t = tb tb = props.pop(0) b = props.pop(0) tvertex = props.pop(0) if "eorder" in kwargs: eorder = props.pop(0) # The interactive callbacks work on the merged graph, whose vertices are # the visible ones of the graph and of the hierarchy tree. The control # points are computed with the tree relabeled to the indices of the merged # graph (its vertices that are not in the merged graph, e.g. hidden by # ``hide``, keep their positions). N = g.num_vertices(True) t_all = GraphView(t_orig, skip_vfilt=True) tmap = numpy.full(t_all.num_vertices(), -1, dtype="int64") nu = u.num_vertices(True) tmap[GraphView(u, skip_vfilt=True).own_property(tvertex).a] = \ numpy.arange(nu) textra = numpy.where(tmap < 0)[0] tmap[textra] = nu + numpy.arange(len(textra)) tu = Graph() tu.add_vertex(nu + len(textra)) tu.add_edge_list(tmap[t_orig.get_edges()]) tu_xy = numpy.zeros((2, tu.num_vertices())) tu_xy[:, tmap] = t_all.own_property(tpos).get_2d_array([0, 1]) tu_skip = tu.new_vertex_property("bool") if tskip is not None: tu_skip.a[tmap] = t_all.own_property(tskip).a tu_root = tmap[t_orig.num_vertices(True) - 1 if troot is None else troot] u_leaf = u.new_vertex_property("bool") u_leaf.a = GraphView(u, skip_vfilt=True).own_property(tvertex).a < N def update_cts(widget, gg, picked, pos, vprops, eprops): xy = tu_xy.copy() xy[:, :nu] = GraphView(gg, skip_vfilt=True).own_property(pos).get_2d_array([0, 1]) tpos_u = tu.new_vertex_property("vector<double>") tpos_u.set_2d_array(xy) leaves = GraphView(gg, vfilt=gg.own_property(u_leaf)) _hierarchy_control_points(leaves, tu, tpos_u, beta, cts=eprops["control_points"], max_depth=max_depth, skip=tu_skip) def draw_branch(widget, gg, key_id, picked, pos, vprops, eprops): if key_id == ord('b'): if picked is None or isinstance(picked, PropertyMap): return v = int(tvertex[gg.vertex(int(picked))]) if v < N: return # The level of the picked group is given by its height above the # leaves. h = 0 w = t_orig.vertex(v) while int(w) >= N: w = next(w.out_neighbors(), None) if w is None: # empty branch (empty_branches=True) return h += 1 l = h - 1 if l >= len(state.levels): return nstate = _hierarchy_branch_state(state, l, tb_t[v]) if nstate is None: return # Property maps of the original graph do not apply to the branch. def own(ps): return {k: x for k, x in (ps or {}).items() if not isinstance(x, PropertyMap)} kwargs_ = own(kwargs_orig) kwargs_["main"] = False # A branch inside one partition cannot be drawn on two sides. nlayout = layout if isinstance(layout, str) else "radial" if nlayout == "bipartite": try: if len(numpy.unique(_bip_sides(nstate, 0, None))) < 2: nlayout = "radial" except ValueError: nlayout = "radial" draw_hierarchy(nstate, layout=nlayout, beta=beta, vprops=own(vprops_orig), eprops=own(eprops_orig), hvprops=own(hvprops_orig), heprops=own(heprops_orig), rel_order=rel_order if isinstance(rel_order, str) else "degree", bip_aspect=bip_aspect, bip_left=bip_left, hshortcuts=hshortcuts, empty_branches=False, **kwargs_) if key_id == ord('r'): if layout == "radial": xy = tu_xy.copy() xy[:, :nu] = GraphView(gg, skip_vfilt=True).own_property(pos).get_2d_array([0, 1]) xy -= xy[:, :nu].mean(axis=1)[:, None] angle = tu.new_vertex_property("double") angle.a = (numpy.arctan2(xy[1], xy[0]) + 2 * numpy.pi) % (2 * numpy.pi) tpos_u = radial_tree_layout(tu, root=tu.vertex(tu_root), rel_order=angle) xy = tpos_u.get_2d_array([0, 1]) gpos = GraphView(gg, skip_vfilt=True).own_property(pos) gpos.set_2d_array(xy[:, :nu]) update_cts(widget, gg, picked, pos, vprops, eprops) if widget.vertex_matrix is not None: widget.vertex_matrix.update() widget.picked = None widget.selected.fa = False widget.fit_to_window() widget.regenerate_surface(reset=True) widget.queue_draw() if ("output" not in kwargs and not kwargs.get("inline", has_draw_inline) and kwargs.get("mplfig", None) is None): kwargs["layout_callback"] = update_cts kwargs["key_press_callback"] = draw_branch if "eorder" in kwargs: kwargs["eorder"] = eorder vorder = kwargs.pop("vorder", None) if vorder is None: vorder = g.degree_property_map("total") tvorder = u.own_property(tvorder) tvorder.fa[:g.num_vertices()] = vorder.fa for k, v in kwargs.items(): if isinstance(v, PropertyMap) and v.get_graph().base is not u.base: kwargs[k] = u.own_property(v.copy()) ret = graph_draw(u, pos, vprops=t_vprops, eprops=t_eprops, vorder=tvorder, **kwargs) if isinstance(ret, PropertyMap): ret = g.own_property(ret) return ret, t_orig, tpos
def _hierarchy_branch_state(state, l, r): # The nested state restricted to group r at level l of the hierarchy, # with its levels up to l, the last one a single group, or None if the # group is empty (for overlapping states, it contains the edges whose # both half-edges belong to the group). The arguments of # the base state that are property maps are carried to the subgraph. st = state.__getstate__() g = state.g overlap = isinstance(state.levels[0], OverlapBlockState) if not overlap: b = state.project_partition(l, 0) u = GraphView(g, vfilt=b.a == r) u.vp["__b"] = state.levels[0].b else: # the groups of the half-edges at level l (project_level() does not # support overlapping states) rs = state.levels[0].b.get_2d_array([0, 1]).astype("int64") for i in range(1, l + 1): rs = state.levels[i].b.fa[rs] u = GraphView(g, efilt=g.new_ep("bool", vals=(rs[0] == r) & (rs[1] == r))) u = GraphView(u, vfilt=u.degree_property_map("total").fa > 0) u.ep["__be"] = state.levels[0].b bargs = dict(st["base_state_args"]) for k, x in bargs.items(): if isinstance(x, PropertyMap): u.properties[(x.key_type(), "__arg_" + k)] = x u = Graph(u, prune=True) if u.num_vertices() == 0: return None for k, x in bargs.items(): if isinstance(x, PropertyMap): bargs[k] = u.properties[(x.key_type(), "__arg_" + k)] del u.properties[(x.key_type(), "__arg_" + k)] if not overlap: b0 = u.vp["__b"].a.copy() del u.vp["__b"] B0 = b0.max() + 1 else: b0 = u.ep["__be"] del u.ep["__be"] B0 = b0.get_2d_array([0, 1]).max() + 1 bs = [b0] + [state.levels[i].b.fa.copy() for i in range(1, l + 1)] if l == 0: # a group of the lowest level gets a single group above it bs.append(numpy.zeros(B0, dtype="int")) else: bs[-1][:] = 0 return NestedBlockState(u, bs=bs, base_state=st["base_state"], base_state_args=bargs, extra_args=st["extra_args"][:len(bs)]) def _hierarchy_text_rotation(g, pos, layout): # Text rotation and position for text_position == "centered": radial, # pointing away from the center, except in the bipartite layout, where it # is horizontal, pointing away from the middle. if not (isinstance(layout, str) and layout == "bipartite"): return centered_rotation(g, pos, text_pos=True) x = ungroup_vector_property(pos, [0])[0] angle = g.new_vertex_property("double") text_pos = g.new_vertex_property("double") text_pos.a[x.a < 0] = numpy.pi return angle, text_pos def _bip_sides(state, left, node_weight): # Side of each vertex of the bipartite layout (0 for the left, 1 for the # right), given by the partition constraint labels of the state if they # have two values, or otherwise by the bipartition of the graph. N = state.g.num_vertices(True) labels = None try: pclabel = state.levels[0].pclabel if pclabel.key_type() == "v" and "vector" not in pclabel.value_type(): labels = pclabel.a[:N] if len(numpy.unique(pclabel.fa)) != 2: labels = None except AttributeError: pass if labels is None: bip, part = is_bipartite(state.g, partition=True) if not bip: raise ValueError("The bipartite layout requires a bipartite graph" + " or a state with a 'pclabel' with two values.") labels = part.a[:N].astype("int") vmask = numpy.zeros(N, dtype="bool") vmask[state.g.get_vertices()] = True values = numpy.unique(labels[vmask]) if isinstance(left, str): if left not in ["smaller", "larger"]: raise ValueError("Invalid value for 'bip_left': " + repr(left)) w = numpy.ones(N) if node_weight is None else node_weight.a[:N] ws = [w[vmask & (labels == r)].sum() for r in values] r = numpy.argmax(ws) if left == "larger" else numpy.argmin(ws) left = values[r] elif left not in values: raise ValueError("Invalid value for 'bip_left': %s (the partition" % \ repr(left) + " labels are %s)" % str(values.tolist())) side = numpy.where(labels == left, 0, 1).astype("int32") side[~vmask] = -1 return side def _bip_hierarchy_layout(state, g, t, tb, tvorder, left=0, aspect=1., node_weight=None, rel_order=None): # Split the hierarchy tree in two sides and lay it out, as described in # src/graph/draw/hierarchy_bip.cc. Returns the new tree, its labels, # order, positions, and the vertices that the edges do not pass through. N = state.g.num_vertices(True) side = _bip_sides(state, left, node_weight) if node_weight is None: weight = numpy.ones(N) else: weight = numpy.array(node_weight.a[:N], dtype="double") weight[weight == 0] = 1 # With the default ordering, the initial order by degree is changed to # reduce the edge crossings, with at most this number of sweeps. order = numpy.array(tvorder.a, dtype="double") niter = 0 if rel_order is None: order = numpy.arange(len(order), dtype="double") elif isinstance(rel_order, str): if rel_order != "degree": raise ValueError("Invalid value for 'rel_order': " + repr(rel_order)) niter = 20 else: order[:N] = rel_order.a[:N] tedges = numpy.ascontiguousarray(t.get_edges(), dtype="int64") gedges = numpy.ascontiguousarray(g.get_edges(), dtype="int64") nedges, orig, pos, skip = \ libgraph_tool_draw.bip_hierarchy_layout(tedges, gedges, side, weight, order, aspect, niter) nt = Graph() nt.add_vertex(len(orig)) nt.add_edge_list(nedges.reshape(-1, 2)) ntb = nt.new_vertex_property(tb.value_type(), vals=tb.a[orig]) ntvorder = nt.new_vertex_property(tvorder.value_type(), vals=tvorder.a[orig]) tpos = nt.new_vertex_property("vector<double>") tpos.set_2d_array(pos.reshape(-1, 2).T) tskip = nt.new_vertex_property("bool", vals=skip) return nt, ntb, ntvorder, tpos, tskip # Handle cairo contexts from cairocffi try: import cairocffi import ctypes pycairo_aux = ctypes.PyDLL(os.path.dirname(os.path.abspath(__file__)) + "/libgt_pycairo_aux.so") pycairo_aux.gt_PycairoContext_FromContext.restype = ctypes.c_void_p pycairo_aux.gt_PycairoContext_FromContext.argtypes = 3 * [ctypes.c_void_p] ctypes.pythonapi.PyList_Append.argtypes = 2 * [ctypes.c_void_p] except ImportError: pass def _UNSAFE_cairocffi_context_to_pycairo(cairocffi_context): # Sanity check. Continuing with another type would probably segfault. if not isinstance(cairocffi_context, cairocffi.Context): raise TypeError('Expected a cairocffi.Context, got %r' % cairocffi_context) # Create a reference for PycairoContext_FromContext to take ownership of. cairocffi.cairo.cairo_reference(cairocffi_context._pointer) # Casting the pointer to uintptr_t (the integer type as wide as a pointer) # gets the context’s integer address. # On CPython id(cairo.Context) gives the address to the Context type, # as expected by PycairoContext_FromContext. address = pycairo_aux.gt_PycairoContext_FromContext( int(cairocffi.ffi.cast('uintptr_t', cairocffi_context._pointer)), id(cairo.Context), None) assert address # This trick uses Python’s C API # to get a reference to a Python object from its address. temp_list = [] assert ctypes.pythonapi.PyList_Append(id(temp_list), address) == 0 return temp_list[0] # Bottom imports to avoid circular dependency issues from .. inference import get_hierarchy_tree, NestedBlockState, BlockState, \ OverlapBlockState