Debian Codegraph @

src/igraph/drawing/cairo/matrix.py

raw
1 """This module provides implementation for a Cairo-specific matrix drawer."""
2
3 from itertools import islice
4 from math import pi
5
6 from igraph.drawing.cairo.base import AbstractCairoDrawer
7
8 __all__ = ("CairoMatrixDrawer",)
9
10
11 class CairoMatrixDrawer(AbstractCairoDrawer):
12 """Default Cairo drawer object for matrices."""
13
14 def __init__(self, context):
15 """Constructs the vertex drawer and associates it to the given
16 palette.
17
18 @param context: the context on which we will draw
19 """
20 super().__init__(context, bbox=None)
21
22 def draw(self, matrix, **kwds):
23 """Draws the given Matrix in a Cairo context.
24
25 @param matrix: the igraph.Matrix to plot.
26
27 It accepts the following keyword arguments:
28
29 - C{bbox}: the bounding box within which we will draw.
30 Can be anything accepted by the constructor of L{BoundingBox}
31 (i.e., a 2-tuple, a 4-tuple or a L{BoundingBox} object).
32
33 - C{palette}: the palette that can be used to map integer color
34 indices to colors when drawing vertices
35
36 - C{style}: the style of the plot. C{boolean} is useful for plotting
37 matrices with boolean (C{True}/C{False} or 0/1) values: C{False}
38 will be shown with a white box and C{True} with a black box.
39 C{palette} uses the given palette to represent numbers by colors,
40 the minimum will be assigned to palette color index 0 and the maximum
41 will be assigned to the length of the palette. C{None} draws transparent
42 cell backgrounds only. The default style is C{boolean} (but it may
43 change in the future). C{None} values in the matrix are treated
44 specially in both cases: nothing is drawn in the cell corresponding
45 to C{None}.
46
47 - C{square}: whether the cells of the matrix should be square or not.
48 Default is C{True}.
49
50 - C{grid_width}: line width of the grid shown on the matrix. If zero or
51 negative, the grid is turned off. The grid is also turned off if the size
52 of a cell is less than three times the given line width. Default is C{1}.
53 Fractional widths are also allowed.
54
55 - C{border_width}: line width of the border drawn around the matrix.
56 If zero or negative, the border is turned off. Default is C{1}.
57
58 - C{row_names}: the names of the rows
59
60 - C{col_names}: the names of the columns.
61
62 - C{values}: values to be displayed in the cells. If C{None} or
63 C{False}, no values are displayed. If C{True}, the values come
64 from the matrix being plotted. If it is another matrix, the
65 values of that matrix are shown in the cells. In this case,
66 the shape of the value matrix must match the shape of the
67 matrix being plotted.
68
69 - C{value_format}: a format string or a callable that specifies how
70 the values should be plotted. If it is a callable, it must be a
71 function that expects a single value and returns a string.
72 Example: C{"%#.2f"} for floating-point numbers with always exactly
73 two digits after the decimal point. See the Python documentation of
74 the C{%} operator for details on the format string. If the format
75 string is not given, it defaults to the C{str} function.
76
77 If only the row names or the column names are given and the matrix
78 is square-shaped, the same names are used for both column and row
79 names.
80 """
81 context = self.context
82 Matrix = matrix.__class__
83
84 bbox = self.bbox = kwds.pop("bbox", None)
85 palette = kwds.pop("palette", None)
86 if bbox is None:
87 raise ValueError("bbox is required for Cairo plots")
88 if palette is None:
89 raise ValueError("palette is required for Cairo plots")
90
91 grid_width = float(kwds.get("grid_width", 1.0))
92 border_width = float(kwds.get("border_width", 1.0))
93 style = kwds.get("style", "boolean")
94 row_names = kwds.get("row_names")
95 col_names = kwds.get("col_names", row_names)
96 values = kwds.get("values")
97 value_format = kwds.get("value_format", str)
98
99 # Validations
100 if style not in ("boolean", "palette", "none", None):
101 raise ValueError("invalid style")
102 if style == "none":
103 style = None
104 if row_names is None and col_names is not None:
105 row_names = col_names
106 if row_names is not None:
107 row_names = [str(name) for name in islice(row_names, matrix._nrow)]
108 if len(row_names) < matrix._nrow:
109 row_names.extend([""] * (matrix._nrow - len(row_names)))
110 if col_names is not None:
111 col_names = [str(name) for name in islice(col_names, matrix._ncol)]
112 if len(col_names) < matrix._ncol:
113 col_names.extend([""] * (matrix._ncol - len(col_names)))
114 if values is False:
115 values = None
116 if values is True:
117 values = matrix
118 if isinstance(values, list):
119 values = Matrix(list)
120 if values is not None and not isinstance(values, Matrix):
121 raise TypeError("values must be None, False, True or a matrix")
122 if values is not None and values.shape != matrix.shape:
123 raise ValueError("values must be a matrix of size %s" % matrix.shape)
124
125 # Calculate text extents if needed
126 if row_names is not None or col_names is not None:
127 te = context.text_extents
128 space_width = te(" ")[4]
129 if row_names is not None:
130 max_row_name_width = max([te(s)[4] for s in row_names]) + space_width
131 else:
132 max_row_name_width = 0
133 if col_names is not None:
134 max_col_name_width = max([te(s)[4] for s in col_names]) + space_width
135 else:
136 max_col_name_width = 0
137 else:
138 max_row_name_width, max_col_name_width = 0, 0
139 space_width = 0
140
141 # Calculate sizes
142 total_width = float(bbox.width) - max_row_name_width
143 total_height = float(bbox.height) - max_col_name_width
144 dx = total_width / matrix.shape[1]
145 dy = total_height / matrix.shape[0]
146 if kwds.get("square", True):
147 dx, dy = min(dx, dy), min(dx, dy)
148 total_width, total_height = dx * matrix.shape[1], dy * matrix.shape[0]
149 ox = bbox.left + (bbox.width - total_width - max_row_name_width) / 2.0
150 oy = bbox.top + (bbox.height - total_height - max_col_name_width) / 2.0
151 ox += max_row_name_width
152 oy += max_col_name_width
153
154 # Determine rescaling factors for the palette if needed
155 if style == "palette":
156 mi, ma = matrix.min(), matrix.max()
157 color_offset = mi
158 color_ratio = (len(palette) - 1) / float(ma - mi)
159 else:
160 color_offset, color_ratio = 0, 1
161
162 # Validate grid width
163 if dx < 3 * grid_width or dy < 3 * grid_width:
164 grid_width = 0.0
165 if grid_width > 0:
166 context.set_line_width(grid_width)
167 else:
168 # When the grid width is zero, we will still stroke the
169 # rectangles, but with the same color as the fill color
170 # of the cell - otherwise we would get thin white lines
171 # between the cells as a drawing artifact
172 context.set_line_width(1)
173
174 # Draw row names (if any)
175 context.set_source_rgb(0.0, 0.0, 0.0)
176 if row_names is not None:
177 x, y = ox, oy
178 for heading in row_names:
179 _, _, _, h, xa, _ = context.text_extents(heading)
180 context.move_to(x - xa - space_width, y + (dy + h) / 2.0)
181 context.show_text(heading)
182 y += dy
183
184 # Draw column names (if any)
185 if col_names is not None:
186 context.save()
187 context.translate(ox, oy)
188 context.rotate(-pi / 2)
189 x, y = 0.0, 0.0
190 for heading in col_names:
191 _, _, _, h, _, _ = context.text_extents(heading)
192 context.move_to(x + space_width, y + (dx + h) / 2.0)
193 context.show_text(heading)
194 y += dx
195 context.restore()
196
197 # Draw matrix
198 x, y = ox, oy
199 if style is None:
200 fill = lambda: None # noqa: E731
201 else:
202 fill = context.fill_preserve
203 for row in matrix:
204 for item in row:
205 if item is None:
206 x += dx
207 continue
208 if style == "boolean":
209 if item:
210 context.set_source_rgb(0.0, 0.0, 0.0)
211 else:
212 context.set_source_rgb(1.0, 1.0, 1.0)
213 elif style == "palette":
214 cidx = int((item - color_offset) * color_ratio)
215 if cidx < 0:
216 cidx = 0
217 context.set_source_rgba(*palette.get(cidx))
218 context.rectangle(x, y, dx, dy)
219 if grid_width > 0:
220 fill()
221 context.set_source_rgb(0.5, 0.5, 0.5)
222 context.stroke()
223 else:
224 fill()
225 context.stroke()
226 x += dx
227 x, y = ox, y + dy
228
229 # Draw cell values
230 if values is not None:
231 x, y = ox, oy
232 context.set_source_rgb(0.0, 0.0, 0.0)
233 for row in values.data:
234 if callable(value_format):
235 values = [value_format(item) for item in row]
236 else:
237 values = [value_format % item for item in row]
238 for item in values:
239 th, tw = context.text_extents(item)[3:5]
240 context.move_to(x + (dx - tw) / 2.0, y + (dy + th) / 2.0)
241 context.show_text(item)
242 x += dx
243 x, y = ox, y + dy
244
245 # Draw borders
246 if border_width > 0:
247 context.set_line_width(border_width)
248 context.set_source_rgb(0.0, 0.0, 0.0)
249 context.rectangle(ox, oy, dx * matrix.shape[1], dy * matrix.shape[0])
250 context.stroke()