Debian Codegraph @

src/igraph/drawing/cairo/dendrogram.py

raw
1 """This module provides a dendrogram drawer for the Cairo backend."""
2
3 from math import pi
4
5 from igraph.drawing.utils import str_to_orientation
6
7 from .base import AbstractCairoDrawer
8
9 __all__ = ("CairoDendrogramDrawer",)
10
11
12 class CairoDendrogramDrawer(AbstractCairoDrawer):
13 """Default Cairo drawer object for dendrograms."""
14
15 def __init__(self, context, bbox, palette):
16 """Constructs the drawer and associates it to the given palette.
17
18 @param context: the context on which we will draw
19 @param bbox: the bounding box within which we will draw.
20 Can be anything accepted by the constructor
21 of L{BoundingBox} (i.e., a 2-tuple, a 4-tuple
22 or a L{BoundingBox} object).
23 @param palette: the palette that can be used to map integer
24 color indices to colors when drawing vertices
25 """
26 super().__init__(context, bbox)
27 self.palette = palette
28
29 @staticmethod
30 def _item_box_size(dendro, context, horiz, idx):
31 """Calculates the amount of space needed for drawing an
32 individual vertex at the bottom of the dendrogram."""
33 if dendro._names is None or dendro._names[idx] is None:
34 x_bearing, _, _, height, x_advance, _ = context.text_extents("")
35 else:
36 x_bearing, _, _, height, x_advance, _ = context.text_extents(
37 str(dendro._names[idx])
38 )
39
40 if horiz:
41 return x_advance - x_bearing, height
42 return height, x_advance - x_bearing
43
44 def _plot_item(self, dendro, context, horiz, idx, x, y):
45 """Plots a dendrogram item to the given Cairo context
46
47 @param context: the Cairo context we are plotting on
48 @param horiz: whether the dendrogram is horizontally oriented
49 @param idx: the index of the item
50 @param x: the X position of the item
51 @param y: the Y position of the item
52 """
53 if dendro._names is None or dendro._names[idx] is None:
54 return
55
56 height = self._item_box_size(dendro, context, True, idx)[1]
57 if horiz:
58 context.move_to(x, y + height)
59 context.show_text(str(dendro._names[idx]))
60 else:
61 context.save()
62 context.translate(x, y)
63 context.rotate(-pi / 2.0)
64 context.move_to(0, height)
65 context.show_text(str(dendro._names[idx]))
66 context.restore()
67
68 def draw(self, dendro, **kwds):
69 """Draws the given Dendrogram in a Cairo context.
70
71 @param dendro: the igraph.Dendrogram to plot.
72
73 It accepts the following keyword arguments:
74
75 - C{style}: the style of the plot. C{boolean} is useful for plotting
76 matrices with boolean (C{True}/C{False} or 0/1) values: C{False}
77 will be shown with a white box and C{True} with a black box.
78 C{palette} uses the given palette to represent numbers by colors,
79 the minimum will be assigned to palette color index 0 and the maximum
80 will be assigned to the length of the palette. C{None} draws transparent
81 cell backgrounds only. The default style is C{boolean} (but it may
82 change in the future). C{None} values in the matrix are treated
83 specially in both cases: nothing is drawn in the cell corresponding
84 to C{None}.
85
86 - C{square}: whether the cells of the matrix should be square or not.
87 Default is C{True}.
88
89 - C{grid_width}: line width of the grid shown on the matrix. If zero or
90 negative, the grid is turned off. The grid is also turned off if the size
91 of a cell is less than three times the given line width. Default is C{1}.
92 Fractional widths are also allowed.
93
94 - C{border_width}: line width of the border drawn around the matrix.
95 If zero or negative, the border is turned off. Default is C{1}.
96
97 - C{row_names}: the names of the rows
98
99 - C{col_names}: the names of the columns.
100
101 - C{values}: values to be displayed in the cells. If C{None} or
102 C{False}, no values are displayed. If C{True}, the values come
103 from the matrix being plotted. If it is another matrix, the
104 values of that matrix are shown in the cells. In this case,
105 the shape of the value matrix must match the shape of the
106 matrix being plotted.
107
108 - C{value_format}: a format string or a callable that specifies how
109 the values should be plotted. If it is a callable, it must be a
110 function that expects a single value and returns a string.
111 Example: C{"%#.2f"} for floating-point numbers with always exactly
112 two digits after the decimal point. See the Python documentation of
113 the C{%} operator for details on the format string. If the format
114 string is not given, it defaults to the C{str} function.
115
116 If only the row names or the column names are given and the matrix
117 is square-shaped, the same names are used for both column and row
118 names.
119 """
120 from igraph.layout import Layout
121
122 context = self.context
123 bbox = self.bbox
124
125 if dendro._names is None:
126 dendro._names = [str(x) for x in range(dendro._nitems)]
127
128 orientation = str_to_orientation(
129 kwds.get("orientation", "lr"), reversed_vertical=True
130 )
131 horiz = orientation in ("lr", "rl")
132
133 # Get the font height
134 font_height = context.font_extents()[2]
135
136 # Calculate space needed for individual items at the
137 # bottom of the dendrogram
138 item_boxes = [
139 self._item_box_size(dendro, context, horiz, idx)
140 for idx in range(dendro._nitems)
141 ]
142
143 # Small correction for cases when the right edge of the labels is
144 # aligned with the tips of the dendrogram branches
145 ygap = 2 if orientation == "bt" else 0
146 xgap = 2 if orientation == "lr" else 0
147 item_boxes = [(x + xgap, y + ygap) for x, y in item_boxes]
148
149 # Calculate coordinates
150 layout = Layout([(0, 0)] * dendro._nitems, dim=2)
151 inorder = dendro._traverse_inorder()
152 if not horiz:
153 x, y = 0, 0
154 for element in inorder:
155 layout[element] = (x, 0)
156 x += max(font_height, item_boxes[element][0])
157
158 for id1, id2 in dendro._merges:
159 y += 1
160 layout.append(((layout[id1][0] + layout[id2][0]) / 2.0, y))
161
162 # Mirror or rotate the layout if necessary
163 if orientation == "bt":
164 layout.mirror(1)
165 else:
166 x, y = 0, 0
167 for element in inorder:
168 layout[element] = (0, y)
169 y += max(font_height, item_boxes[element][1])
170
171 for id1, id2 in dendro._merges:
172 x += 1
173 layout.append((x, (layout[id1][1] + layout[id2][1]) / 2.0))
174
175 # Mirror or rotate the layout if necessary
176 if orientation == "rl":
177 layout.mirror(0)
178
179 # Rescale layout to the bounding box
180 maxw = max(e[0] for e in item_boxes)
181 maxh = max(e[1] for e in item_boxes)
182
183 # w, h: width and height of the area containing the dendrogram
184 # tree without the items.
185 # delta_x, delta_y: displacement of the dendrogram tree
186 width, height = float(bbox.width), float(bbox.height)
187 delta_x, delta_y = 0, 0
188 if horiz:
189 width -= maxw
190 if orientation == "lr":
191 delta_x = maxw
192 else:
193 height -= maxh
194 if orientation == "tb":
195 delta_y = maxh
196
197 if horiz:
198 delta_y += font_height / 2.0
199 else:
200 delta_x += font_height / 2.0
201 layout.fit_into(
202 (delta_x, delta_y, width - delta_x, height - delta_y),
203 keep_aspect_ratio=False,
204 )
205
206 context.save()
207
208 context.translate(bbox.left, bbox.top)
209 context.set_source_rgb(0.0, 0.0, 0.0)
210 context.set_line_width(1)
211
212 # Draw items
213 if horiz:
214 sgn = 0 if orientation == "rl" else -1
215 for idx in range(dendro._nitems):
216 x = layout[idx][0] + sgn * item_boxes[idx][0]
217 y = layout[idx][1] - item_boxes[idx][1] / 2.0
218 self._plot_item(dendro, context, horiz, idx, x, y)
219 else:
220 sgn = 1 if orientation == "bt" else 0
221 for idx in range(dendro._nitems):
222 x = layout[idx][0] - item_boxes[idx][0] / 2.0
223 y = layout[idx][1] + sgn * item_boxes[idx][1]
224 dendro._plot_item(dendro, context, horiz, idx, x, y)
225
226 # Draw dendrogram lines
227 if not horiz:
228 for idx, (id1, id2) in enumerate(dendro._merges):
229 x0, y0 = layout[id1]
230 x1, y1 = layout[id2]
231 x2, y2 = layout[idx + dendro._nitems]
232 context.move_to(x0, y0)
233 context.line_to(x0, y2)
234 context.line_to(x1, y2)
235 context.line_to(x1, y1)
236 context.stroke()
237 else:
238 for idx, (id1, id2) in enumerate(dendro._merges):
239 x0, y0 = layout[id1]
240 x1, y1 = layout[id2]
241 x2, y2 = layout[idx + dendro._nitems]
242 context.move_to(x0, y0)
243 context.line_to(x2, y0)
244 context.line_to(x2, y1)
245 context.line_to(x1, y1)
246 context.stroke()
247
248 context.restore()