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,39 @@
1
+ """Routing, evidence checks, label hierarchies, reports and the hierarchy figure for cell-type annotation."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from cell_type_annotation import pl, routing
6
+ from cell_type_annotation.checks import (
7
+ cell_cycle_genes,
8
+ confidence_proxy,
9
+ negative_marker_flags,
10
+ normalization_fingerprint,
11
+ panel_gate,
12
+ qc_deviation,
13
+ validate_cl_ids,
14
+ )
15
+ from cell_type_annotation.hierarchy import LabelHierarchy, build_hierarchy, hierarchy_markers
16
+ from cell_type_annotation.markers import display_markers, read_markers
17
+ from cell_type_annotation.report import LABEL_COLUMNS, check_level, prediction_summary, render_level
18
+
19
+ __all__ = [
20
+ "LABEL_COLUMNS",
21
+ "LabelHierarchy",
22
+ "build_hierarchy",
23
+ "cell_cycle_genes",
24
+ "check_level",
25
+ "confidence_proxy",
26
+ "display_markers",
27
+ "hierarchy_markers",
28
+ "negative_marker_flags",
29
+ "normalization_fingerprint",
30
+ "panel_gate",
31
+ "pl",
32
+ "prediction_summary",
33
+ "qc_deviation",
34
+ "read_markers",
35
+ "render_level",
36
+ "routing",
37
+ "validate_cl_ids",
38
+ ]
39
+ __version__ = version("cell-type-annotation")
@@ -0,0 +1,318 @@
1
+ """Checks on the data and the evidence that no scanpy or decoupler function makes."""
2
+
3
+ import io
4
+ import re
5
+ from collections.abc import Iterable, Mapping
6
+ from importlib.resources import files
7
+
8
+ import numpy as np
9
+ import pandas as pd
10
+ import scipy.sparse as sp
11
+
12
+ #: Below this many on-panel positive markers a candidate type is uncallable on the panel: it
13
+ #: contributes to ``Unknown``, it does not score zero.
14
+ MIN_ON_PANEL_MARKERS = 2
15
+
16
+ #: A negative marker detected in more of a cluster's cells than this argues against the call.
17
+ #: Calibrated on five atlases (immune, GTEx, mouse pancreas, HypoMap, HNOCA): genuine positives
18
+ #: reach 50-68% of their type's cells, the background of a truly absent marker 10-20% in the
19
+ #: noisiest data. 0.20 flags no genuine positive and few true negatives; raise toward 0.25 for
20
+ #: continuous developmental data.
21
+ NEG_MARKER_MAX_PCT = 0.20
22
+
23
+ #: Cell Ontology (CL) and Provisional Cell Ontology (PCL) accessions.
24
+ CL_ID_PATTERN = re.compile(r"^(?:CL|PCL):\d{7}$")
25
+
26
+ #: ``(min top-1 log2FC, min markers with log2FC >= strong, suggested confidence)``, first match wins.
27
+ CONFIDENCE_BANDS = ((3.0, 5, 0.9), (2.0, 3, 0.8), (1.0, 1, 0.7), (0.5, 0, 0.6))
28
+ CONFIDENCE_BASE = 0.45
29
+
30
+
31
+ def normalization_fingerprint(X, *, n_cells: int = 2000, seed: int = 0) -> dict:
32
+ """Tell raw counts, proper log-normalization and log1p of un-normalized counts apart.
33
+
34
+ A ``max > 50`` heuristic passes the most dangerous case: ``log1p`` of counts that were never
35
+ size-normalized reads as log1p, but its markers track depth and cell size, not identity. Two
36
+ cheap probes on a sample of cells separate the cases:
37
+
38
+ - integer-valued entries mean counts; log1p output is essentially never integer;
39
+ - ``expm1(X).sum(1)`` recovers each cell's pre-log total, whose coefficient of variation is
40
+ ~0 when every cell was normalized to the same total before ``log1p``.
41
+
42
+ The CV test recognizes ``normalize_total``-style data. Size factors (scran), sctransform, or an
43
+ ``X`` subset to highly variable genes after normalization read as un-normalized: confirm those
44
+ with the user rather than stopping.
45
+
46
+ Parameters
47
+ ----------
48
+ X
49
+ Dense or sparse cells x genes matrix, as declared log-normalized.
50
+ n_cells
51
+ Cells to sample.
52
+ seed
53
+ Seed for the sample.
54
+
55
+ Returns
56
+ -------
57
+ ``{"verdict", "ok", "integer_valued", "expm1_sum_cv", "min", "max"}``. ``ok`` is true only for
58
+ size-normalized log1p data.
59
+ """
60
+ rows = np.random.default_rng(seed).choice(X.shape[0], size=min(n_cells, X.shape[0]), replace=False)
61
+ sample = X[np.sort(rows)]
62
+ if sp.issparse(sample): # stays sparse: densifying 2,000 cells x 30,000 genes costs ~0.5 GB
63
+ sample = sp.csr_matrix(sample, dtype=float)
64
+ stored = sample.data
65
+ exp = sample.copy()
66
+ exp.data = np.expm1(exp.data)
67
+ totals = np.asarray(exp.sum(axis=1)).ravel()
68
+ else:
69
+ sample = np.asarray(sample, dtype=float)
70
+ stored = sample.ravel()
71
+ totals = np.expm1(sample).sum(axis=1)
72
+ finite = bool(np.isfinite(stored).all())
73
+ nonzero = stored[(stored != 0) & np.isfinite(stored)]
74
+ xmin, xmax = (float(np.nanmin(stored)), float(np.nanmax(stored))) if stored.size else (0.0, 0.0)
75
+ if sp.issparse(sample) and sample.nnz < np.prod(sample.shape):
76
+ xmin, xmax = min(xmin, 0.0), max(xmax, 0.0)
77
+
78
+ integer_valued = bool(nonzero.size and np.allclose(nonzero, np.round(nonzero)))
79
+ totals = totals[np.isfinite(totals) & (totals > 0)]
80
+ cv = float(totals.std() / totals.mean()) if totals.size else float("nan")
81
+
82
+ if not finite:
83
+ verdict = "non-finite values (NaN or inf, e.g. genes missing from part of a joined object)"
84
+ elif xmin < 0:
85
+ verdict = "scaled (z-scored): not usable as log-normalized data"
86
+ elif integer_valued:
87
+ verdict = "raw counts (integer-valued): not log-normalized"
88
+ elif np.isfinite(cv) and cv < 0.05:
89
+ verdict = "size-normalized + log1p"
90
+ elif np.isfinite(cv):
91
+ verdict = "log1p of un-normalized counts? per-cell totals vary, so markers would track depth"
92
+ else:
93
+ verdict = "indeterminate"
94
+ return {
95
+ "verdict": verdict,
96
+ "ok": verdict == "size-normalized + log1p",
97
+ "integer_valued": integer_valued,
98
+ "expm1_sum_cv": round(cv, 4) if np.isfinite(cv) else None,
99
+ "min": round(xmin, 3),
100
+ "max": round(xmax, 3),
101
+ }
102
+
103
+
104
+ def panel_gate(
105
+ markers: pd.DataFrame, var_names: Iterable[str], *, min_on_panel: int = MIN_ON_PANEL_MARKERS
106
+ ) -> pd.DataFrame:
107
+ """Split each candidate's markers into measured and off-panel.
108
+
109
+ An off-panel gene is unmeasured, never evidence of absence. A candidate with fewer than
110
+ ``min_on_panel`` measured positive markers is uncallable on this panel.
111
+
112
+ Parameters
113
+ ----------
114
+ markers
115
+ Signed marker table as returned by :func:`~cell_type_annotation.markers.read_markers`.
116
+ var_names
117
+ The genes measured.
118
+ min_on_panel
119
+ Positive markers a candidate needs on the panel to be callable.
120
+
121
+ Returns
122
+ -------
123
+ One row per ``(level, node)``: ``n_pos``, ``n_pos_on_panel``, ``uncallable``, ``off_panel_pos``,
124
+ ``off_panel_neg`` (semicolon-joined).
125
+ """
126
+ present = set(map(str, var_names))
127
+ rows = []
128
+ for (level, node), group in markers.groupby(["level", "node"], sort=False):
129
+ pos = group.loc[group["sign"] == "pos", "gene"]
130
+ neg = group.loc[group["sign"] == "neg", "gene"]
131
+ n_on = int(pos.isin(present).sum())
132
+ rows.append(
133
+ {
134
+ "level": level,
135
+ "node": node,
136
+ "n_pos": len(pos),
137
+ "n_pos_on_panel": n_on,
138
+ "uncallable": n_on < min_on_panel,
139
+ "off_panel_pos": ";".join(pos[~pos.isin(present)]),
140
+ "off_panel_neg": ";".join(neg[~neg.isin(present)]),
141
+ }
142
+ )
143
+ columns = ["level", "node", "n_pos", "n_pos_on_panel", "uncallable", "off_panel_pos", "off_panel_neg"]
144
+ return pd.DataFrame(rows, columns=columns)
145
+
146
+
147
+ def negative_marker_flags(
148
+ pct: pd.DataFrame, markers: pd.DataFrame, *, max_pct: float = NEG_MARKER_MAX_PCT
149
+ ) -> pd.DataFrame:
150
+ """Flag clusters that express a candidate's negative markers.
151
+
152
+ A gene is routinely a positive marker of one type and a negative marker of another, so the
153
+ check runs per ``(candidate, gene)`` pair. Off-panel negatives are skipped: unmeasured is not
154
+ confirmed absent.
155
+
156
+ Parameters
157
+ ----------
158
+ pct
159
+ Fraction of cells detecting each gene, clusters x genes, e.g. from
160
+ ``sc.get.aggregate(adata, by=cluster_key, func="count_nonzero")`` divided by cluster sizes.
161
+ markers
162
+ Signed marker table.
163
+ max_pct
164
+ Detection above which a negative marker counts as expressed.
165
+
166
+ Returns
167
+ -------
168
+ One row per ``(cluster, level, node, gene)``: ``pct`` and ``violation``. ``level`` keeps a
169
+ label reused at two levels apart.
170
+ """
171
+ negatives = markers.loc[(markers["sign"] == "neg") & markers["gene"].isin(pct.columns), ["level", "node", "gene"]]
172
+ if pct[negatives["gene"].unique()].isna().any().any():
173
+ raise ValueError("`pct` has missing detection values: every NaN would read as 'not expressed'")
174
+ rows = [
175
+ {
176
+ "cluster": str(cluster),
177
+ "level": level,
178
+ "node": node,
179
+ "gene": gene,
180
+ "pct": round(float(pct.at[cluster, gene]), 4),
181
+ "violation": bool(pct.at[cluster, gene] > max_pct),
182
+ }
183
+ for cluster in pct.index
184
+ for level, node, gene in negatives.itertuples(index=False)
185
+ ]
186
+ return pd.DataFrame(rows, columns=["cluster", "level", "node", "gene", "pct", "violation"])
187
+
188
+
189
+ def validate_cl_ids(cl_ids: Mapping[str, object] | pd.Series) -> list[str]:
190
+ """Check ontology ids for syntax: ``CL:0000000`` or ``PCL:0000000``; blanks are allowed.
191
+
192
+ Syntax only. Whether the term exists, is current and matches its label is checked through the
193
+ knowledgebase MCP (``bc_get_term_details``).
194
+
195
+ Parameters
196
+ ----------
197
+ cl_ids
198
+ Ontology id per cluster.
199
+
200
+ Returns
201
+ -------
202
+ One message per malformed id.
203
+ """
204
+ problems = []
205
+ for cluster, value in dict(cl_ids).items():
206
+ cl_id = "" if pd.isna(value) else str(value).strip()
207
+ if cl_id and not CL_ID_PATTERN.match(cl_id):
208
+ problems.append(f"cluster {cluster!r}: cl_id {cl_id!r} is not of the form CL:0000000 or PCL:0000000")
209
+ return problems
210
+
211
+
212
+ def qc_deviation(medians: pd.DataFrame) -> pd.DataFrame:
213
+ """Robust z of each cluster's QC medians against the spread across clusters.
214
+
215
+ ``(median - median over clusters) / (1.4826 * MAD)``, per column, so a cluster that is off
216
+ the population on depth, mitochondrial fraction or a cell-cycle score stands out whatever the
217
+ metric. Where most clusters share one value the MAD is 0, and the scale falls back to
218
+ ``1.2533 * mean absolute deviation`` so a lone outlier still shows. Columns without any spread
219
+ give 0; a missing median stays missing. Meaningful from three clusters on.
220
+
221
+ Parameters
222
+ ----------
223
+ medians
224
+ Clusters x numeric QC metrics, e.g. ``obs.groupby(cluster_key)[metrics].median()``.
225
+
226
+ Returns
227
+ -------
228
+ Clusters x metrics robust z, rounded to 2 decimals.
229
+ """
230
+ center = medians.median()
231
+ deviation = (medians - center).abs()
232
+ scale = (deviation.median() * 1.4826).where(lambda s: s > 0, deviation.mean() * 1.2533)
233
+ spread = scale > 0
234
+ z = (medians - center).divide(scale.where(spread))
235
+ z.loc[:, ~spread] = 0.0
236
+ return z.mask(medians.isna()).round(2) # missing evidence stays missing, never "normal"
237
+
238
+
239
+ def confidence_proxy(
240
+ filtered_markers: pd.DataFrame,
241
+ clusters: Iterable[str],
242
+ *,
243
+ agree: Mapping[str, float] | None = None,
244
+ strong: float = 1.0,
245
+ ) -> pd.DataFrame:
246
+ """A per-cluster confidence band from marker specificity, to calibrate hand-set confidences.
247
+
248
+ Advisory: a high confidence on a cluster with weak markers is the thing to re-examine.
249
+
250
+ Parameters
251
+ ----------
252
+ filtered_markers
253
+ Markers surviving ``sc.tl.filter_rank_genes_groups``, e.g. from
254
+ ``sc.get.rank_genes_groups_df(adata, group=None, key="rank_genes_groups_filtered")``, with
255
+ columns ``group`` (or ``cluster``) and ``logfoldchanges``.
256
+ clusters
257
+ All clusters, so a cluster without a surviving marker gets the lowest band rather than no row.
258
+ agree
259
+ Optional number of cross-check methods agreeing per cluster; each above one adds 0.05.
260
+ strong
261
+ log2 fold-change at which a marker counts as strong.
262
+
263
+ Returns
264
+ -------
265
+ One row per cluster: ``lfc_top1``, ``lfc_margin``, ``n_strong``, ``suggested_conf``.
266
+ """
267
+ agree = {str(k): v for k, v in dict(agree if agree is not None else {}).items()}
268
+ key = "group" if "group" in filtered_markers.columns else "cluster"
269
+ # filter_rank_genes_groups blanks the names of rejected genes rather than dropping their rows
270
+ kept = filtered_markers.dropna(subset=["names"]) if "names" in filtered_markers.columns else filtered_markers
271
+ lfc_by_cluster = {
272
+ str(cluster): sorted(pd.to_numeric(g["logfoldchanges"], errors="coerce").dropna(), reverse=True)
273
+ for cluster, g in kept.groupby(key, observed=True)
274
+ }
275
+ rows = []
276
+ for cluster in map(str, clusters):
277
+ lfc = lfc_by_cluster.get(cluster, [])
278
+ top1 = lfc[0] if lfc else 0.0
279
+ top2 = lfc[1] if len(lfc) > 1 else 0.0
280
+ n_strong = sum(v >= strong for v in lfc)
281
+ conf = next((c for t, n, c in CONFIDENCE_BANDS if lfc and top1 >= t and n_strong >= n), CONFIDENCE_BASE)
282
+ if pd.notna(agree.get(cluster)):
283
+ conf = min(0.95, conf + 0.05 * (agree[cluster] - 1))
284
+ rows.append(
285
+ {
286
+ "cluster": cluster,
287
+ "lfc_top1": round(top1, 3),
288
+ "lfc_margin": round(top1 - top2, 3),
289
+ "n_strong": n_strong,
290
+ "suggested_conf": round(conf, 2),
291
+ }
292
+ )
293
+ return pd.DataFrame(rows)
294
+
295
+
296
+ def cell_cycle_genes(var_names: Iterable[str] | None = None) -> tuple[list[str], list[str]]:
297
+ """The Tirosh et al. (2016) S and G2/M gene lists, for ``sc.tl.score_genes_cell_cycle``.
298
+
299
+ Human symbols, matched case-insensitively so the same lists resolve mouse genes. A few legacy
300
+ symbols (MLF1IP, FAM64A, HN1) go unmatched on objects using their current names.
301
+
302
+ Parameters
303
+ ----------
304
+ var_names
305
+ If given, return only the genes present, spelled as in ``var_names``.
306
+
307
+ Returns
308
+ -------
309
+ ``(s_genes, g2m_genes)``.
310
+ """
311
+ phases = pd.read_csv(
312
+ io.StringIO(files("cell_type_annotation").joinpath("data/cell_cycle_tirosh.tsv").read_text()), sep="\t"
313
+ )
314
+ s, g2m = (phases.loc[phases["phase"] == p, "gene"].tolist() for p in ("S", "G2M"))
315
+ if var_names is None:
316
+ return s, g2m
317
+ lookup = {str(v).upper(): str(v) for v in var_names}
318
+ return [lookup[g] for g in s if g in lookup], [lookup[g] for g in g2m if g in lookup]
@@ -0,0 +1,98 @@
1
+ gene phase
2
+ MCM5 S
3
+ PCNA S
4
+ TYMS S
5
+ FEN1 S
6
+ MCM2 S
7
+ MCM4 S
8
+ RRM1 S
9
+ UNG S
10
+ GINS2 S
11
+ MCM6 S
12
+ CDCA7 S
13
+ DTL S
14
+ PRIM1 S
15
+ UHRF1 S
16
+ MLF1IP S
17
+ HELLS S
18
+ RFC2 S
19
+ RPA2 S
20
+ NASP S
21
+ RAD51AP1 S
22
+ GMNN S
23
+ WDR76 S
24
+ SLBP S
25
+ CCNE2 S
26
+ UBR7 S
27
+ POLD3 S
28
+ MSH2 S
29
+ ATAD2 S
30
+ RAD51 S
31
+ RRM2 S
32
+ CDC45 S
33
+ CDC6 S
34
+ EXO1 S
35
+ TIPIN S
36
+ DSCC1 S
37
+ BLM S
38
+ CASP8AP2 S
39
+ USP1 S
40
+ CLSPN S
41
+ POLA1 S
42
+ CHAF1B S
43
+ BRIP1 S
44
+ E2F8 S
45
+ HMGB2 G2M
46
+ CDK1 G2M
47
+ NUSAP1 G2M
48
+ UBE2C G2M
49
+ BIRC5 G2M
50
+ TPX2 G2M
51
+ TOP2A G2M
52
+ NDC80 G2M
53
+ CKS2 G2M
54
+ NUF2 G2M
55
+ CKS1B G2M
56
+ MKI67 G2M
57
+ TMPO G2M
58
+ CENPF G2M
59
+ TACC3 G2M
60
+ FAM64A G2M
61
+ SMC4 G2M
62
+ CCNB2 G2M
63
+ CKAP2L G2M
64
+ CKAP2 G2M
65
+ AURKB G2M
66
+ BUB1 G2M
67
+ KIF11 G2M
68
+ ANP32E G2M
69
+ TUBB4B G2M
70
+ GTSE1 G2M
71
+ KIF20B G2M
72
+ HJURP G2M
73
+ CDCA3 G2M
74
+ HN1 G2M
75
+ CDC20 G2M
76
+ TTK G2M
77
+ CDC25C G2M
78
+ KIF2C G2M
79
+ RANGAP1 G2M
80
+ NCAPD2 G2M
81
+ DLGAP5 G2M
82
+ CDCA2 G2M
83
+ CDCA8 G2M
84
+ ECT2 G2M
85
+ KIF23 G2M
86
+ HMMR G2M
87
+ AURKA G2M
88
+ PSRC1 G2M
89
+ ANLN G2M
90
+ LBR G2M
91
+ CKAP5 G2M
92
+ CENPE G2M
93
+ CTCF G2M
94
+ NEK2 G2M
95
+ G2E3 G2M
96
+ GAS2L3 G2M
97
+ CBX5 G2M
98
+ CENPA G2M