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.
- cell_type_annotation/__init__.py +39 -0
- cell_type_annotation/checks.py +318 -0
- cell_type_annotation/data/cell_cycle_tirosh.tsv +98 -0
- cell_type_annotation/hierarchy.py +530 -0
- cell_type_annotation/markers.py +164 -0
- cell_type_annotation/pl.py +869 -0
- cell_type_annotation/report.py +239 -0
- cell_type_annotation/routing.py +371 -0
- cell_type_annotation-0.4.2.dist-info/METADATA +105 -0
- cell_type_annotation-0.4.2.dist-info/RECORD +12 -0
- cell_type_annotation-0.4.2.dist-info/WHEEL +4 -0
- cell_type_annotation-0.4.2.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""The signed, sourced marker table, and the rule for which markers a figure shows.
|
|
2
|
+
|
|
3
|
+
One table, ``results/markers.csv``, holds every curated marker of the run: one row per
|
|
4
|
+
``(level, node, gene)`` with its ``sign`` (``pos``, or ``neg`` for a gene whose presence argues
|
|
5
|
+
against the type) and its ``source`` and ``pmid``. The assumptions ledger signs it off level by
|
|
6
|
+
level, and it is the whitelist from which :func:`display_markers` picks what a figure shows.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterable, Mapping
|
|
10
|
+
from os import PathLike
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from cell_type_annotation.hierarchy import LabelHierarchy
|
|
16
|
+
|
|
17
|
+
MARKER_COLUMNS = ("level", "node", "gene", "sign", "source", "pmid", "note")
|
|
18
|
+
REQUIRED_COLUMNS = ("level", "node", "gene", "sign")
|
|
19
|
+
|
|
20
|
+
#: Labels that mean "no identity", drawn with the ∅ flag rather than given markers.
|
|
21
|
+
UNKNOWN_LABELS = frozenset({"unknown", "unassigned"})
|
|
22
|
+
|
|
23
|
+
#: What each flag symbol means, for the figure's key.
|
|
24
|
+
FLAGS = {
|
|
25
|
+
"†": "canonical markers off-panel",
|
|
26
|
+
"−": "no canonical marker separates it from its siblings",
|
|
27
|
+
"∅": "unassigned",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def read_markers(source: str | PathLike | pd.DataFrame) -> pd.DataFrame:
|
|
32
|
+
"""Read and validate the signed marker table.
|
|
33
|
+
|
|
34
|
+
Parameters
|
|
35
|
+
----------
|
|
36
|
+
source
|
|
37
|
+
Path to the CSV, or the frame itself.
|
|
38
|
+
|
|
39
|
+
Returns
|
|
40
|
+
-------
|
|
41
|
+
The table with all of :data:`MARKER_COLUMNS` (missing optional ones filled with ``""``),
|
|
42
|
+
``sign`` lower-cased, plus any extra columns.
|
|
43
|
+
|
|
44
|
+
Raises
|
|
45
|
+
------
|
|
46
|
+
ValueError
|
|
47
|
+
If a required column is missing, a sign is not ``pos``/``neg``, or a gene appears more
|
|
48
|
+
than once for the same node.
|
|
49
|
+
"""
|
|
50
|
+
df = source.copy() if isinstance(source, pd.DataFrame) else pd.read_csv(source, dtype=str, keep_default_na=False)
|
|
51
|
+
missing = [c for c in REQUIRED_COLUMNS if c not in df.columns]
|
|
52
|
+
if missing:
|
|
53
|
+
raise ValueError(f"Marker table is missing columns {missing}; expected {list(MARKER_COLUMNS)}")
|
|
54
|
+
for column in MARKER_COLUMNS:
|
|
55
|
+
df[column] = df[column].fillna("").astype(str).str.strip() if column in df.columns else ""
|
|
56
|
+
df["sign"] = df["sign"].str.lower()
|
|
57
|
+
bad = sorted(set(df["sign"]) - {"pos", "neg"})
|
|
58
|
+
if bad:
|
|
59
|
+
raise ValueError(f"`sign` must be 'pos' or 'neg', got {bad}")
|
|
60
|
+
repeated = df[df.duplicated(["level", "node", "gene"], keep=False)]
|
|
61
|
+
if not repeated.empty:
|
|
62
|
+
keys = sorted(set(map(tuple, repeated[["level", "node", "gene"]].to_numpy())))
|
|
63
|
+
raise ValueError(
|
|
64
|
+
f"Genes listed more than once for one node, or with both signs: {keys}. "
|
|
65
|
+
"List each gene once per node and join several sources with ';'."
|
|
66
|
+
)
|
|
67
|
+
return df[[*MARKER_COLUMNS, *(c for c in df.columns if c not in MARKER_COLUMNS)]]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _is_unknown(label: str) -> bool:
|
|
71
|
+
return label.strip().lower() in UNKNOWN_LABELS or label.strip().lower().startswith("unknown")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def display_markers(
|
|
75
|
+
scores: pd.DataFrame,
|
|
76
|
+
hierarchy: LabelHierarchy,
|
|
77
|
+
markers: pd.DataFrame,
|
|
78
|
+
var_names: Iterable[str],
|
|
79
|
+
*,
|
|
80
|
+
level_keys: Mapping[str, str] | None = None,
|
|
81
|
+
min_margin: float = 10.0,
|
|
82
|
+
n: int = 2,
|
|
83
|
+
) -> tuple[pd.DataFrame, pd.DataFrame]:
|
|
84
|
+
"""Pick the canonical markers a hierarchy figure shows, and flag the nodes that have none.
|
|
85
|
+
|
|
86
|
+
A node shows a gene when it is one of the node's curated positive markers, its detection
|
|
87
|
+
margin over the pooled siblings is at least ``min_margin`` points, and no single sibling
|
|
88
|
+
detects it more widely. The best ``n`` by margin are shown. A node where none passes is
|
|
89
|
+
flagged, never given a data-driven substitute:
|
|
90
|
+
|
|
91
|
+
- ``∅``: an unknown or unassigned node;
|
|
92
|
+
- ``†``: its canonical markers are all off the panel;
|
|
93
|
+
- ``−``: no measured canonical marker separates it from its siblings (or none was curated).
|
|
94
|
+
|
|
95
|
+
A ``−`` flag on a confident call is evidence for the critics: the markers the call was signed
|
|
96
|
+
off on do not separate it from its siblings in this data.
|
|
97
|
+
|
|
98
|
+
Parameters
|
|
99
|
+
----------
|
|
100
|
+
scores
|
|
101
|
+
:func:`~cell_type_annotation.hierarchy.hierarchy_markers` output, run with
|
|
102
|
+
``include_genes`` set to every measured positive marker, so each one has a row on every node.
|
|
103
|
+
hierarchy
|
|
104
|
+
The hierarchy the scores were computed on.
|
|
105
|
+
markers
|
|
106
|
+
Signed marker table (:func:`read_markers`).
|
|
107
|
+
var_names
|
|
108
|
+
The genes measured.
|
|
109
|
+
level_keys
|
|
110
|
+
Maps the table's ``level`` values to the hierarchy's ``obs`` columns, e.g.
|
|
111
|
+
``{"L1": "annot_L1_v1"}``. Defaults to identity.
|
|
112
|
+
min_margin
|
|
113
|
+
Minimum ``det_in - det_out``, in percentage points.
|
|
114
|
+
n
|
|
115
|
+
Markers shown per node.
|
|
116
|
+
|
|
117
|
+
Returns
|
|
118
|
+
-------
|
|
119
|
+
``(shown, flags)``. ``shown`` has one row per displayed gene (``level, node, gene, score,
|
|
120
|
+
det_in, det_out, det_best_sibling, rank, source, pmid``) and is what
|
|
121
|
+
:func:`~cell_type_annotation.pl.annotation_hierarchy` takes as ``markers``. ``flags`` has one
|
|
122
|
+
row per flagged node: ``level, node, symbol, reason``.
|
|
123
|
+
"""
|
|
124
|
+
level_keys = dict(level_keys or {})
|
|
125
|
+
present = set(map(str, var_names))
|
|
126
|
+
positives = markers[markers["sign"] == "pos"].assign(level=lambda d: d["level"].map(lambda v: level_keys.get(v, v)))
|
|
127
|
+
det_in = scores.set_index(["level", "node", "gene"])["det_in"]
|
|
128
|
+
|
|
129
|
+
shown, flags = [], []
|
|
130
|
+
for level, node in hierarchy.iter_nodes(levels=hierarchy.levels):
|
|
131
|
+
if _is_unknown(node): # before the sibling test: an Unknown is often an only child
|
|
132
|
+
flags.append((level, node, "∅", "unassigned"))
|
|
133
|
+
continue
|
|
134
|
+
siblings = hierarchy.siblings_of(level, node)
|
|
135
|
+
if not siblings:
|
|
136
|
+
continue
|
|
137
|
+
canonical = positives[(positives["level"] == level) & (positives["node"] == node)]
|
|
138
|
+
measured = canonical[canonical["gene"].isin(present)]
|
|
139
|
+
if canonical.empty:
|
|
140
|
+
flags.append((level, node, "−", "no canonical marker curated"))
|
|
141
|
+
continue
|
|
142
|
+
if measured.empty:
|
|
143
|
+
flags.append((level, node, "†", f"off-panel: {', '.join(canonical['gene'])}"))
|
|
144
|
+
continue
|
|
145
|
+
|
|
146
|
+
candidates = []
|
|
147
|
+
for gene, source, pmid in measured[["gene", "source", "pmid"]].itertuples(index=False):
|
|
148
|
+
hit = scores[(scores["level"] == level) & (scores["node"] == node) & (scores["gene"] == gene)]
|
|
149
|
+
if hit.empty:
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"No score for {gene!r} on {level} / {node}; pass it to hierarchy_markers' include_genes"
|
|
152
|
+
)
|
|
153
|
+
best_sibling = max(det_in.get((level, s, gene), np.nan) for s in siblings)
|
|
154
|
+
row = hit.iloc[0]
|
|
155
|
+
if row["score"] >= min_margin and row["det_in"] > best_sibling:
|
|
156
|
+
candidates.append((row["score"], gene, row["det_in"], row["det_out"], best_sibling, source, pmid))
|
|
157
|
+
if not candidates:
|
|
158
|
+
flags.append((level, node, "−", f"measured but not separating: {', '.join(measured['gene'])}"))
|
|
159
|
+
continue
|
|
160
|
+
for rank, (score, gene, d_in, d_out, best, source, pmid) in enumerate(sorted(candidates, reverse=True)[:n], 1):
|
|
161
|
+
shown.append((level, node, gene, score, d_in, d_out, best, rank, source, pmid))
|
|
162
|
+
|
|
163
|
+
shown_cols = ["level", "node", "gene", "score", "det_in", "det_out", "det_best_sibling", "rank", "source", "pmid"]
|
|
164
|
+
return pd.DataFrame(shown, columns=shown_cols), pd.DataFrame(flags, columns=["level", "node", "symbol", "reason"])
|