Debian Codegraph @

src/igraph/drawing/cairo/graph.py

raw
1 """
2 Drawing routines to draw graphs.
3
4 This module contains routines to draw graphs on:
5
6 - Cairo surfaces (L{DefaultGraphDrawer})
7 - Matplotlib axes (L{MatplotlibGraphDrawer})
8
9 It also contains routines to send an igraph graph directly to
10 (U{Cytoscape<http://www.cytoscape.org>}) using the
11 (U{CytoscapeRPC plugin<http://gforge.nbic.nl/projects/cytoscaperpc/>}), see
12 L{CytoscapeGraphDrawer}. L{CytoscapeGraphDrawer} can also fetch the current
13 network from Cytoscape and convert it to igraph format.
14 """
15
16 from math import atan2, cos, pi, sin, tan
17 from warnings import warn
18
19 from igraph._igraph import convex_hull, VertexSeq
20 from igraph.configuration import Configuration
21 from igraph.drawing.baseclasses import AbstractGraphDrawer
22 from igraph.drawing.text import TextAlignment
23 from igraph.drawing.utils import Point
24
25 from .base import AbstractCairoDrawer
26 from .edge import CairoArrowEdgeDrawer
27 from .polygon import CairoPolygonDrawer
28 from .text import CairoTextDrawer
29 from .utils import find_cairo
30 from .vertex import CairoVertexDrawer
31
32 __all__ = ("CairoGraphDrawer",)
33
34 cairo = find_cairo()
35
36 #####################################################################
37
38
39 #####################################################################
40
41
42 class AbstractCairoGraphDrawer(AbstractGraphDrawer, AbstractCairoDrawer):
43 """Abstract base class for graph drawers that draw on a Cairo canvas."""
44
45 def __init__(self, context, bbox):
46 """Constructs the graph drawer and associates it to the given
47 Cairo context and the given L{BoundingBox}.
48
49 @param context: the context on which we will draw
50 @param bbox: the bounding box within which we will draw.
51 Can be anything accepted by the constructor
52 of L{BoundingBox} (i.e., a 2-tuple, a 4-tuple
53 or a L{BoundingBox} object).
54 """
55 AbstractCairoDrawer.__init__(self, context, bbox)
56 AbstractGraphDrawer.__init__(self)
57
58
59 #####################################################################
60
61
62 class CairoGraphDrawer(AbstractCairoGraphDrawer):
63 """Class implementing the default visualisation of a graph.
64
65 The default visualisation of a graph draws the nodes on a 2D plane
66 according to a given L{Layout}, then draws a straight or curved
67 edge between nodes connected by edges. This is the visualisation
68 used when one invokes the L{plot()} function on a L{Graph} object.
69
70 See L{Graph.__plot__()} for the keyword arguments understood by
71 this drawer."""
72
73 def __init__(
74 self,
75 context,
76 bbox=None,
77 vertex_drawer_factory=CairoVertexDrawer,
78 edge_drawer_factory=CairoArrowEdgeDrawer,
79 label_drawer_factory=CairoTextDrawer,
80 ):
81 """Constructs the graph drawer and associates it to the given
82 Cairo context and the given L{BoundingBox}.
83
84 @param context: the context on which we will draw
85 @param bbox: the bounding box within which we will draw.
86 Can be anything accepted by the constructor
87 of L{BoundingBox} (i.e., a 2-tuple, a 4-tuple
88 or a L{BoundingBox} object).
89 @param vertex_drawer_factory: a factory method that returns an
90 L{AbstractCairoVertexDrawer} instance bound to a
91 given Cairo context. The factory method must take
92 four parameters: the Cairo context, the bounding
93 box of the drawing area, the palette to be
94 used for drawing colored vertices, and the graph layout.
95 The default vertex drawer is L{CairoVertexDrawer}.
96 @param edge_drawer_factory: a factory method that returns an
97 L{AbstractCairoEdgeDrawer} instance bound to a
98 given Cairo context. The factory method must take
99 two parameters: the Cairo context and the palette
100 to be used for drawing colored edges. You can use
101 any of the actual L{AbstractEdgeDrawer}
102 implementations here to control the style of
103 edges drawn by igraph. The default edge drawer is
104 L{CairoArrowEdgeDrawer}.
105 @param label_drawer_factory: a factory method that returns a
106 L{CairoTextDrawer} instance bound to a given Cairo
107 context. The method must take one parameter: the
108 Cairo context. The default label drawer is
109 L{CairoTextDrawer}.
110 """
111 super().__init__(context, bbox)
112 self.vertex_drawer_factory = vertex_drawer_factory
113 self.edge_drawer_factory = edge_drawer_factory
114 self.label_drawer_factory = label_drawer_factory
115
116 def draw(self, graph, *args, **kwds):
117 # Positional arguments are not used
118 if args:
119 warn(
120 "Positional arguments to plot functions are ignored "
121 "and will be deprecated soon.",
122 DeprecationWarning,
123 stacklevel=1,
124 )
125
126 bbox = kwds.pop("bbox", None)
127 if bbox is None:
128 raise ValueError("bbox is required for Cairo plots")
129 # Validate it through set/get
130 self.bbox = bbox
131 bbox = self.bbox
132
133 # Some abbreviations for sake of simplicity
134 directed = graph.is_directed()
135 context = self.context
136
137 # Palette
138 palette = kwds.pop("palette", None)
139
140 # Calculate/get the layout of the graph
141 layout = self.ensure_layout(kwds.get("layout", None), graph)
142
143 # Determine the size of the margin on each side
144 margin = kwds.get("margin", 0)
145 try:
146 margin = list(margin) # type: ignore
147 except TypeError:
148 margin = [margin]
149 while len(margin) < 4:
150 margin.extend(margin)
151
152 # Contract the drawing area by the margin and fit the layout
153 bbox = self.bbox.contract(margin)
154 layout.fit_into(bbox, keep_aspect_ratio=kwds.get("keep_aspect_ratio", False))
155
156 # Decide whether we need to calculate the curvature of edges
157 # automatically -- and calculate them if needed.
158 autocurve = kwds.get("autocurve", None)
159 if autocurve or (
160 autocurve is None
161 and "edge_curved" not in kwds
162 and "curved" not in graph.edge_attributes()
163 and graph.ecount() < 10000
164 ):
165 from igraph import autocurve
166
167 default = kwds.get("edge_curved", 0)
168 if default is True:
169 default = 0.5
170 default = float(default)
171 kwds["edge_curved"] = autocurve(graph, attribute=None, default=default)
172
173 # Construct the vertex, edge and label drawers
174 vertex_drawer = self.vertex_drawer_factory(context, bbox, palette, layout)
175 edge_drawer = self.edge_drawer_factory(context, palette)
176 label_drawer = self.label_drawer_factory(context)
177
178 # Construct the visual vertex/edge builders based on the specifications
179 # provided by the vertex_drawer and the edge_drawer
180 vertex_builder = vertex_drawer.VisualVertexBuilder(graph.vs, kwds)
181 edge_builder = edge_drawer.VisualEdgeBuilder(graph.es, kwds)
182
183 # Determine the order in which we will draw the vertices and edges
184 vertex_order = self._determine_vertex_order(graph, kwds)
185 edge_order = self._determine_edge_order(graph, kwds)
186
187 # Draw the highlighted groups (if any)
188 if "mark_groups" in kwds:
189 mark_groups = kwds["mark_groups"]
190
191 # Deferred import to avoid a cycle in the import graph
192 from igraph.clustering import VertexClustering, VertexCover
193
194 # Figure out what to do with mark_groups in order to be able to
195 # iterate over it and get memberlist-color pairs
196 if isinstance(mark_groups, dict):
197 # Dictionary mapping vertex indices or tuples of vertex
198 # indices to colors
199 group_iter = iter(mark_groups.items())
200 elif isinstance(mark_groups, (VertexClustering, VertexCover)):
201 # Vertex clustering
202 group_iter = ((group, color) for color, group in enumerate(mark_groups))
203 elif hasattr(mark_groups, "__iter__"):
204 # Lists, tuples, iterators etc
205 group_iter = iter(mark_groups)
206 else:
207 # False
208 group_iter = iter({}.items())
209
210 # We will need a polygon drawer to draw the convex hulls
211 polygon_drawer = CairoPolygonDrawer(context, bbox)
212
213 # Iterate over color-memberlist pairs
214 for group, color_id in group_iter:
215 if not group or color_id is None:
216 continue
217
218 color = palette.get(color_id)
219
220 if isinstance(group, VertexSeq):
221 group = [vertex.index for vertex in group]
222 if not hasattr(group, "__iter__"):
223 raise TypeError("group membership list must be iterable")
224
225 # Get the vertex indices that constitute the convex hull
226 hull = [group[i] for i in convex_hull([layout[idx] for idx in group])]
227
228 # Calculate the preferred rounding radius for the corners
229 corner_radius = 1.25 * max(vertex_builder[idx].size for idx in hull)
230
231 # Construct the polygon
232 polygon = [layout[idx] for idx in hull]
233
234 if len(polygon) == 2:
235 # Expand the polygon (which is a flat line otherwise)
236 a, b = Point(*polygon[0]), Point(*polygon[1])
237 c = corner_radius * (a - b).normalized()
238 n = Point(-c[1], c[0])
239 polygon = [a + n, b + n, b - c, b - n, a - n, a + c]
240 else:
241 # Expand the polygon around its center of mass
242 center = Point(
243 *[sum(coords) / float(len(coords)) for coords in zip(*polygon)]
244 )
245 polygon = [
246 Point(*point).towards(center, -corner_radius)
247 for point in polygon
248 ]
249
250 # Draw the hull
251 context.set_source_rgba(color[0], color[1], color[2], color[3] * 0.25)
252 polygon_drawer.draw_path(polygon, corner_radius=corner_radius)
253 context.fill_preserve()
254 context.set_source_rgba(*color)
255 context.stroke()
256
257 # Construct the iterator that we will use to draw the edges
258 es = graph.es
259 if edge_order is None:
260 # Default edge order
261 edge_coord_iter = zip(es, edge_builder)
262 else:
263 # Specified edge order
264 edge_coord_iter = ((es[i], edge_builder[i]) for i in edge_order)
265
266 # Draw the edges
267 if directed:
268 drawer_method = edge_drawer.draw_directed_edge
269 else:
270 drawer_method = edge_drawer.draw_undirected_edge
271 for edge, visual_edge in edge_coord_iter:
272 src, dest = edge.tuple
273 src_vertex, dest_vertex = vertex_builder[src], vertex_builder[dest]
274 drawer_method(visual_edge, src_vertex, dest_vertex)
275
276 # Construct the iterator that we will use to draw the vertices
277 vs = graph.vs
278 if vertex_order is None:
279 # Default vertex order
280 vertex_coord_iter = zip(vs, vertex_builder, layout)
281 else:
282 # Specified vertex order
283 vertex_coord_iter = (
284 (vs[i], vertex_builder[i], layout[i]) for i in vertex_order
285 )
286
287 # Draw the vertices
288 drawer_method = vertex_drawer.draw
289 context.set_line_width(1)
290 for vertex, visual_vertex, coords in vertex_coord_iter:
291 drawer_method(visual_vertex, vertex, coords)
292
293 # Decide whether the labels have to be wrapped
294 wrap = kwds.get("wrap_labels")
295 if wrap is None:
296 wrap = Configuration.instance()["plotting.wrap_labels"]
297 wrap = bool(wrap)
298
299 # Construct the iterator that we will use to draw the vertex labels
300 if vertex_order is None:
301 # Default vertex order
302 vertex_coord_iter = zip(vertex_builder, layout)
303 else:
304 # Specified vertex order
305 vertex_coord_iter = ((vertex_builder[i], layout[i]) for i in vertex_order)
306
307 # Draw the vertex labels
308 for vertex, coords in vertex_coord_iter:
309 if vertex.label is None:
310 continue
311
312 # Set the font family, size, color and text
313 context.select_font_face(
314 vertex.font, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL
315 )
316 context.set_font_size(vertex.label_size)
317 context.set_source_rgba(*vertex.label_color)
318 label_drawer.text = vertex.label
319
320 if vertex.label_dist:
321 # Label is displaced from the center of the vertex.
322 _, yb, w, h, _, _ = label_drawer.text_extents()
323 w, h = w / 2.0, h / 2.0
324 radius = vertex.label_dist * vertex.size / 2.0
325 # First we find the reference point that is at distance `radius'
326 # from the vertex in the direction given by `label_angle'.
327 # Then we place the label in a way that the line connecting the
328 # center of the bounding box of the label with the center of the
329 # vertex goes through the reference point and the reference
330 # point lies exactly on the bounding box of the vertex.
331 alpha = vertex.label_angle % (2 * pi)
332 cx = coords[0] + radius * cos(alpha)
333 cy = coords[1] - radius * sin(alpha)
334 # Now we have the reference point. We have to decide which side
335 # of the label box will intersect with the line that connects
336 # the center of the label with the center of the vertex.
337 if w > 0:
338 beta = atan2(h, w) % (2 * pi)
339 else:
340 beta = pi / 2.0
341 gamma = pi - beta
342 if alpha > 2 * pi - beta or alpha <= beta:
343 # Intersection at left edge of label
344 cx += w
345 cy -= tan(alpha) * w
346 elif alpha > beta and alpha <= gamma:
347 # Intersection at bottom edge of label
348 try:
349 cx += h / tan(alpha)
350 except Exception:
351 pass # tan(alpha) == inf
352 cy -= h
353 elif alpha > gamma and alpha <= gamma + 2 * beta:
354 # Intersection at right edge of label
355 cx -= w
356 cy += tan(alpha) * w
357 else:
358 # Intersection at top edge of label
359 try:
360 cx -= h / tan(alpha)
361 except Exception:
362 pass # tan(alpha) == inf
363 cy += h
364 # Draw the label
365 label_drawer.draw_at(cx - w, cy - h - yb, wrap=wrap)
366 else:
367 # Label is exactly in the center of the vertex
368 cx, cy = coords
369 half_size = vertex.size / 2.0
370 label_drawer.bbox = (
371 cx - half_size,
372 cy - half_size,
373 cx + half_size,
374 cy + half_size,
375 )
376 label_drawer.draw(wrap=wrap)
377
378 # Construct the iterator that we will use to draw the edge labels
379 es = graph.es
380 if edge_order is None:
381 # Default edge order
382 edge_coord_iter = zip(es, edge_builder)
383 else:
384 # Specified edge order
385 edge_coord_iter = ((es[i], edge_builder[i]) for i in edge_order)
386
387 # Draw the edge labels
388 for edge, visual_edge in edge_coord_iter:
389 if visual_edge.label is None:
390 continue
391
392 # Set the font family, size, color and text
393 context.select_font_face(
394 visual_edge.font, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL
395 )
396 context.set_font_size(visual_edge.label_size)
397 context.set_source_rgba(*visual_edge.label_color)
398 label_drawer.text = visual_edge.label
399
400 # Ask the edge drawer to propose an anchor point for the label
401 src, dest = edge.tuple
402 src_vertex, dest_vertex = vertex_builder[src], vertex_builder[dest]
403 (x, y), (halign, valign) = edge_drawer.get_label_position(
404 visual_edge, src_vertex, dest_vertex
405 )
406
407 # Measure the text
408 _, yb, w, h, _, _ = label_drawer.text_extents()
409 w /= 2.0
410 h /= 2.0
411
412 # Place the text relative to the edge
413 if halign == TextAlignment.RIGHT:
414 x -= w
415 elif halign == TextAlignment.LEFT:
416 x += w
417 if valign == TextAlignment.BOTTOM:
418 y -= h - yb / 2.0
419 elif valign == TextAlignment.TOP:
420 y += h
421
422 # Draw the edge label
423 label_drawer.halign = halign
424 label_drawer.valign = valign
425 label_drawer.bbox = (x - w, y - h, x + w, y + h)
426 label_drawer.draw(wrap=wrap)