Debian Codegraph @

src/igraph/drawing/cairo/plot.py

raw
1 """
2 Drawing and plotting routines for IGraph.
3
4 igraph has two plotting backends at the moment: Cairo and Matplotlib.
5
6 The Cairo backend is dependent on the C{pycairo} or C{cairocffi} libraries that
7 provide Python bindings to the popular U{Cairo library<http://www.cairographics.org>}.
8 This means that if you don't have U{pycairo<http://www.cairographics.org/pycairo>}
9 or U{cairocffi<https://doc.courtbouillon.org/cairocffi/>} installed, you won't be able
10 to use the Cairo plotting backend. Whenever the documentation refers to the
11 C{pycairo} library, you can safely replace it with C{cairocffi} as the two are
12 API-compatible.
13
14 The Matplotlib backend uses the U{Matplotlib library<https://matplotlib.org>}.
15 You will need to install it from PyPI if you want to use the Matplotlib
16 plotting backend.
17
18 If you do not want to (or cannot) install any of the dependencies outlined
19 above, you can still save the graph to an SVG file and view it from
20 U{Mozilla Firefox<https://www.mozilla.org/firefox>} (free) or edit it in
21 U{Inkscape<https://www.inkscape.org>} (free), U{Skencil<https://www.skencil.org>}
22 (formerly known as Sketch, also free) or Adobe Illustrator.
23 """
24
25 import os
26
27 from io import BytesIO
28 from warnings import warn
29
30 from igraph.configuration import Configuration
31 from igraph.drawing.cairo.utils import find_cairo
32 from igraph.drawing.colors import Palette, palettes
33 from igraph.drawing.utils import BoundingBox
34 from igraph.utils import named_temporary_file
35
36 __all__ = ("CairoPlot",)
37
38 cairo = find_cairo()
39
40 #####################################################################
41
42
43 class CairoPlot:
44 """Class representing an arbitrary plot that uses the Cairo plotting
45 backend.
46
47 Objects that you can plot include graphs, matrices, palettes, clusterings,
48 covers, and dendrograms.
49
50 In Cairo, every plot has an associated surface object. The surface is an
51 instance of C{cairo.Surface}, a member of the C{pycairo} library. The
52 surface itself provides a unified API to various plotting targets like SVG
53 files, X11 windows, PostScript files, PNG files and so on. C{igraph} does
54 not usually know on which surface it is plotting at each point in time,
55 since C{pycairo} takes care of the actual drawing. Everything that's
56 supported by C{pycairo} should be supported by this class as well.
57
58 Current Cairo surfaces include:
59
60 - C{cairo.GlitzSurface} -- OpenGL accelerated surface for the X11
61 Window System.
62
63 - C{cairo.ImageSurface} -- memory buffer surface. Can be written to a
64 C{PNG} image file.
65
66 - C{cairo.PDFSurface} -- PDF document surface.
67
68 - C{cairo.PSSurface} -- PostScript document surface.
69
70 - C{cairo.SVGSurface} -- SVG (Scalable Vector Graphics) document surface.
71
72 - C{cairo.Win32Surface} -- Microsoft Windows screen rendering.
73
74 - C{cairo.XlibSurface} -- X11 Window System screen rendering.
75
76 If you create a C{Plot} object with a string given as the target surface,
77 the string will be treated as a filename, and its extension will decide
78 which surface class will be used. Please note that not all surfaces might
79 be available, depending on your C{pycairo} installation.
80
81 A C{Plot} has an assigned default palette (see L{igraph.drawing.colors.Palette})
82 which is used for plotting objects.
83
84 A C{Plot} object also has a list of objects to be plotted with their
85 respective bounding boxes, palettes and opacities. Palettes assigned to an
86 object override the default palette of the plot. Objects can be added by the
87 L{Plot.add} method and removed by the L{Plot.remove} method.
88 """
89
90 def __init__(
91 self,
92 target=None,
93 bbox=None,
94 palette=None,
95 background=None,
96 ):
97 """Creates a new plot.
98
99 @param target: the target surface to write to. It can be one of the
100 following types:
101
102 - C{None} -- a Cairo surface will be created and the object will be
103 plotted there.
104
105 - C{cairo.Surface} -- the given Cairo surface will be used.
106
107 - C{string} -- a file with the given name will be created and an
108 appropriate Cairo surface will be attached to it.
109
110 @param bbox: the bounding box of the surface. It is interpreted
111 differently with different surfaces: PDF and PS surfaces will treat it
112 as points (1 point = 1/72 inch). Image surfaces will treat it as
113 pixels. SVG surfaces will treat it as an abstract unit, but it will
114 mostly be interpreted as pixels when viewing the SVG file in Firefox.
115
116 @param palette: the palette primarily used on the plot if the
117 added objects do not specify a private palette. Must be either
118 an L{igraph.drawing.colors.Palette} object or a string referring
119 to a valid key of C{igraph.drawing.colors.palettes} (see module
120 L{igraph.drawing.colors}) or C{None}. In the latter case, the default
121 palette given by the configuration key C{plotting.palette} is used.
122
123 @param background: the background color. If C{None}, the background
124 will be transparent. You can use any color specification here that is
125 understood by L{igraph.drawing.colors.color_name_to_rgba}.
126 """
127
128 self._filename = None
129 self._need_tmpfile = False
130
131 if bbox is None:
132 self.bbox = BoundingBox(600, 600)
133 elif isinstance(bbox, tuple) or isinstance(bbox, list):
134 self.bbox = BoundingBox(bbox)
135 else:
136 self.bbox = bbox
137
138 if palette is None:
139 config = Configuration.instance()
140 palette = config["plotting.palette"]
141 if not isinstance(palette, Palette):
142 palette = palettes[palette]
143 self._palette = palette
144
145 if target is None:
146 self._need_tmpfile = True
147 self._surface = cairo.ImageSurface(
148 cairo.FORMAT_ARGB32, int(self.bbox.width), int(self.bbox.height)
149 )
150 elif isinstance(target, cairo.Surface):
151 self._surface = target
152 else:
153 self._filename = target
154 _, ext = os.path.splitext(target)
155 ext = ext.lower()
156 if ext == ".pdf":
157 self._surface = cairo.PDFSurface(
158 target, self.bbox.width, self.bbox.height
159 )
160 elif ext == ".ps" or ext == ".eps":
161 self._surface = cairo.PSSurface(
162 target, self.bbox.width, self.bbox.height
163 )
164 elif ext == ".png":
165 self._surface = cairo.ImageSurface(
166 cairo.FORMAT_ARGB32, int(self.bbox.width), int(self.bbox.height)
167 )
168 elif ext == ".svg":
169 self._surface = cairo.SVGSurface(
170 target, self.bbox.width, self.bbox.height
171 )
172 else:
173 raise ValueError("image format not handled by Cairo: %s" % ext)
174
175 self._ctx = cairo.Context(self._surface)
176
177 self._objects = []
178 self._is_dirty = False
179
180 if background is None:
181 background = "white"
182 self.background = background
183
184 def add(self, obj, bbox=None, palette=None, opacity=1.0, *args, **kwds):
185 """Adds an object to the plot.
186
187 Arguments not specified here are stored and passed to the object's
188 plotting function when necessary. Since you are most likely interested
189 in the arguments acceptable by graphs, see L{Graph.__plot__} for more
190 details.
191
192 @param obj: the object to be added
193 @param bbox: the bounding box of the object. If C{None}, the object
194 will fill the entire area of the plot.
195 @param palette: the color palette used for drawing the object. If the
196 object tries to get a color assigned to a positive integer, it
197 will use this palette. If C{None}, defaults to the global palette
198 of the plot.
199 @param opacity: the opacity of the object being plotted, in the range
200 0.0-1.0
201
202 @see: Graph.__plot__
203 """
204 if opacity < 0.0 or opacity > 1.0:
205 raise ValueError("opacity must be between 0.0 and 1.0")
206 if bbox is None:
207 bbox = self.bbox
208 if (bbox is not None) and (not isinstance(bbox, BoundingBox)):
209 bbox = BoundingBox(bbox)
210 self._objects.append((obj, bbox, palette, opacity, args, kwds))
211 self.mark_dirty()
212
213 @property
214 def background(self):
215 """Returns the background color of the plot. C{None} means a
216 transparent background.
217 """
218 return self._background
219
220 @background.setter
221 def background(self, color):
222 """Sets the background color of the plot. C{None} means a
223 transparent background. You can use any color specification here
224 that is understood by the C{get} method of the current palette
225 or by L{igraph.drawing.colors.color_name_to_rgb}.
226 """
227 if color is None:
228 self._background = None
229 else:
230 self._background = self._palette.get(color)
231
232 def remove(self, obj, bbox=None, idx=1):
233 """Removes an object from the plot.
234
235 If the object has been added multiple times and no bounding box
236 was specified, it removes the instance which occurs M{idx}th
237 in the list of identical instances of the object.
238
239 @param obj: the object to be removed
240 @param bbox: optional bounding box specification for the object.
241 If given, only objects with exactly this bounding box will be
242 considered.
243 @param idx: if multiple objects match the specification given by
244 M{obj} and M{bbox}, only the M{idx}th occurrence will be removed.
245 @return: C{True} if the object has been removed successfully,
246 C{False} if the object was not on the plot at all or M{idx}
247 was larger than the count of occurrences
248 """
249 for i in range(len(self._objects)):
250 current_obj, current_bbox = self._objects[i][0:2]
251 if current_obj is obj and (bbox is None or current_bbox == bbox):
252 idx -= 1
253 if idx == 0:
254 self._objects[i : (i + 1)] = []
255 self.mark_dirty()
256 return True
257 return False
258
259 def mark_dirty(self):
260 """Marks the plot as dirty (should be redrawn)"""
261 self._is_dirty = True
262
263 def redraw(self, context=None):
264 """Redraws the plot"""
265 ctx = context or self._ctx
266 if self._background is not None:
267 ctx.set_source_rgba(*self._background)
268 ctx.rectangle(0, 0, self.bbox.width, self.bbox.height)
269 ctx.fill()
270
271 for obj, bbox, palette, opacity, args, kwds in self._objects:
272 if palette is None:
273 palette = getattr(obj, "_default_palette", self._palette)
274 plotter = getattr(obj, "__plot__", None)
275 if plotter is None:
276 warn("%s does not support plotting" % (obj,), stacklevel=1)
277 else:
278 if opacity < 1.0:
279 ctx.push_group()
280 else:
281 ctx.save()
282 plotter(
283 "cairo",
284 ctx,
285 bbox=bbox,
286 palette=palette,
287 *args, # noqa: B026
288 **kwds,
289 )
290 if opacity < 1.0:
291 ctx.pop_group_to_source()
292 ctx.paint_with_alpha(opacity)
293 else:
294 ctx.restore()
295
296 self._is_dirty = False
297
298 def save(self, fname=None):
299 """Saves the plot.
300
301 @param fname: the filename to save to. It is ignored if the surface
302 of the plot is not an C{ImageSurface}.
303 """
304 if self._is_dirty:
305 self.redraw()
306 if isinstance(self._surface, cairo.ImageSurface):
307 if fname is None and self._need_tmpfile:
308 with named_temporary_file(prefix="igraph", suffix=".png") as fname:
309 self._surface.write_to_png(fname)
310 return None
311
312 fname = fname or self._filename
313 if fname is None:
314 raise ValueError("no file name is known for the surface and none given")
315
316 # Conversion to string is needed because the user might pass a Path
317 # object and cairocffi expects a string
318 return self._surface.write_to_png(str(fname))
319
320 if fname is not None:
321 warn(
322 "filename is ignored for surfaces other than ImageSurface", stacklevel=1
323 )
324
325 self._ctx.show_page()
326 self._surface.finish()
327
328 def _repr_svg_(self):
329 """Returns an SVG representation of this plot as a string.
330
331 This method is used by IPython to display this plot inline.
332 """
333 io = BytesIO()
334 # Create a new SVG surface and use that to get the SVG representation,
335 # which will end up in io
336 surface = cairo.SVGSurface(io, self.bbox.width, self.bbox.height)
337 context = cairo.Context(surface)
338 # Plot the graph on this context
339 self.redraw(context)
340 # No idea why this is needed but python crashes without
341 context.show_page()
342 surface.finish()
343 # Return the raw SVG representation
344 result = io.getvalue().decode("utf-8")
345 return result, {"isolated": True} # put it inside an iframe
346
347 @property
348 def bounding_box(self):
349 """Returns the bounding box of the Cairo surface as a
350 L{BoundingBox} object"""
351 return BoundingBox(self.bbox)
352
353 @property
354 def height(self):
355 """Returns the height of the Cairo surface on which the plot
356 is drawn"""
357 return self.bbox.height
358
359 @property
360 def surface(self):
361 """Returns the Cairo surface on which the plot is drawn"""
362 return self._surface
363
364 @property
365 def width(self):
366 """Returns the width of the Cairo surface on which the plot
367 is drawn"""
368 return self.bbox.width