cell-type-annotation 0.4.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,869 @@
1
+ """The annotation-hierarchy plot: nested label columns, connecting ribbons, and per-node markers.
2
+
3
+ The plot is drawn into one :class:`~matplotlib.axes.Axes` whose x unit is the typographic point and
4
+ whose y unit is one leaf row. Column widths are *measured* from rendered glyphs, which is what keeps
5
+ marker genes from colliding with long labels; any width the axes have beyond what the content needs
6
+ widens the boxes. Row ``i`` sits at ``y = i`` and the y limits span exactly the rows, so another
7
+ axes with the same vertical extent lines up with the leaves.
8
+
9
+ Everything typographic comes from :class:`HierarchyStyle`; fonts come from ``rcParams``. The caller
10
+ owns the figure, its size and the keys, which :class:`HierarchyLayout` supports with a colour
11
+ mappable and line handles for the ribbons.
12
+
13
+ This is the one paper figure of an annotation run, so the caller builds and exports it following the
14
+ ``sci-figures`` skill.
15
+ """
16
+
17
+ import colorsys
18
+ from collections.abc import Callable, Collection, Mapping, Sequence
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, Literal
21
+
22
+ import matplotlib.pyplot as plt
23
+ import numpy as np
24
+ import pandas as pd
25
+ from anndata import AnnData
26
+ from matplotlib.axes import Axes
27
+ from matplotlib.cm import ScalarMappable
28
+ from matplotlib.colors import ListedColormap, Normalize, to_hex, to_rgb
29
+ from matplotlib.font_manager import FontProperties
30
+ from matplotlib.lines import Line2D
31
+ from matplotlib.patches import FancyBboxPatch, PathPatch
32
+ from matplotlib.path import Path as MPath
33
+ from matplotlib.textpath import TextPath
34
+
35
+ from cell_type_annotation.hierarchy import LabelHierarchy, build_hierarchy, hierarchy_row_positions
36
+
37
+ #: Ribbon colours for an effect up and down, the ends of RdBu_r.
38
+ DIRECTIONAL_COLORS = {"up": "#b2182b", "down": "#2166ac"}
39
+
40
+ RibbonColor = Literal["enrichment", "family"]
41
+ RibbonWidth = Literal["significance", "n_cells", "constant"]
42
+ RGB = tuple[float, float, float]
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class HierarchyStyle:
47
+ """Typography, ink and geometry of :func:`annotation_hierarchy`.
48
+
49
+ Sizes and distances are in points, except ``box_height`` (a fraction of a row). Pass a
50
+ modified copy, e.g. ``HierarchyStyle(label_size=7)``, to restyle the plot.
51
+ """
52
+
53
+ label_size: float = 6.0
54
+ marker_size: float = 5.0
55
+ number_size: float = 5.0
56
+ header_size: float = 7.0
57
+ subheader_size: float = 5.0
58
+ badge_size: float = 5.0
59
+ #: Baseline distance of stacked lines (labels, genes), as a multiple of their font size.
60
+ line_spacing: float = 1.15
61
+ ink: str = "black"
62
+ ink_secondary: str = "#595959"
63
+ #: Fraction of a row a node box fills.
64
+ box_height: float = 0.8
65
+ box_linewidth: float = 0.5
66
+ box_rounding: float = 1.0
67
+ #: Fraction of the way toward white for a box's fill, relative to its edge colour.
68
+ tint: float = 0.72
69
+ badge_diameter: float = 7.0
70
+ #: Inner margin of a box.
71
+ padding: float = 2.0
72
+ #: Space between a box's label, genes and numbers.
73
+ spacing: float = 3.0
74
+ #: Minimum horizontal space between two columns, which the ribbons cross.
75
+ column_gap: float = 12.0
76
+ #: Length of the lead-in ribbon of each root node.
77
+ stub: float = 6.0
78
+ #: Linewidth range a ribbon can take.
79
+ ribbon_linewidth: tuple[float, float] = (0.4, 3.0)
80
+ #: Linewidth of a ribbon that could not be tested. Not testable is a statement about the tree,
81
+ #: not a weak result, so it is fixed rather than the bottom of the significance scale.
82
+ untested_linewidth: float = 1.0
83
+ #: Opacity of the ribbons. Deliberately not an encoding channel: fading by significance on top
84
+ #: of a colour ramp made both unreadable.
85
+ ribbon_alpha: float = 0.8
86
+ #: Height of a row when the function creates its own figure.
87
+ row_height: float = 16.0
88
+ #: Baseline of the level titles above the axes' top edge; ``None`` puts them just above the
89
+ #: marker sub-headers. Raise it to make room for, say, tick labels of a neighbouring axes.
90
+ title_offset: float | None = None
91
+ #: Size and colour of a node's flag symbol, drawn where its markers would be.
92
+ flag_size: float = 7.0
93
+ flag_color: str = "#b2182b"
94
+
95
+
96
+ def _tint(color, amount: float) -> RGB:
97
+ """Blend ``color`` toward white by ``amount``, for a box fill under a saturated edge."""
98
+ r, g, b = to_rgb(color)
99
+ return tuple(channel + (1.0 - channel) * amount for channel in (r, g, b))
100
+
101
+
102
+ def _ink_on(color) -> str:
103
+ """Pick dark or light text for legibility on ``color``, by BT.601 luma."""
104
+ r, g, b = to_rgb(color)
105
+ return "black" if (0.299 * r + 0.587 * g + 0.114 * b) > 0.55 else "white"
106
+
107
+
108
+ def _splits(label: str, max_lines: int) -> list[list[str]]:
109
+ """Every way to break ``label`` onto at most ``max_lines`` lines.
110
+
111
+ Breaks fall at spaces, or after a hyphen before a lowercase letter, so "MB-HB" stays whole.
112
+ """
113
+ out = [[label]]
114
+ if max_lines < 2:
115
+ return out
116
+ for i, char in enumerate(label):
117
+ if char == " ":
118
+ head, tail = label[:i], label[i + 1 :]
119
+ elif char == "-" and 0 < i < len(label) - 1 and label[i + 1].islower(): # not inside "MB-HB"
120
+ head, tail = label[: i + 1], label[i + 1 :]
121
+ else:
122
+ continue
123
+ out += [[head, *rest] for rest in _splits(tail, max_lines - 1)]
124
+ return out
125
+
126
+
127
+ def _wrap(label: str, width: float, measure, max_lines: int = 2) -> list[str]:
128
+ """Break ``label`` onto the fewest lines no wider than ``width`` points.
129
+
130
+ Falls back to the narrowest possible break when nothing fits.
131
+ """
132
+ options = sorted(_splits(label, max_lines), key=lambda lines: (len(lines), max(map(measure, lines))))
133
+ fitting = [lines for lines in options if max(map(measure, lines)) <= width + 1e-6]
134
+ return fitting[0] if fitting else min(options, key=lambda lines: max(map(measure, lines)))
135
+
136
+
137
+ def _text_width_points(text: str, size: float, weight: str = "normal", style: str = "normal") -> float:
138
+ """Measure a string's rendered width in points, using the actual glyph outlines."""
139
+ if not text:
140
+ return 0.0
141
+ prop = FontProperties(family="sans-serif", size=size, weight=weight, style=style)
142
+ return TextPath((0, 0), text, prop=prop).get_extents().width
143
+
144
+
145
+ @dataclass
146
+ class HierarchyLayout:
147
+ """Where :func:`annotation_hierarchy` placed everything.
148
+
149
+ x is in points from the axes' left edge, y in rows (row ``i`` at ``y = i``).
150
+
151
+ Attributes
152
+ ----------
153
+ ax
154
+ The axes the tree was drawn into
155
+ hierarchy
156
+ The hierarchy that was drawn
157
+ leaf_order
158
+ Leaf labels top to bottom; row ``i`` is ``leaf_order[i]``
159
+ y_of
160
+ Vertical position of every ``(level, node)``
161
+ leaf_y
162
+ Vertical position of each leaf, i.e. of each row
163
+ colors
164
+ Node colour for every ``(level, node)``, including ``(leaf_level, leaf)``
165
+ column_x
166
+ ``(x0, width)`` of each drawn level column
167
+ marker_x
168
+ x of the marker-gene column of each drawn level, for drawing a custom mark there
169
+ x_end
170
+ Right edge of the drawn tree
171
+ row_points
172
+ Height of one row in points
173
+ header_offsets
174
+ ``(title, subheader)`` baselines in points above the axes' top edge, so neighbouring
175
+ panels can align their own headers
176
+ style
177
+ The style the tree was drawn with
178
+ """
179
+
180
+ ax: Axes
181
+ hierarchy: LabelHierarchy
182
+ leaf_order: list[str]
183
+ y_of: dict[tuple[str, str], float]
184
+ leaf_y: dict[str, float]
185
+ colors: dict[tuple[str, str], RGB]
186
+ column_x: list[tuple[float, float]]
187
+ marker_x: list[float]
188
+ x_end: float
189
+ row_points: float
190
+ header_offsets: tuple[float, float]
191
+ style: HierarchyStyle
192
+ _enrichment: dict | None = field(default=None, repr=False)
193
+ _ribbons: dict = field(default_factory=dict, repr=False)
194
+
195
+ @property
196
+ def leaf_level_name(self) -> str:
197
+ """Name of the ``obs`` column whose categories are the figure's rows."""
198
+ return self.hierarchy.leaf_level
199
+
200
+ def text_width(self, text: str, size: float, weight: str = "normal", style: str = "normal") -> float:
201
+ """Return the rendered width of ``text`` in points, the x unit of the axes."""
202
+ return _text_width_points(text, size, weight, style)
203
+
204
+ def enrichment_mappable(self) -> ScalarMappable:
205
+ """Return the ribbon colour scale as a mappable, for a colorbar.
206
+
207
+ Raises
208
+ ------
209
+ ValueError
210
+ If the tree was drawn without enrichment colours.
211
+ """
212
+ info = self._require_enrichment()
213
+ scale, metric = info["scale"], info["metric"]
214
+ ramp = [
215
+ _enrichment_color({metric: t * scale, "estimable": True}, scale, info["colors"], metric)
216
+ for t in np.linspace(-1.0, 1.0, 257)
217
+ ]
218
+ return ScalarMappable(norm=Normalize(-scale, scale), cmap=ListedColormap(ramp))
219
+
220
+ def ribbon_handles(self, qvalues: Sequence[float] = (1.0, 0.05, 0.001)) -> list[Line2D]:
221
+ """Return legend handles for what the drawn ribbons' widths and dashes encode.
222
+
223
+ Width examples per the ``ribbon_width`` in effect (none when every ribbon has one width),
224
+ then the dashed untested ribbon if one was drawn.
225
+
226
+ Parameters
227
+ ----------
228
+ qvalues
229
+ Adjusted p-values to show, when width encodes significance. Labels are the values
230
+ themselves; the last is the saturation point if it is at or below it
231
+
232
+ Returns
233
+ -------
234
+ list
235
+ :class:`~matplotlib.lines.Line2D` handles with labels, for ``ax.legend(handles=...)``.
236
+ """
237
+ info = self._ribbons
238
+ style = self.style
239
+ handles = []
240
+ if info["width_by"] == "significance":
241
+ for q in qvalues:
242
+ lw = _ribbon_linewidth({"estimable": True, "qvalue": q}, "significance", 0, 1, style)
243
+ label = f"≤{q:g}" if -np.log10(q) >= SIGNIFICANCE_SPAN else f"{q:g}"
244
+ handles.append(Line2D([], [], color=NEUTRAL_RIBBON, lw=lw, solid_capstyle="butt", label=label))
245
+ elif info["width_by"] == "n_cells" and info["counts"]:
246
+ total = max(self.hierarchy.n_cells_total, 1)
247
+ smallest = max(min(info["counts"]), 1)
248
+ for n in (10**k for k in range(int(np.log10(smallest)), int(np.log10(total)) + 1)):
249
+ lw = _ribbon_linewidth(None, "n_cells", n, total, style)
250
+ handles.append(Line2D([], [], color=NEUTRAL_RIBBON, lw=lw, solid_capstyle="butt", label=f"{n:,}"))
251
+ if info["dashed"]:
252
+ lw = style.untested_linewidth
253
+ handles.append(Line2D([], [], color=NEUTRAL_RIBBON, lw=lw, ls=_dashes_for(lw), label="Not tested"))
254
+ return handles
255
+
256
+ def _require_enrichment(self) -> dict:
257
+ if self._enrichment is None:
258
+ raise ValueError("This layout was drawn without enrichment colours, so the ribbons have no key")
259
+ return self._enrichment
260
+
261
+
262
+ def hierarchy_palette(
263
+ hierarchy: LabelHierarchy,
264
+ *,
265
+ root_colors: Mapping[str, Any] | None = None,
266
+ hue_span: float = 80.0,
267
+ lightness_spread: float = 0.16,
268
+ sibling_spread: float = 0.12,
269
+ group_level: str | None = None,
270
+ grey_categories: Sequence[str] = ("Unknown", "Unassigned"),
271
+ ) -> dict[tuple[str, str], RGB]:
272
+ """Derive a colour for every node, coherent within each root family.
273
+
274
+ Each root class gets an anchor colour and its leaves fan out around it, keeping saturation, so
275
+ a family reads as one colour band. Every internal node then takes the mean colour of its own
276
+ leaves, which makes a parent visibly the average of what it contains.
277
+
278
+ Colour is built from two superposed components. A **family-wide ramp** in hue and lightness
279
+ runs monotonically over the leaves, so a clade's colours stay continuous and neighbouring
280
+ clades stay neighbouring colours. On top of it, a **within-group lightness offset** pulls
281
+ apart the children of one parent, which the ramp alone cannot do: a family of 11 leaves would
282
+ need most of the gamut to separate neighbours by eye, and stretching it that far stops the
283
+ family reading as one colour.
284
+
285
+ Both are needed. Driving everything from the family ramp leaves siblings indistinguishable
286
+ (CIE76 ΔE under 3 in practice); driving hue from the group index instead makes every clade
287
+ restart the same lightness ramp, so the last member of one clade collides with the last member
288
+ of the next while jumping away from its own sibling.
289
+
290
+ Parameters
291
+ ----------
292
+ hierarchy
293
+ The hierarchy to colour
294
+ root_colors
295
+ Anchor colour per root-level label. Missing labels fall back to matplotlib's ``tab20``
296
+ hue_span
297
+ Hue arc in degrees spanned by one family
298
+ lightness_spread
299
+ Lightness ramp (+/-) across one family, which is what keeps a clade's colours continuous
300
+ sibling_spread
301
+ Extra lightness offset (+/-) applied within one sibling group, on top of that ramp. This
302
+ is what pulls two children of the same parent apart
303
+ group_level
304
+ Level whose nodes define a sibling group. Defaults to the second-deepest drawn level, i.e.
305
+ the parent of the deepest column
306
+ grey_categories
307
+ Root labels rendered as greys instead of hues, for classes such as ``'Unknown'`` that
308
+ should not read as a biological identity
309
+
310
+ Returns
311
+ -------
312
+ dict
313
+ Mapping of ``(level, node)`` to an RGB triple.
314
+
315
+ Examples
316
+ --------
317
+ >>> colors = hierarchy_palette(hierarchy, root_colors={"NPC": "#2d62a3", "Neuron": "#ED496F"})
318
+ """
319
+ root_level = hierarchy.all_levels[0]
320
+ roots = hierarchy.nodes(root_level)
321
+
322
+ anchors = dict(root_colors or {})
323
+ palette = plt.get_cmap("tab20").colors
324
+ for i, root in enumerate(r for r in roots if r not in anchors):
325
+ anchors[root] = to_hex(palette[i % len(palette)])
326
+
327
+ levels = hierarchy.levels
328
+ group_level = group_level or (levels[-2] if len(levels) >= 2 else root_level)
329
+ group_of = {leaf: node for node in hierarchy.nodes(group_level) for leaf in hierarchy.leaves_of(group_level, node)}
330
+
331
+ leaf_color: dict[str, RGB] = {}
332
+ grey = set(grey_categories)
333
+ for root in roots:
334
+ leaves = hierarchy.leaves_of(root_level, root)
335
+ r, g, b = to_rgb(anchors[root])
336
+ hue, lightness, saturation = colorsys.rgb_to_hls(r, g, b)
337
+
338
+ # Leaves come in nested order, so one group's leaves are contiguous.
339
+ groups: list[tuple[str, list[str]]] = []
340
+ for leaf in leaves:
341
+ node = group_of.get(leaf, leaf)
342
+ if not groups or groups[-1][0] != node:
343
+ groups.append((node, []))
344
+ groups[-1][1].append(leaf)
345
+
346
+ # Hue runs monotonically across the whole family, so a family reads as one continuous band
347
+ # and neighbouring clades stay neighbouring colours. Lightness varies only *within* a
348
+ # group, which is what separates siblings. Driving hue from the group index instead makes
349
+ # every clade restart the same lightness ramp, so the last member of one clade collides
350
+ # with the last member of the next while jumping away from its own sibling.
351
+ n_leaves = len(leaves)
352
+ j = 0
353
+ for _node, members in groups:
354
+ for li, leaf in enumerate(members):
355
+ ramp = 0.5 if n_leaves == 1 else j / (n_leaves - 1)
356
+ offset = 0.0 if len(members) == 1 else (li / (len(members) - 1) - 0.5) * 2
357
+ j += 1
358
+ if root in grey:
359
+ leaf_color[leaf] = colorsys.hls_to_rgb(0.0, 0.62 - 0.12 * ramp, 0.0)
360
+ continue
361
+ shifted_hue = (hue + (ramp - 0.5) * hue_span / 360.0) % 1.0
362
+ shifted_lightness = min(
363
+ 0.86, max(0.24, lightness + (ramp - 0.5) * 2 * lightness_spread + offset * sibling_spread)
364
+ )
365
+ leaf_color[leaf] = colorsys.hls_to_rgb(shifted_hue, shifted_lightness, saturation)
366
+
367
+ return {
368
+ (level, node): tuple(np.array([leaf_color[leaf] for leaf in hierarchy.leaves_of(level, node)]).mean(0))
369
+ for level, node in hierarchy.iter_nodes()
370
+ }
371
+
372
+
373
+ def _enrichment_lookup(enrichment: pd.DataFrame | None, metric: str = "log_odds") -> dict[tuple[str, str], dict]:
374
+ """Index an enrichment frame by ``(level, node)``."""
375
+ if enrichment is None or enrichment.empty:
376
+ return {}
377
+ missing = {"level", "node", metric} - set(enrichment.columns)
378
+ if missing:
379
+ raise ValueError(f"`enrichment` is missing columns: {sorted(missing)}")
380
+ return {(row["level"], row["node"]): row for _, row in enrichment.iterrows()}
381
+
382
+
383
+ NEUTRAL_RIBBON = "#b8b7b0"
384
+ #: -log10(q) at which the significance encoding saturates, i.e. q = 1e-3.
385
+ SIGNIFICANCE_SPAN = 3.0
386
+
387
+
388
+ def _is_testable(record: dict | None) -> bool:
389
+ """Whether a node was actually tested, as opposed to having no siblings to test against."""
390
+ return record is not None and bool(record.get("estimable", False))
391
+
392
+
393
+ def _significance(record: dict | None) -> float:
394
+ """Return significance on a 0-1 scale from the adjusted p-value, or 0 when untested."""
395
+ if not _is_testable(record):
396
+ return 0.0
397
+ q = record.get("qvalue", np.nan)
398
+ if pd.isna(q):
399
+ q = record.get("pvalue", np.nan)
400
+ if pd.isna(q):
401
+ return 0.0
402
+ return float(np.clip(-np.log10(max(float(q), 1e-12)) / SIGNIFICANCE_SPAN, 0.0, 1.0))
403
+
404
+
405
+ def _enrichment_color(record: dict | None, scale: float, colors: Mapping[str, Any], metric: str) -> Any:
406
+ """Map an enrichment record to a diverging colour: hue is direction, saturation is magnitude."""
407
+ if not _is_testable(record):
408
+ return to_rgb(NEUTRAL_RIBBON)
409
+ effect = record.get(metric, 0.0)
410
+ effect = 0.0 if pd.isna(effect) else float(effect)
411
+ magnitude = min(abs(effect) / scale, 1.0) if scale > 0 else 0.0
412
+ target = colors["up"] if effect > 0 else colors["down"]
413
+ return tuple(np.array(to_rgb(NEUTRAL_RIBBON)) * (1 - magnitude) + np.array(to_rgb(target)) * magnitude)
414
+
415
+
416
+ def _ribbon_linewidth(record: dict | None, width_by: str, n_cells: int, n_total: int, style: HierarchyStyle) -> float:
417
+ """Return a ribbon linewidth in points, from whichever variable drives width."""
418
+ lo, hi = style.ribbon_linewidth
419
+ if width_by == "n_cells":
420
+ return lo + (hi - lo) * float(np.sqrt(n_cells / max(n_total, 1)))
421
+ if width_by == "significance":
422
+ if not _is_testable(record):
423
+ return style.untested_linewidth
424
+ return lo + (hi - lo) * _significance(record)
425
+ return (lo + hi) / 2
426
+
427
+
428
+ def _dashes_for(lw: float, on: float = 3.0, off: float = 2.2) -> tuple[float, tuple[float, float]]:
429
+ """Return a dash pattern that renders as ``on``/``off`` points regardless of linewidth.
430
+
431
+ Matplotlib scales a dash pattern by its linewidth, so a thick dashed ribbon gets
432
+ proportionally longer dashes — over a short span it shows a single dash and reads as solid.
433
+ Dividing through by the linewidth cancels that scaling.
434
+ """
435
+ lw = max(lw, 1e-6)
436
+ return (0.0, (on / lw, off / lw))
437
+
438
+
439
+ def _markers_by_node(markers: pd.DataFrame | None) -> dict[tuple[str, str], list[tuple[str, float, float]]]:
440
+ """Group the markers to show by ``(level, node)``, keeping their order."""
441
+ if markers is None or markers.empty:
442
+ return {}
443
+ missing = {"level", "node", "gene", "det_in", "det_out"} - set(markers.columns)
444
+ if missing:
445
+ raise ValueError(f"`markers` is missing columns: {sorted(missing)}")
446
+ out: dict[tuple[str, str], list[tuple[str, float, float]]] = {}
447
+ for r in markers.itertuples(index=False):
448
+ out.setdefault((r.level, r.node), []).append((str(r.gene), float(r.det_in), float(r.det_out)))
449
+ return out
450
+
451
+
452
+ def annotation_hierarchy(
453
+ adata: AnnData | None = None,
454
+ levels: Sequence[str] | None = None,
455
+ *,
456
+ ax: Axes | None = None,
457
+ hierarchy: LabelHierarchy | None = None,
458
+ leaf_level: str | None = None,
459
+ root_order: Sequence[str] | None = None,
460
+ markers: pd.DataFrame | None = None,
461
+ flags: pd.DataFrame | None = None,
462
+ enrichment: pd.DataFrame | None = None,
463
+ enrichment_metric: Literal["log_odds", "effect_pts"] = "log_odds",
464
+ enrichment_scale: float | None = None,
465
+ enrichment_colors: Mapping[str, Any] | None = None,
466
+ ribbon_color: RibbonColor = "enrichment",
467
+ ribbon_width: RibbonWidth = "significance",
468
+ root_stub: bool = True,
469
+ bold_nodes: Collection[str] | None = None,
470
+ display_names: Mapping[str, str] | None = None,
471
+ level_titles: Sequence[str] | None = None,
472
+ level_subtitles: Sequence[str] | None = None,
473
+ marker_headers: tuple[str, str] | None = ("Marker", "In/out (%)"),
474
+ badge_level: str | None = None,
475
+ draw_badge: Callable[[Axes, float, float, Any, str], Any] | None = None,
476
+ root_colors: Mapping[str, Any] | None = None,
477
+ node_colors: Mapping[tuple[str, str], Any] | None = None,
478
+ max_label_lines: int = 2,
479
+ style: HierarchyStyle | None = None,
480
+ ) -> HierarchyLayout:
481
+ """Draw a nested annotation hierarchy as columns of labelled boxes joined by ribbons.
482
+
483
+ One column is drawn per entry in ``levels``, with one row per leaf. Each node box carries its
484
+ label, the marker genes it is given (italic) with their in/out detection percentages, and
485
+ optionally a numbered badge. Ribbons join each node to its parent; their colour carries the
486
+ condition effect when an enrichment frame is supplied, and their width its significance.
487
+
488
+ The function works for any number of levels. ``leaf_level`` may name a column finer than the
489
+ last drawn level, in which case rows are that column's categories and the deepest boxes simply
490
+ have no outgoing ribbons.
491
+
492
+ Parameters
493
+ ----------
494
+ adata
495
+ AnnData object holding the label columns. Not needed if ``hierarchy`` is given
496
+ levels
497
+ Names of the ``obs`` columns to draw, coarse to fine
498
+ ax
499
+ Axes to draw into. The tree fills its width: any width beyond what the content needs
500
+ widens the boxes, and too little raises. The y limits are set to span exactly the rows.
501
+ Without ``ax``, a figure just wide enough is created
502
+ hierarchy
503
+ A pre-built hierarchy, used instead of deriving one from ``adata``
504
+ leaf_level
505
+ ``obs`` column defining the rows. Defaults to the last entry of ``levels``
506
+ root_order
507
+ Explicit ordering of the root-level labels, top to bottom
508
+ markers
509
+ The markers to show, one row per gene in display order, with columns ``level``, ``node``,
510
+ ``gene``, ``det_in`` and ``det_out`` (percentage of cells detecting the gene in the node and
511
+ in its siblings). Choosing them is the caller's job, e.g. with
512
+ :func:`~cell_type_annotation.markers.display_markers`. Nodes without rows show none; a
513
+ caller can draw its own mark at :attr:`HierarchyLayout.marker_x`. Pass ``None`` to draw a
514
+ bare tree
515
+ flags
516
+ Nodes to mark with a symbol instead of markers, with columns ``level``, ``node`` and
517
+ ``symbol``, as returned by :func:`~cell_type_annotation.markers.display_markers`
518
+ enrichment
519
+ Per-node condition effects used to colour the ribbons, with columns ``level``, ``node``,
520
+ ``estimable``, ``qvalue`` and ``enrichment_metric``, e.g. from a parent-conditional
521
+ composition model with the replicate as the unit
522
+ enrichment_metric
523
+ Column of ``enrichment`` driving the ribbon colour. ``'log_odds'`` (default) is the model's
524
+ native scale and is independent of how abundant a node is; ``'effect_pts'`` is in
525
+ percentage points, which is easier to read but systematically hides small classes — a node
526
+ holding 3% of the cells cannot move more than a few points however condition-specific it is
527
+ enrichment_scale
528
+ Value of ``enrichment_metric`` that saturates the ribbon colour. Defaults to the largest
529
+ absolute value among estimable nodes
530
+ enrichment_colors
531
+ Mapping with keys ``'up'`` and ``'down'`` giving the two directional colours. Defaults to
532
+ :data:`DIRECTIONAL_COLORS`; pass the conditions' own colours where they have them
533
+ ribbon_color
534
+ ``'enrichment'`` colours ribbons by condition effect, ``'family'`` by the child's own
535
+ colour. Falls back to ``'family'`` when no enrichment frame is given
536
+ ribbon_width
537
+ What drives ribbon thickness: ``'significance'`` (default), ``'n_cells'``, or
538
+ ``'constant'``. A ribbon has only two readable channels, colour and width, so exactly one
539
+ variable goes in each
540
+ root_stub
541
+ Whether to draw a short lead-in ribbon for each root-level node, so the root level shares
542
+ the same encoding as the rest of the tree
543
+ bold_nodes
544
+ Node labels to draw in bold, for marking a class of node (organizing centres, say)
545
+ display_names
546
+ Text to show instead of a node's label, keyed by label; e.g. for sentence case
547
+ level_titles
548
+ Column headers. Defaults to the ``obs`` column names
549
+ level_subtitles
550
+ Text after each header, describing what the level means
551
+ marker_headers
552
+ Sub-headers over the gene and number columns, or ``None`` for none (and no width spent on them)
553
+ badge_level
554
+ Level whose boxes carry a numbered badge, numbered by that column's categorical order
555
+ draw_badge
556
+ ``draw_badge(ax, x, y, color, label)`` draws one badge, so a figure can use the same mark it
557
+ uses elsewhere; its diameter must match ``style.badge_diameter``. Defaults to a filled
558
+ circle with the label in black or white
559
+ root_colors
560
+ Anchor colour per root-level label, passed to :func:`hierarchy_palette`. Defaults to
561
+ ``adata.uns[f"{levels[0]}_colors"]`` when present
562
+ node_colors
563
+ Explicit colour per ``(level, node)``, bypassing :func:`hierarchy_palette` entirely
564
+ max_label_lines
565
+ Maximum number of lines a label may wrap onto. A column is as wide as its widest label at
566
+ its narrowest break; within that width (plus any spare width of the axes) each label takes
567
+ as few lines as fit. Breaks fall at spaces, or after a hyphen before a lowercase letter
568
+ style
569
+ Typography, ink and geometry. Defaults to :class:`HierarchyStyle`'s defaults
570
+
571
+ Returns
572
+ -------
573
+ HierarchyLayout
574
+ Where everything was drawn, so further panels can be aligned to the same rows.
575
+
576
+ Examples
577
+ --------
578
+ >>> shown, flags = display_markers(scores, hierarchy, markers, adata.var_names)
579
+ >>> layout = annotation_hierarchy(adata, hierarchy=hierarchy, markers=shown, flags=flags)
580
+ >>> layout.ax.scatter([layout.x_end + 2], [layout.leaf_y["Dorsal Telen. NPC"]])
581
+ """
582
+ if hierarchy is None:
583
+ if adata is None or levels is None:
584
+ raise ValueError("Pass either `hierarchy`, or both `adata` and `levels`")
585
+ hierarchy = build_hierarchy(adata, levels, leaf_level=leaf_level, root_order=root_order)
586
+ root_key = f"{hierarchy.all_levels[0]}_colors"
587
+ if root_colors is None and adata is not None and root_key in adata.uns:
588
+ categories = adata.obs[hierarchy.all_levels[0]].astype("category").cat.categories
589
+ root_colors = dict(zip(map(str, categories), adata.uns[root_key], strict=False)) # nodes are strings
590
+
591
+ style = style or HierarchyStyle()
592
+ drawn_levels = list(hierarchy.levels)
593
+ n_levels = len(drawn_levels)
594
+ bold = set(bold_nodes or ())
595
+ names = dict(display_names or {})
596
+
597
+ titles = list(level_titles) if level_titles is not None else list(drawn_levels)
598
+ subtitles = list(level_subtitles) if level_subtitles is not None else [""] * n_levels
599
+ for name, seq in (("level_titles", titles), ("level_subtitles", subtitles)):
600
+ if len(seq) != n_levels:
601
+ raise ValueError(f"`{name}` has {len(seq)} entries but there are {n_levels} levels")
602
+
603
+ colors: dict[tuple[str, str], RGB] = (
604
+ {key: to_rgb(value) for key, value in node_colors.items()}
605
+ if node_colors is not None
606
+ else hierarchy_palette(hierarchy, root_colors=root_colors)
607
+ )
608
+ y_of = hierarchy_row_positions(hierarchy)
609
+ leaf_y = {leaf: y_of[(hierarchy.leaf_level, leaf)] for leaf in hierarchy.leaf_order}
610
+ n_rows = len(hierarchy.leaf_order)
611
+
612
+ enrichment_by_node = _enrichment_lookup(enrichment, enrichment_metric)
613
+ use_enrichment = ribbon_color == "enrichment" and bool(enrichment_by_node)
614
+ if enrichment_scale is None:
615
+ effects = [
616
+ abs(float(r[enrichment_metric]))
617
+ for r in enrichment_by_node.values()
618
+ if r.get("estimable", False) and pd.notna(r[enrichment_metric])
619
+ ]
620
+ enrichment_scale = max(effects) if effects else 1.0
621
+ if not np.isfinite(enrichment_scale) or enrichment_scale <= 0:
622
+ enrichment_scale = 1.0
623
+ directional = dict(enrichment_colors or DIRECTIONAL_COLORS)
624
+
625
+ # --- column geometry in points, measured from rendered glyphs ---
626
+ def measure(node):
627
+ size, weight = style.label_size, "bold" if node in bold else "normal"
628
+ return lambda line: _text_width_points(line, size, weight)
629
+
630
+ def lines_of(node, width=0.0):
631
+ """A label's lines: on as few as fit ``width``; at its narrowest when ``width`` is 0."""
632
+ return _wrap(names.get(node, node), width, measure(node), max_label_lines)
633
+
634
+ shown_by_node = _markers_by_node(markers)
635
+ flag_of = {} if flags is None else {(r.level, r.node): str(r.symbol) for r in flags.itertuples(index=False)}
636
+ badge_w, label_w, gene_w, number_w, block_w, min_w = [], [], [], [], [], []
637
+ for i, level in enumerate(drawn_levels):
638
+ badge_w.append(style.badge_diameter + style.spacing if level == badge_level else 0.0)
639
+ label_w.append(
640
+ max(
641
+ _text_width_points(line, style.label_size, "bold" if node in bold else "normal")
642
+ for node in hierarchy.nodes(level)
643
+ for line in lines_of(node)
644
+ )
645
+ )
646
+ shown = [m for node in hierarchy.nodes(level) for m in shown_by_node.get((level, node), [])]
647
+ symbols = [flag_of[(level, node)] for node in hierarchy.nodes(level) if (level, node) in flag_of]
648
+ if shown or symbols:
649
+ heads = marker_headers or ("", "")
650
+ gene_w.append(
651
+ max(
652
+ [_text_width_points(t, style.marker_size, style="italic") for t, *_ in shown]
653
+ + [_text_width_points(s, style.flag_size, "bold") for s in symbols]
654
+ + [_text_width_points(heads[0], style.subheader_size)]
655
+ )
656
+ )
657
+ number_w.append(
658
+ max(
659
+ [_text_width_points(f"{a:.0f}/{b:.0f}", style.number_size) for _t, a, b in shown]
660
+ + [_text_width_points(heads[1], style.subheader_size)]
661
+ )
662
+ )
663
+ block_w.append(gene_w[-1] + style.spacing + number_w[-1])
664
+ else:
665
+ gene_w.append(0.0)
666
+ number_w.append(0.0)
667
+ block_w.append(0.0)
668
+ title_w = _text_width_points(titles[i], style.header_size, "bold")
669
+ if subtitles[i]:
670
+ title_w += style.header_size * 0.4 + _text_width_points(subtitles[i], style.subheader_size)
671
+ min_w.append(
672
+ max(
673
+ 2 * style.padding + badge_w[i] + label_w[i] + (2 * style.spacing + block_w[i] if block_w[i] else 0),
674
+ title_w,
675
+ )
676
+ )
677
+
678
+ stub = style.stub if root_stub else 0.0
679
+ needed = stub + sum(min_w) + style.column_gap * (n_levels - 1)
680
+ default_title = style.subheader_size + 2.0 + 2.5 # just above the marker sub-headers
681
+ header_offsets = (default_title if style.title_offset is None else style.title_offset, 2.0)
682
+ header_pt = header_offsets[0] + style.header_size
683
+
684
+ if ax is None:
685
+ fig_w, fig_h = needed / 72.0, (n_rows * style.row_height + header_pt) / 72.0
686
+ fig = plt.figure(figsize=(fig_w, fig_h))
687
+ ax = fig.add_axes((0, 0, 1, n_rows * style.row_height / 72.0 / fig_h))
688
+ fig = ax.figure
689
+ position = ax.get_position()
690
+ width_pt = position.width * fig.get_figwidth() * 72.0
691
+ height_pt = position.height * fig.get_figheight() * 72.0
692
+ if needed > width_pt + 1e-6:
693
+ raise ValueError(
694
+ f"The hierarchy needs {needed / 72 * 25.4:.1f} mm but the axes are {width_pt / 72 * 25.4:.1f} mm wide. "
695
+ "Widen the axes, allow more `max_label_lines`, or reduce sizes in `style`."
696
+ )
697
+ extra = (width_pt - needed) / n_levels
698
+ widths = [w + extra for w in min_w]
699
+ x0, cursor = [], stub
700
+ for w in widths:
701
+ x0.append(cursor)
702
+ cursor += w + style.column_gap
703
+ x_end = x0[-1] + widths[-1]
704
+ number_x = [x0[i] + widths[i] - style.padding - number_w[i] for i in range(n_levels)]
705
+ marker_x = [x0[i] + widths[i] - style.padding - block_w[i] for i in range(n_levels)]
706
+
707
+ ax.set_xlim(0, width_pt)
708
+ ax.set_ylim(n_rows - 0.5, -0.5)
709
+ ax.axis("off")
710
+ row_pt = height_pt / n_rows
711
+
712
+ def rows(points):
713
+ return points / row_pt
714
+
715
+ # --- ribbons ---
716
+ # What the drawn ribbons actually encode, for their key: without test records, significance
717
+ # widths collapse to one width, and only drawn untested ribbons are dashed.
718
+ width_by = "constant" if ribbon_width == "significance" and not enrichment_by_node else ribbon_width
719
+ ribbons = {"width_by": width_by, "dashed": False, "counts": []}
720
+
721
+ def draw_ribbon(x_start, y_start, x_stop, y_stop, color, linestyle, lw, n_cells):
722
+ ribbons["dashed"] |= linestyle != "solid"
723
+ ribbons["counts"].append(n_cells)
724
+ dx = (x_stop - x_start) * 0.45
725
+ path = MPath(
726
+ [(x_start, y_start), (x_start + dx, y_start), (x_stop - dx, y_stop), (x_stop, y_stop)],
727
+ [MPath.MOVETO, MPath.CURVE4, MPath.CURVE4, MPath.CURVE4],
728
+ )
729
+ ax.add_patch(
730
+ PathPatch(path, fc="none", ec=color, lw=lw, alpha=style.ribbon_alpha, linestyle=linestyle, zorder=1)
731
+ )
732
+
733
+ def ribbon_style(level, node):
734
+ """Return ``(colour, linestyle, linewidth, n_cells)`` for one node's incoming ribbon."""
735
+ record = enrichment_by_node.get((level, node)) if enrichment_by_node else None
736
+ lw = _ribbon_linewidth(record, ribbon_width, hierarchy.n_cells(level, node), hierarchy.n_cells_total, style)
737
+ color = (
738
+ _enrichment_color(record, enrichment_scale, directional, enrichment_metric)
739
+ if use_enrichment
740
+ else colors[(level, node)]
741
+ )
742
+ # A node with no siblings was never tested; dashed says so without implying "no effect".
743
+ linestyle = "solid" if (record is None or _is_testable(record)) else _dashes_for(lw)
744
+ return color, linestyle, lw, hierarchy.n_cells(level, node)
745
+
746
+ if root_stub:
747
+ root_level = drawn_levels[0]
748
+ for node in hierarchy.nodes(root_level):
749
+ y = y_of[(root_level, node)]
750
+ draw_ribbon(0.0, y, x0[0], y, *ribbon_style(root_level, node))
751
+
752
+ for i in range(n_levels - 1):
753
+ parent_level, child_level = drawn_levels[i], drawn_levels[i + 1]
754
+ for node in hierarchy.nodes(child_level):
755
+ parent = hierarchy.parent_of(child_level, node)
756
+ draw_ribbon(
757
+ x0[i] + widths[i],
758
+ y_of[(parent_level, parent)],
759
+ x0[i + 1],
760
+ y_of[(child_level, node)],
761
+ *ribbon_style(child_level, node),
762
+ )
763
+
764
+ # --- node boxes ---
765
+ badge_numbers: dict[str, int] = {}
766
+ if badge_level is not None:
767
+ if adata is not None and isinstance(adata.obs[badge_level].dtype, pd.CategoricalDtype):
768
+ badge_numbers = {str(c): i for i, c in enumerate(adata.obs[badge_level].cat.categories, 1)}
769
+ else:
770
+ badge_numbers = {n: i for i, n in enumerate(hierarchy.nodes(badge_level), 1)}
771
+
772
+ def stacked(n, size):
773
+ """Offsets in rows that centre ``n`` lines of ``size``-point text on a row."""
774
+ return [rows((k - (n - 1) / 2) * size * style.line_spacing) for k in range(n)]
775
+
776
+ text = {"zorder": 3, "va": "center_baseline"}
777
+ for i, level in enumerate(drawn_levels):
778
+ for node in hierarchy.nodes(level):
779
+ color = colors[(level, node)]
780
+ y = y_of[(level, node)]
781
+ ax.add_patch(
782
+ FancyBboxPatch(
783
+ (x0[i], y - style.box_height / 2),
784
+ widths[i],
785
+ style.box_height,
786
+ boxstyle=f"round,pad=0,rounding_size={style.box_rounding}",
787
+ mutation_aspect=1 / row_pt,
788
+ fc=_tint(color, style.tint),
789
+ ec=color,
790
+ lw=style.box_linewidth,
791
+ zorder=2,
792
+ )
793
+ )
794
+
795
+ label_x = x0[i] + style.padding
796
+ if level == badge_level and node in badge_numbers:
797
+ bx = label_x + style.badge_diameter / 2
798
+ if draw_badge is not None:
799
+ draw_badge(ax, bx, y, color, str(badge_numbers[node]))
800
+ else:
801
+ ax.scatter(
802
+ [bx], [y], s=style.badge_diameter**2, c=[color], edgecolors="none", zorder=4, clip_on=False
803
+ )
804
+ ax.text(
805
+ bx, y, str(badge_numbers[node]), ha="center", fontsize=style.badge_size,
806
+ color=_ink_on(color), zorder=5, va="center_baseline",
807
+ ) # fmt: skip
808
+ label_x += badge_w[i]
809
+
810
+ lines = lines_of(node, label_w[i] + extra)
811
+ for line, dy in zip(lines, stacked(len(lines), style.label_size), strict=True):
812
+ ax.text(
813
+ label_x, y + dy, line, ha="left", fontsize=style.label_size, color=style.ink,
814
+ weight="bold" if node in bold else "normal", **text,
815
+ ) # fmt: skip
816
+
817
+ shown = shown_by_node.get((level, node), [])
818
+ for (gene, det_in, det_out), dy in zip(shown, stacked(len(shown), style.marker_size), strict=True):
819
+ ax.text(
820
+ marker_x[i], y + dy, gene, ha="left", fontsize=style.marker_size, color=style.ink,
821
+ style="italic", **text,
822
+ ) # fmt: skip
823
+ ax.text(
824
+ number_x[i], y + dy, f"{det_in:.0f}/{det_out:.0f}", ha="left", fontsize=style.number_size,
825
+ color=style.ink_secondary, **text,
826
+ ) # fmt: skip
827
+ if (level, node) in flag_of:
828
+ ax.text(
829
+ marker_x[i], y, flag_of[(level, node)], ha="left", fontsize=style.flag_size,
830
+ color=style.flag_color, weight="bold", **text,
831
+ ) # fmt: skip
832
+
833
+ # --- column headers, above the axes ---
834
+ def header(x, offset, string, **kwargs):
835
+ ax.annotate(
836
+ string, xy=(x, 1.0), xycoords=("data", "axes fraction"), xytext=(0, offset),
837
+ textcoords="offset points", ha="left", va="baseline", annotation_clip=False, **kwargs,
838
+ ) # fmt: skip
839
+
840
+ title_y, sub_y = header_offsets
841
+ for i in range(n_levels):
842
+ header(x0[i], title_y, titles[i], fontsize=style.header_size, color=style.ink, weight="bold")
843
+ if subtitles[i]:
844
+ gap = _text_width_points(titles[i], style.header_size, "bold") + style.header_size * 0.4
845
+ header(x0[i] + gap, title_y, subtitles[i], fontsize=style.subheader_size, color=style.ink_secondary)
846
+ if gene_w[i] and marker_headers:
847
+ header(marker_x[i], sub_y, marker_headers[0], fontsize=style.subheader_size, color=style.ink_secondary)
848
+ header(number_x[i], sub_y, marker_headers[1], fontsize=style.subheader_size, color=style.ink_secondary)
849
+
850
+ return HierarchyLayout(
851
+ ax=ax,
852
+ hierarchy=hierarchy,
853
+ leaf_order=list(hierarchy.leaf_order),
854
+ y_of=y_of,
855
+ leaf_y=leaf_y,
856
+ colors=colors,
857
+ column_x=list(zip(x0, widths, strict=True)),
858
+ marker_x=marker_x,
859
+ x_end=x_end,
860
+ row_points=row_pt,
861
+ header_offsets=header_offsets,
862
+ style=style,
863
+ _enrichment=(
864
+ {"metric": enrichment_metric, "scale": enrichment_scale, "colors": directional, "width_by": ribbon_width}
865
+ if use_enrichment
866
+ else None
867
+ ),
868
+ _ribbons=ribbons,
869
+ )