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,530 @@
1
+ """A strictly nested label hierarchy, and marker scoring of each node against its siblings.
2
+
3
+ A hierarchy is an ordered list of ``adata.obs`` columns, coarse to fine, that nest strictly: every
4
+ label at level ``i+1`` occurs under exactly one label at level ``i``. :func:`build_hierarchy`
5
+ enforces that per cell, so it doubles as the nesting check before write-back.
6
+
7
+ :func:`hierarchy_markers` asks, at every node, which genes mark it **against its siblings within
8
+ its parent**. That is the question of a top-down annotation: ``FOXG1`` is a poor telencephalic
9
+ marker against every other class (telencephalic progenitors carry it too), but an excellent one
10
+ at the branch point where the question is telencephalic versus non-telencephalic.
11
+ """
12
+
13
+ import logging
14
+ from collections.abc import Mapping, Sequence
15
+ from dataclasses import dataclass, field
16
+ from typing import Literal
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ import scipy.sparse as sp
21
+ from anndata import AnnData
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ ChildOrder = Literal["size", "name", "category"]
26
+ Aggregate = Literal["leaf_min", "pooled"]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class LabelHierarchy:
31
+ """A strictly nested hierarchy of categorical labels, derived from ``adata.obs`` columns.
32
+
33
+ Nodes are addressed by a ``(level, node)`` pair, where ``level`` is the name of the ``obs``
34
+ column the node lives in, so the object is agnostic about level naming.
35
+
36
+ Attributes
37
+ ----------
38
+ levels
39
+ The ``obs`` column names that make up the hierarchy, coarse to fine.
40
+ leaf_level
41
+ The ``obs`` column whose categories define the leaves. Either the last entry of ``levels``
42
+ or a further, finer column that is not itself drawn as a level.
43
+ leaf_order
44
+ Leaf labels in nested order: root classes in ``root_order``, then children ordered within
45
+ each parent. This is the top-to-bottom row order of the figure.
46
+ """
47
+
48
+ levels: tuple[str, ...]
49
+ leaf_level: str
50
+ leaf_order: tuple[str, ...]
51
+ _nodes: dict[str, tuple[str, ...]] = field(repr=False)
52
+ _parent: dict[tuple[str, str], str | None] = field(repr=False)
53
+ _children: dict[tuple[str, str], tuple[str, ...]] = field(repr=False)
54
+ _leaves: dict[tuple[str, str], tuple[str, ...]] = field(repr=False)
55
+ _counts: dict[tuple[str, str], int] = field(repr=False)
56
+ n_cells_total: int = 0
57
+
58
+ @property
59
+ def all_levels(self) -> tuple[str, ...]:
60
+ """All columns spanned, including ``leaf_level`` when it lies beyond ``levels``."""
61
+ if self.leaf_level in self.levels:
62
+ return self.levels
63
+ return (*self.levels, self.leaf_level)
64
+
65
+ def level_index(self, level: str) -> int:
66
+ """Return the position of ``level`` within :attr:`all_levels`."""
67
+ try:
68
+ return self.all_levels.index(level)
69
+ except ValueError:
70
+ raise KeyError(f"'{level}' is not a level of this hierarchy: {list(self.all_levels)}") from None
71
+
72
+ def nodes(self, level: str) -> list[str]:
73
+ """Return the labels at ``level``, in nested order."""
74
+ self.level_index(level)
75
+ return list(self._nodes[level])
76
+
77
+ def parent_of(self, level: str, node: str) -> str | None:
78
+ """Return the parent label of ``node``, or ``None`` if ``level`` is the root level."""
79
+ return self._parent[(level, node)]
80
+
81
+ def children_of(self, level: str, node: str) -> list[str]:
82
+ """Return the labels of ``node``'s children, in nested order. Empty at the finest level."""
83
+ return list(self._children.get((level, node), ()))
84
+
85
+ def leaves_of(self, level: str, node: str) -> list[str]:
86
+ """Return the ``leaf_level`` labels descending from ``node``, in nested order."""
87
+ return list(self._leaves[(level, node)])
88
+
89
+ def siblings_of(self, level: str, node: str) -> list[str]:
90
+ """Return the other labels sharing ``node``'s parent.
91
+
92
+ At the root level every other root label is a sibling, since they all share the implicit
93
+ root of the tree.
94
+ """
95
+ parent = self.parent_of(level, node)
96
+ if parent is None:
97
+ return [n for n in self._nodes[level] if n != node]
98
+ parent_level = self.all_levels[self.level_index(level) - 1]
99
+ return [n for n in self._children[(parent_level, parent)] if n != node]
100
+
101
+ def n_cells(self, level: str, node: str) -> int:
102
+ """Return the number of cells carrying ``node`` at ``level``."""
103
+ return self._counts[(level, node)]
104
+
105
+ def iter_nodes(self, *, levels: Sequence[str] | None = None):
106
+ """Yield ``(level, node)`` pairs in level-then-nested order."""
107
+ for level in levels if levels is not None else self.all_levels:
108
+ for node in self._nodes[level]:
109
+ yield level, node
110
+
111
+
112
+ def _ordered_categories(
113
+ series: pd.Series, order: Literal["size", "name", "category"], keys: Sequence[str] | None = None
114
+ ) -> list[str]:
115
+ """Order the observed labels of ``series`` by size, name, or declared categorical order.
116
+
117
+ When ``keys`` is given, labels are first ranked by the position of the first key they
118
+ contain, and ``order`` only breaks ties. That is what makes an ordering follow an axis
119
+ rather than a family: one key list orders ``Telencephalic NPC`` and ``Telencephalic Neuron``
120
+ identically, however different their cell counts are.
121
+ """
122
+ counts = series.value_counts()
123
+ counts = counts[counts > 0] # a categorical also lists its unobserved categories
124
+ if order == "size":
125
+ base = list(counts.index)
126
+ elif order == "name":
127
+ base = sorted(counts.index)
128
+ elif order == "category":
129
+ base = (
130
+ [c for c in series.cat.categories if c in set(counts.index)]
131
+ if isinstance(series.dtype, pd.CategoricalDtype)
132
+ else sorted(counts.index)
133
+ )
134
+ else:
135
+ raise ValueError(f"Unknown order '{order}', expected one of 'size', 'name', 'category'")
136
+
137
+ if not keys:
138
+ return base
139
+
140
+ def rank(label: str) -> int:
141
+ return next((i for i, key in enumerate(keys) if key in label), len(keys))
142
+
143
+ return sorted(base, key=rank) # stable, so `base` breaks ties within a key
144
+
145
+
146
+ def build_hierarchy(
147
+ adata: AnnData,
148
+ levels: Sequence[str],
149
+ *,
150
+ leaf_level: str | None = None,
151
+ root_order: Sequence[str] | None = None,
152
+ child_order: ChildOrder = "size",
153
+ level_order: Mapping[str, Sequence[str]] | None = None,
154
+ dropna: bool = True,
155
+ ) -> LabelHierarchy:
156
+ """Derive a strictly nested label hierarchy from categorical ``obs`` columns.
157
+
158
+ Parameters
159
+ ----------
160
+ adata
161
+ AnnData object whose ``obs`` holds the label columns
162
+ levels
163
+ Names of the ``obs`` columns forming the hierarchy, coarse to fine
164
+ leaf_level
165
+ Name of the ``obs`` column defining the leaves. Defaults to the last entry of ``levels``.
166
+ Pass a finer column to aggregate against leaves that are not themselves drawn as a level
167
+ root_order
168
+ Explicit ordering of the labels at ``levels[0]``. Defaults to the declared categorical
169
+ order if that column is categorical, otherwise to descending cell count
170
+ child_order
171
+ How to order the children within each parent: ``'size'`` (descending cell count),
172
+ ``'name'`` (alphabetical), or ``'category'`` (declared categorical order)
173
+ level_order
174
+ Per-level ordering keys, ``{level: [key, ...]}``, applied within *every* parent at that
175
+ level so the ordering follows an axis rather than each family's own cell counts. A label
176
+ is ranked by the position of the first key it contains, labels matching no key sort last,
177
+ and ``child_order`` breaks ties. ``root_order`` still wins at the root level when given
178
+ dropna
179
+ Whether to drop cells with a missing label in any level. If ``False``, a missing label
180
+ raises instead
181
+
182
+ Returns
183
+ -------
184
+ LabelHierarchy
185
+ The derived hierarchy.
186
+
187
+ Raises
188
+ ------
189
+ ValueError
190
+ If ``levels`` is empty, a column is missing from ``obs``, the labels are not strictly
191
+ nested, or ``dropna`` is ``False`` and labels are missing.
192
+
193
+ Examples
194
+ --------
195
+ >>> hierarchy = build_hierarchy(adata, levels=["annot_L1_v1", "annot_L2_v1", "annot_L3_v1"])
196
+ >>> hierarchy.siblings_of("annot_L2_v1", "Telencephalic NPC")
197
+ ['Non-Telen. NPC']
198
+ """
199
+ levels = list(levels)
200
+ if not levels:
201
+ raise ValueError("`levels` must name at least one obs column")
202
+
203
+ leaf_level = levels[-1] if leaf_level is None else leaf_level
204
+ if leaf_level in levels[:-1]:
205
+ raise ValueError(f"`leaf_level` {leaf_level!r} must be the finest level or a column beyond `levels`")
206
+ all_levels = levels if leaf_level in levels else [*levels, leaf_level]
207
+
208
+ missing = [c for c in all_levels if c not in adata.obs]
209
+ if missing:
210
+ raise ValueError(f"Columns not found in `adata.obs`: {missing}")
211
+
212
+ # Labels as strings, keeping a categorical's declared order for `child_order="category"`.
213
+ # `.astype(str)` turns NaN into the literal 'nan', so find the missing values beforehand.
214
+ obs = pd.DataFrame(
215
+ {
216
+ level: adata.obs[level].cat.rename_categories(str)
217
+ if isinstance(adata.obs[level].dtype, pd.CategoricalDtype)
218
+ else adata.obs[level].astype(str)
219
+ for level in all_levels
220
+ },
221
+ index=adata.obs_names,
222
+ )
223
+ # --- strict nesting: every child label must have exactly one parent ---
224
+ # Checked per pair of levels on the cells labelled at both, before any cells are dropped, so a
225
+ # violation inside a partially labelled level is still caught.
226
+ for parent_col, child_col in zip(all_levels[:-1], all_levels[1:], strict=False):
227
+ labelled = obs.loc[adata.obs[[parent_col, child_col]].notna().all(axis=1).to_numpy()]
228
+ n_parents = labelled.groupby(child_col, observed=True)[parent_col].nunique()
229
+ violations = n_parents[n_parents > 1]
230
+ if not violations.empty:
231
+ detail = ", ".join(f"{label!r} ({n} parents)" for label, n in violations.items())
232
+ raise ValueError(
233
+ f"Labels in '{child_col}' do not nest strictly within '{parent_col}': {detail}. "
234
+ "Every child label must occur under exactly one parent label."
235
+ )
236
+
237
+ na = adata.obs[all_levels].isna().any(axis=1)
238
+ if na.any():
239
+ if not dropna:
240
+ raise ValueError(f"{int(na.sum())} cells have a missing label; pass `dropna=True` to drop them")
241
+ logger.warning(
242
+ "Dropping %s cells with a missing label in %s; carry a parent label down into groups that were not "
243
+ "refined to keep them",
244
+ f"{int(na.sum()):,}",
245
+ all_levels,
246
+ )
247
+ obs = obs.loc[~na]
248
+
249
+ if obs.empty:
250
+ raise ValueError("No cells left after dropping missing labels")
251
+
252
+ counts = {level: obs[level].value_counts() for level in all_levels}
253
+
254
+ parent: dict[tuple[str, str], str | None] = {}
255
+ for parent_col, child_col in zip(all_levels[:-1], all_levels[1:], strict=False):
256
+ mapping = obs.groupby(child_col, observed=True)[parent_col].first()
257
+ for child, par in mapping.items():
258
+ parent[(child_col, child)] = par
259
+
260
+ # --- nested ordering: root order first, then children ordered within each parent ---
261
+ level_order = dict(level_order or {})
262
+ unknown_levels = [level for level in level_order if level not in all_levels]
263
+ if unknown_levels:
264
+ raise ValueError(f"`level_order` names levels not in the hierarchy: {unknown_levels}")
265
+ for level, keys in level_order.items():
266
+ unused = [k for k in keys if not any(k in label for label in obs[level].unique())]
267
+ if unused:
268
+ logger.warning("`level_order['%s']` keys match no label and are ignored: %s", level, unused)
269
+
270
+ root_level = all_levels[0]
271
+ if root_order is None:
272
+ default_order = "category" if isinstance(adata.obs[root_level].dtype, pd.CategoricalDtype) else "size"
273
+ ordered_roots = _ordered_categories(obs[root_level], default_order, level_order.get(root_level))
274
+ else:
275
+ observed = set(obs[root_level].unique())
276
+ unknown = [r for r in root_order if r not in observed]
277
+ if unknown:
278
+ raise ValueError(f"`root_order` names labels absent from '{root_level}': {unknown}")
279
+ ordered_roots = [r for r in dict.fromkeys(root_order) if r in observed]
280
+ ordered_roots += [r for r in _ordered_categories(obs[root_level], "size") if r not in set(ordered_roots)]
281
+
282
+ nodes: dict[str, list[str]] = {root_level: ordered_roots}
283
+ children: dict[tuple[str, str], tuple[str, ...]] = {}
284
+ for parent_col, child_col in zip(all_levels[:-1], all_levels[1:], strict=False):
285
+ ordered_children: list[str] = []
286
+ for par in nodes[parent_col]:
287
+ sub = obs.loc[obs[parent_col] == par, child_col]
288
+ kids = _ordered_categories(sub, child_order, level_order.get(child_col))
289
+ children[(parent_col, par)] = tuple(kids)
290
+ ordered_children.extend(kids)
291
+ nodes[child_col] = ordered_children
292
+ for node in nodes[all_levels[-1]]:
293
+ children[(all_levels[-1], node)] = ()
294
+ for node in nodes[root_level]:
295
+ parent[(root_level, node)] = None
296
+
297
+ # --- leaves per node, in the nested leaf order ---
298
+ leaf_order = tuple(nodes[leaf_level])
299
+ leaf_rank = {leaf: i for i, leaf in enumerate(leaf_order)}
300
+ leaves: dict[tuple[str, str], tuple[str, ...]] = {}
301
+ for level in all_levels:
302
+ grouped = obs.groupby(level, observed=True)[leaf_level].unique()
303
+ for node, node_leaves in grouped.items():
304
+ leaves[(level, node)] = tuple(sorted(node_leaves, key=lambda leaf: leaf_rank[leaf]))
305
+
306
+ logger.info(
307
+ "Hierarchy over %s: %s classes, %s cells",
308
+ all_levels,
309
+ [len(nodes[level]) for level in all_levels],
310
+ f"{len(obs):,}",
311
+ )
312
+
313
+ return LabelHierarchy(
314
+ levels=tuple(levels),
315
+ leaf_level=leaf_level,
316
+ leaf_order=leaf_order,
317
+ _nodes={level: tuple(nodes[level]) for level in all_levels},
318
+ _parent=parent,
319
+ _children=children,
320
+ _leaves=leaves,
321
+ _counts={(level, node): int(counts[level][node]) for level in all_levels for node in nodes[level]},
322
+ n_cells_total=int(len(obs)),
323
+ )
324
+
325
+
326
+ def hierarchy_row_positions(hierarchy: LabelHierarchy) -> dict[tuple[str, str], float]:
327
+ """Return the vertical position of every node, in leaf-row units.
328
+
329
+ Leaves sit at their index in :attr:`LabelHierarchy.leaf_order`; every internal node sits at the
330
+ mean row of its own leaves, so a node is centred on the block of rows it owns.
331
+
332
+ Parameters
333
+ ----------
334
+ hierarchy
335
+ The hierarchy to lay out
336
+
337
+ Returns
338
+ -------
339
+ dict
340
+ Mapping of ``(level, node)`` to a row position.
341
+ """
342
+ rank = {leaf: float(i) for i, leaf in enumerate(hierarchy.leaf_order)}
343
+ return {
344
+ (level, node): float(np.mean([rank[leaf] for leaf in hierarchy.leaves_of(level, node)]))
345
+ for level, node in hierarchy.iter_nodes()
346
+ }
347
+
348
+
349
+ def _detection_counts(
350
+ adata: AnnData,
351
+ leaf_labels: pd.Series,
352
+ leaf_order: Sequence[str],
353
+ genes: Sequence[str],
354
+ layer: str | None,
355
+ threshold: float | None,
356
+ ) -> tuple[np.ndarray, np.ndarray]:
357
+ """Count, per leaf and gene, how many cells detect it: nonzero, or at least ``threshold``.
358
+
359
+ Returns the ``n_leaves x n_genes`` hit counts and the per-leaf cell counts. Sparse input is
360
+ kept sparse: the full matrix is never densified.
361
+ """
362
+ matrix = adata.layers[layer] if layer is not None else adata.X
363
+ gene_idx = adata.var_names.get_indexer(genes)
364
+ if (gene_idx < 0).any():
365
+ missing = [g for g, i in zip(genes, gene_idx, strict=False) if i < 0]
366
+ raise ValueError(f"Genes not found in `adata.var_names`: {missing}")
367
+ matrix = matrix[:, gene_idx]
368
+
369
+ if threshold is not None and sp.issparse(matrix) and threshold <= 0:
370
+ raise ValueError(
371
+ f"`threshold={threshold}` on a sparse matrix would mark every zero as detected. Use a threshold above 0."
372
+ )
373
+
374
+ hits = np.zeros((len(leaf_order), len(genes)), dtype=np.int64)
375
+ n_cells = np.zeros(len(leaf_order), dtype=np.int64)
376
+ labels = leaf_labels.to_numpy()
377
+ for i, leaf in enumerate(leaf_order):
378
+ mask = labels == leaf
379
+ n_cells[i] = int(mask.sum())
380
+ if n_cells[i] == 0:
381
+ continue
382
+ detected = matrix[mask] > 0 if threshold is None else matrix[mask] >= threshold
383
+ hits[i] = np.asarray(detected.sum(axis=0)).ravel()
384
+ return hits, n_cells
385
+
386
+
387
+ def _detection_rate(hits: np.ndarray, n_cells: np.ndarray, rows: Sequence[int], how: Aggregate) -> np.ndarray:
388
+ """Aggregate per-leaf hit counts into a per-gene detection percentage."""
389
+ rows = list(rows)
390
+ if how == "pooled":
391
+ return hits[rows].sum(axis=0) / n_cells[rows].sum() * 100.0
392
+ return hits[rows] / n_cells[rows][:, None] * 100.0
393
+
394
+
395
+ def hierarchy_markers(
396
+ adata: AnnData,
397
+ levels: Sequence[str],
398
+ *,
399
+ leaf_level: str | None = None,
400
+ genes: Sequence[str] | None = None,
401
+ include_genes: Sequence[str] | None = None,
402
+ layer: str | None = None,
403
+ threshold: float | None = None,
404
+ aggregate: Aggregate = "pooled",
405
+ n_top: int = 3,
406
+ hierarchy: LabelHierarchy | None = None,
407
+ ) -> pd.DataFrame:
408
+ """Score marker genes for every node of a label hierarchy, against that node's siblings.
409
+
410
+ The score is the *detection margin*: how much more widely a gene is detected inside the node
411
+ than in its siblings. It is a fraction-of-cells statistic, so it does not depend on how many
412
+ cells a node has, which makes a 378-cell node comparable to a 336,000-cell one.
413
+
414
+ With the default ``aggregate='pooled'``, both sides pool their cells:
415
+
416
+ .. code-block:: text
417
+
418
+ det_in (node, gene) = % of the node's cells detecting the gene
419
+ det_out(node, gene) = % of all its siblings' cells detecting the gene
420
+ score = det_in - det_out
421
+
422
+ Pooling the siblings lets a small sibling be outweighed by a large one, so a gene the node
423
+ shares with one close sibling can still score well. ``aggregate='leaf_min'`` is the strict
424
+ alternative: ``det_in`` is the minimum over the node's leaves and ``det_out`` the maximum over
425
+ its siblings' leaves, so a gene only scores well if it holds for *every* child of the node and
426
+ beats *every* competitor.
427
+
428
+ Nodes without siblings are skipped: there is nothing to be specific against.
429
+
430
+ Parameters
431
+ ----------
432
+ adata
433
+ AnnData object holding the expression matrix and the label columns
434
+ levels
435
+ Names of the ``obs`` columns forming the hierarchy, coarse to fine
436
+ leaf_level
437
+ ``obs`` column defining the leaves. Defaults to the last entry of ``levels``
438
+ genes
439
+ Restrict scoring to these genes. Use this to score a curated marker panel with the same
440
+ specificity metric instead of ranking the whole matrix
441
+ include_genes
442
+ Always emit rows for these genes, in addition to the top ``n_top`` per node. Use this when
443
+ a downstream display names a gene that would not otherwise make the cut
444
+ layer
445
+ Layer to read expression from. ``None`` reads ``adata.X``
446
+ threshold
447
+ A cell detects a gene when its value is nonzero (``None``, the default, as
448
+ ``sc.get.aggregate(func="count_nonzero")`` counts it) or ``>= threshold``. Avoid a positive
449
+ threshold on log-normalized data: ``log1p(CP10k) >= 1`` counts one transcript only in cells
450
+ under ~5,800 counts, so detection would track depth. Use ``layer="counts"`` for a count threshold
451
+ aggregate
452
+ ``'pooled'`` to pool cells on both sides, ``'leaf_min'`` for the strict min/max over leaves
453
+ n_top
454
+ Number of top-scoring genes to report per node
455
+ hierarchy
456
+ A pre-built hierarchy, to avoid re-deriving it. Built from ``adata`` when omitted
457
+
458
+ Returns
459
+ -------
460
+ pd.DataFrame
461
+ Tidy frame with one row per (node, gene): ``level``, ``node``, ``gene``, ``score``,
462
+ ``det_in``, ``det_out``, ``rank``.
463
+
464
+ Examples
465
+ --------
466
+ >>> markers = hierarchy_markers(adata, levels=["annot_L1_v1", "annot_L2_v1"])
467
+ >>> markers = hierarchy_markers(adata, levels=["annot_L1_v1"], genes=["FOXG1", "PAX6", "DLX2"])
468
+ """
469
+ if aggregate not in ("leaf_min", "pooled"):
470
+ raise ValueError(f"Unknown aggregate '{aggregate}', expected 'leaf_min' or 'pooled'")
471
+
472
+ if hierarchy is None:
473
+ hierarchy = build_hierarchy(adata, levels, leaf_level=leaf_level)
474
+
475
+ gene_names = list(adata.var_names) if genes is None else list(dict.fromkeys(genes))
476
+ gene_names += [g for g in (include_genes or []) if g not in set(gene_names)]
477
+ if not gene_names:
478
+ raise ValueError("No genes to score")
479
+
480
+ leaf_order = list(hierarchy.leaf_order)
481
+ # Only the cells the hierarchy kept: a cell missing a label at any level was dropped from it.
482
+ kept = adata.obs[list(hierarchy.all_levels)].notna().all(axis=1)
483
+ leaf_labels = adata.obs[hierarchy.leaf_level].astype(str).where(kept)
484
+ hits, n_cells = _detection_counts(adata, leaf_labels, leaf_order, gene_names, layer, threshold)
485
+ leaf_pos = {leaf: i for i, leaf in enumerate(leaf_order)}
486
+
487
+ gene_array = np.asarray(gene_names)
488
+ forced = set(include_genes or [])
489
+ rows: list[dict] = []
490
+ for level, node in hierarchy.iter_nodes():
491
+ siblings = hierarchy.siblings_of(level, node)
492
+ if not siblings:
493
+ continue
494
+ in_rows = [leaf_pos[leaf] for leaf in hierarchy.leaves_of(level, node)]
495
+ out_rows = [leaf_pos[leaf] for sib in siblings for leaf in hierarchy.leaves_of(level, sib)]
496
+ if not in_rows or not out_rows:
497
+ continue
498
+
499
+ if aggregate == "leaf_min":
500
+ det_in = _detection_rate(hits, n_cells, in_rows, "leaf_min").min(axis=0)
501
+ det_out = _detection_rate(hits, n_cells, out_rows, "leaf_min").max(axis=0)
502
+ else:
503
+ det_in = _detection_rate(hits, n_cells, in_rows, "pooled")
504
+ det_out = _detection_rate(hits, n_cells, out_rows, "pooled")
505
+ score = det_in - det_out
506
+
507
+ order = np.argsort(-score, kind="stable")
508
+ keep = list(order[:n_top])
509
+ if forced:
510
+ rank_of = {int(idx): int(pos) for pos, idx in enumerate(order)}
511
+ keep += [int(i) for i in order if gene_array[i] in forced and int(i) not in set(keep)]
512
+ else:
513
+ rank_of = {int(idx): int(pos) for pos, idx in enumerate(order[:n_top])}
514
+
515
+ for idx in keep:
516
+ rows.append(
517
+ {
518
+ "level": level,
519
+ "node": node,
520
+ "gene": gene_array[idx],
521
+ "score": round(float(score[idx]), 1),
522
+ "det_in": round(float(det_in[idx]), 1),
523
+ "det_out": round(float(det_out[idx]), 1),
524
+ "rank": rank_of[int(idx)] + 1,
525
+ }
526
+ )
527
+
528
+ result = pd.DataFrame(rows, columns=["level", "node", "gene", "score", "det_in", "det_out", "rank"])
529
+ logger.info("Scored %s genes over %s nodes", f"{len(gene_names):,}", result["node"].nunique())
530
+ return result