scinspect 0.1.0__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.
- scinspect/__init__.py +8 -0
- scinspect/__main__.py +5 -0
- scinspect/_matrix.py +76 -0
- scinspect/advice.py +106 -0
- scinspect/checks.py +196 -0
- scinspect/classify.py +464 -0
- scinspect/cli.py +87 -0
- scinspect/core.py +142 -0
- scinspect/features.py +353 -0
- scinspect/model.py +114 -0
- scinspect/readers.py +425 -0
- scinspect/render.py +161 -0
- scinspect-0.1.0.dist-info/METADATA +214 -0
- scinspect-0.1.0.dist-info/RECORD +18 -0
- scinspect-0.1.0.dist-info/WHEEL +5 -0
- scinspect-0.1.0.dist-info/entry_points.txt +2 -0
- scinspect-0.1.0.dist-info/licenses/LICENSE +21 -0
- scinspect-0.1.0.dist-info/top_level.txt +1 -0
scinspect/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""scinspect: find out what is really inside a single-cell dataset before you analyze it."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
from .core import check # noqa: E402
|
|
6
|
+
from .model import Finding, MatrixState, Report # noqa: E402
|
|
7
|
+
|
|
8
|
+
__all__ = ["check", "Report", "MatrixState", "Finding", "__version__"]
|
scinspect/__main__.py
ADDED
scinspect/_matrix.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Helpers for pulling a small, representative sample out of any matrix-like object.
|
|
2
|
+
|
|
3
|
+
Everything downstream works on a CSR sample of cells (rows = cells, columns = features),
|
|
4
|
+
so huge files never need to be loaded in full.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import scipy.sparse as sp
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def matrix_shape(m: Any) -> tuple[int, int]:
|
|
16
|
+
shape = getattr(m, "shape", None)
|
|
17
|
+
if shape is None:
|
|
18
|
+
raise TypeError(f"object of type {type(m).__name__} has no shape")
|
|
19
|
+
return int(shape[0]), int(shape[1])
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def matrix_dtype(m: Any) -> str:
|
|
23
|
+
dt = getattr(m, "dtype", None)
|
|
24
|
+
return str(dt) if dt is not None else "unknown"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def pick_rows(n_rows: int, n_sample: int, rng: np.random.Generator) -> np.ndarray:
|
|
28
|
+
"""Sorted random row indices (sorted indices are required by h5py)."""
|
|
29
|
+
if n_rows <= n_sample:
|
|
30
|
+
return np.arange(n_rows)
|
|
31
|
+
return np.sort(rng.choice(n_rows, size=n_sample, replace=False))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def take_rows(m: Any, idx: np.ndarray) -> sp.csr_matrix:
|
|
35
|
+
"""Return rows ``idx`` of ``m`` as a float64 CSR matrix.
|
|
36
|
+
|
|
37
|
+
Works for numpy arrays, scipy sparse matrices, h5py datasets, anndata backed
|
|
38
|
+
sparse datasets and dask arrays.
|
|
39
|
+
"""
|
|
40
|
+
n_rows = matrix_shape(m)[0]
|
|
41
|
+
full = len(idx) == n_rows
|
|
42
|
+
if full and (sp.issparse(m) or isinstance(m, np.ndarray)):
|
|
43
|
+
sub = m
|
|
44
|
+
else:
|
|
45
|
+
sub = m[idx]
|
|
46
|
+
if hasattr(sub, "compute"): # dask
|
|
47
|
+
sub = sub.compute()
|
|
48
|
+
if sp.issparse(sub):
|
|
49
|
+
out = sp.csr_matrix(sub, dtype=np.float64)
|
|
50
|
+
else:
|
|
51
|
+
out = sp.csr_matrix(np.asarray(sub, dtype=np.float64))
|
|
52
|
+
out.sum_duplicates()
|
|
53
|
+
out.eliminate_zeros()
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def dense_block(sample: sp.csr_matrix, n_cols: int, rng: np.random.Generator) -> np.ndarray:
|
|
58
|
+
"""Dense sub-block (all sampled rows x up to ``n_cols`` random columns)."""
|
|
59
|
+
cols = pick_rows(sample.shape[1], n_cols, rng)
|
|
60
|
+
return np.asarray(sample[:, cols].toarray())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Transposed:
|
|
64
|
+
"""Lazy view that swaps rows and columns, e.g. for genes x cells storage."""
|
|
65
|
+
|
|
66
|
+
def __init__(self, base: Any):
|
|
67
|
+
self.base = base
|
|
68
|
+
r, c = matrix_shape(base)
|
|
69
|
+
self.shape = (c, r)
|
|
70
|
+
self.dtype = getattr(base, "dtype", None)
|
|
71
|
+
|
|
72
|
+
def __getitem__(self, idx: Any) -> Any:
|
|
73
|
+
block = self.base[:, idx]
|
|
74
|
+
if sp.issparse(block):
|
|
75
|
+
return block.T.tocsr()
|
|
76
|
+
return np.asarray(block).T
|
scinspect/advice.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Turn matrix states into concrete 'use this slot for that tool' advice."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
|
|
7
|
+
from .checks import pick_counts, pick_lognorm
|
|
8
|
+
from .model import MatrixState
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _ref(slot: str) -> str:
|
|
12
|
+
if slot == "X":
|
|
13
|
+
return "adata.X"
|
|
14
|
+
if slot == "raw.X":
|
|
15
|
+
return "adata.raw.X"
|
|
16
|
+
if slot.startswith("layers["):
|
|
17
|
+
return "adata." + slot
|
|
18
|
+
return slot
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_advice(states: Sequence[MatrixState]) -> list[dict[str, str]]:
|
|
22
|
+
counts = pick_counts(states)
|
|
23
|
+
lognorm = pick_lognorm(states)
|
|
24
|
+
scaled = next((s for s in states if s.kind == "scaled"), None)
|
|
25
|
+
x = next((s for s in states if s.slot == "X"), None)
|
|
26
|
+
raw = next((s for s in states if s.slot == "raw.X"), None)
|
|
27
|
+
advice: list[dict[str, str]] = []
|
|
28
|
+
|
|
29
|
+
def add(task: str, status: str, use: str, note: str = "") -> None:
|
|
30
|
+
advice.append({"task": task, "status": status, "use": use, "note": note})
|
|
31
|
+
|
|
32
|
+
no_counts = "no raw counts found"
|
|
33
|
+
# count-based models
|
|
34
|
+
for task in (
|
|
35
|
+
"scVI / scANVI / totalVI",
|
|
36
|
+
"Pseudobulk differential expression (DESeq2, edgeR)",
|
|
37
|
+
"Highly variable genes, flavor='seurat_v3'",
|
|
38
|
+
):
|
|
39
|
+
if counts:
|
|
40
|
+
layer_hint = ""
|
|
41
|
+
if counts.slot.startswith("layers["):
|
|
42
|
+
layer_hint = f"pass layer={counts.slot[7:-1]}"
|
|
43
|
+
elif counts.slot == "raw.X":
|
|
44
|
+
layer_hint = "copy counts out first: adata.layers['counts'] = adata.raw.X (same genes only)"
|
|
45
|
+
add(task, "ok", _ref(counts.slot), layer_hint)
|
|
46
|
+
else:
|
|
47
|
+
add(task, "blocked", no_counts, "These methods need integer counts. Get the raw counts from the data source.")
|
|
48
|
+
|
|
49
|
+
# normalization
|
|
50
|
+
if lognorm:
|
|
51
|
+
add(
|
|
52
|
+
"sc.pp.normalize_total + sc.pp.log1p",
|
|
53
|
+
"skip",
|
|
54
|
+
f"already done in {_ref(lognorm.slot)}",
|
|
55
|
+
"Running them again would log-transform twice.",
|
|
56
|
+
)
|
|
57
|
+
elif counts:
|
|
58
|
+
note = "Normalize and log before PCA and markers."
|
|
59
|
+
if counts.slot == "X":
|
|
60
|
+
note += " Save the counts first: adata.layers['counts'] = adata.X.copy()."
|
|
61
|
+
add("sc.pp.normalize_total + sc.pp.log1p", "todo", _ref(counts.slot), note)
|
|
62
|
+
|
|
63
|
+
# embeddings / clustering
|
|
64
|
+
if scaled and scaled.slot == "X":
|
|
65
|
+
add("PCA, neighbors, clustering, UMAP", "ok", _ref(scaled.slot), "Scaled data is the usual input for PCA.")
|
|
66
|
+
elif lognorm:
|
|
67
|
+
add("PCA, neighbors, clustering, UMAP", "ok", _ref(lognorm.slot))
|
|
68
|
+
elif scaled:
|
|
69
|
+
add("PCA, neighbors, clustering, UMAP", "ok", _ref(scaled.slot), "Scaled data is the usual input for PCA.")
|
|
70
|
+
elif counts:
|
|
71
|
+
add("PCA, neighbors, clustering, UMAP", "todo", "normalize counts first")
|
|
72
|
+
|
|
73
|
+
# marker genes
|
|
74
|
+
if lognorm:
|
|
75
|
+
note = ""
|
|
76
|
+
if raw is not None and raw.kind == "raw_counts" and lognorm.slot == "X":
|
|
77
|
+
note = "adata.raw holds counts, and rank_genes_groups uses adata.raw by default: pass use_raw=False."
|
|
78
|
+
add("Marker genes (sc.tl.rank_genes_groups)", "ok", _ref(lognorm.slot), note)
|
|
79
|
+
else:
|
|
80
|
+
add("Marker genes (sc.tl.rank_genes_groups)", "todo", "needs log-normalized data")
|
|
81
|
+
|
|
82
|
+
# CellTypist has a strict input contract
|
|
83
|
+
if lognorm:
|
|
84
|
+
d = lognorm.details
|
|
85
|
+
exact = d.get("log_base") == "e" and d.get("target_sum") and abs(d["target_sum"] - 1e4) < 100
|
|
86
|
+
if exact:
|
|
87
|
+
add("CellTypist annotation", "ok", _ref(lognorm.slot), "Matches its required input: ln(1+x), 10,000 per cell.")
|
|
88
|
+
else:
|
|
89
|
+
add(
|
|
90
|
+
"CellTypist annotation",
|
|
91
|
+
"todo",
|
|
92
|
+
"re-normalize",
|
|
93
|
+
"CellTypist needs ln(1+x) of counts normalized to 10,000 per cell. "
|
|
94
|
+
+ ("Rebuild from " + _ref(counts.slot) + "." if counts else "Raw counts are needed to rebuild it."),
|
|
95
|
+
)
|
|
96
|
+
elif counts:
|
|
97
|
+
add("CellTypist annotation", "todo", "normalize counts to 10,000 per cell, then log1p")
|
|
98
|
+
|
|
99
|
+
if x is not None and x.kind == "scaled":
|
|
100
|
+
add(
|
|
101
|
+
"Plotting expression (violin, dot plots)",
|
|
102
|
+
"warn",
|
|
103
|
+
_ref(lognorm.slot) if lognorm else "log-normalized data",
|
|
104
|
+
"adata.X is scaled, so plots from it show z-scores, not expression.",
|
|
105
|
+
)
|
|
106
|
+
return advice
|
scinspect/checks.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""Dataset-level checks that look across matrices."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import scipy.sparse as sp
|
|
10
|
+
|
|
11
|
+
from .classify import INVERSES
|
|
12
|
+
from .model import Finding, MatrixState
|
|
13
|
+
|
|
14
|
+
# Sizes of 10x barcode whitelists: a matrix with exactly this many cells was never cell-called.
|
|
15
|
+
WHITELIST_SIZES = {737_280: "10x v2", 6_794_880: "10x v3", 3_686_400: "10x multiome / ARC"}
|
|
16
|
+
PROCESSED_KINDS = {"log1p_normalized", "normalized_linear", "log1p_counts"}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def check_droplets(state: MatrixState, sample: sp.csr_matrix | None, n_obs: int) -> list[Finding]:
|
|
20
|
+
if state.kind != "raw_counts" or sample is None:
|
|
21
|
+
return []
|
|
22
|
+
if n_obs in WHITELIST_SIZES:
|
|
23
|
+
return [_unfiltered(state, f"{n_obs:,} barcodes is exactly the {WHITELIST_SIZES[n_obs]} whitelist size")]
|
|
24
|
+
if sample.shape[1] < 5000:
|
|
25
|
+
# Gene panels, subsets and protein matrices have naturally low totals; depth cutoffs don't apply.
|
|
26
|
+
return []
|
|
27
|
+
totals = np.asarray(sample.sum(axis=1)).ravel()
|
|
28
|
+
frac_tiny = float(np.mean(totals < 100))
|
|
29
|
+
state.details["fraction_cells_under_100_counts"] = round(frac_tiny, 4)
|
|
30
|
+
if n_obs > 50_000 and frac_tiny > 0.5:
|
|
31
|
+
return [_unfiltered(state, f"{frac_tiny:.0%} of sampled barcodes have fewer than 100 counts")]
|
|
32
|
+
if frac_tiny > 0.2:
|
|
33
|
+
return [
|
|
34
|
+
Finding(
|
|
35
|
+
"warn",
|
|
36
|
+
"cells.many_low_count",
|
|
37
|
+
f"{frac_tiny:.0%} of cells in {state.slot} have fewer than 100 counts",
|
|
38
|
+
"Low-quality cells or empty droplets may not have been removed.",
|
|
39
|
+
"Run basic QC (sc.pp.filter_cells(min_counts=...) / min_genes) before analysis.",
|
|
40
|
+
)
|
|
41
|
+
]
|
|
42
|
+
return []
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _unfiltered(state: MatrixState, why: str) -> Finding:
|
|
46
|
+
return Finding(
|
|
47
|
+
"error",
|
|
48
|
+
"cells.unfiltered_droplets",
|
|
49
|
+
f"{state.slot} looks like an UNFILTERED droplet matrix (mostly empty droplets)",
|
|
50
|
+
why,
|
|
51
|
+
"Use the filtered matrix (filtered_feature_bc_matrix) or call cells first "
|
|
52
|
+
"(EmptyDrops, CellBender, or a knee-plot cutoff).",
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def check_slot_names(states: Sequence[MatrixState]) -> list[Finding]:
|
|
57
|
+
"""Flag slots whose name promises something their contents do not deliver."""
|
|
58
|
+
out: list[Finding] = []
|
|
59
|
+
for st in states:
|
|
60
|
+
name = st.slot.lower()
|
|
61
|
+
if "count" in name and st.kind not in ("raw_counts", "fractional_counts", "empty"):
|
|
62
|
+
out.append(
|
|
63
|
+
Finding(
|
|
64
|
+
"error",
|
|
65
|
+
"slots.counts_not_counts",
|
|
66
|
+
f"{st.slot} is named like counts but contains: {st.label}",
|
|
67
|
+
advice="Tools that read this layer as counts (scVI, seurat_v3 HVG, pseudobulk DE) will be "
|
|
68
|
+
"silently wrong. Find the true raw counts.",
|
|
69
|
+
)
|
|
70
|
+
)
|
|
71
|
+
if st.slot == "raw.X" and st.kind in PROCESSED_KINDS:
|
|
72
|
+
out.append(
|
|
73
|
+
Finding(
|
|
74
|
+
"info",
|
|
75
|
+
"slots.raw_is_lognorm",
|
|
76
|
+
"adata.raw holds normalized values, not raw counts",
|
|
77
|
+
"This is the usual Scanpy habit (adata.raw = adata after log1p), but many people assume "
|
|
78
|
+
"'raw' means counts.",
|
|
79
|
+
"Do not feed adata.raw to count-based models.",
|
|
80
|
+
)
|
|
81
|
+
)
|
|
82
|
+
if st.slot == "raw.X" and st.kind == "raw_counts":
|
|
83
|
+
out.append(
|
|
84
|
+
Finding(
|
|
85
|
+
"info",
|
|
86
|
+
"slots.raw_is_counts",
|
|
87
|
+
"adata.raw holds raw counts",
|
|
88
|
+
advice="sc.tl.rank_genes_groups and some plots use adata.raw by default. Pass use_raw=False "
|
|
89
|
+
"so they run on log-normalized data.",
|
|
90
|
+
)
|
|
91
|
+
)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_derivation(
|
|
96
|
+
counts: MatrixState,
|
|
97
|
+
counts_sample: sp.csr_matrix,
|
|
98
|
+
counts_var: Sequence[str] | None,
|
|
99
|
+
proc: MatrixState,
|
|
100
|
+
proc_sample: sp.csr_matrix,
|
|
101
|
+
proc_var: Sequence[str] | None,
|
|
102
|
+
) -> Finding | None:
|
|
103
|
+
"""Is the processed matrix really computed from the counts matrix (same cells, same gene order)?"""
|
|
104
|
+
if counts_sample.shape[0] != proc_sample.shape[0]:
|
|
105
|
+
return None
|
|
106
|
+
base = proc.details.get("fingerprint") or proc.details.get("log_base") or "linear"
|
|
107
|
+
inverse = INVERSES.get(base)
|
|
108
|
+
if inverse is None:
|
|
109
|
+
return None
|
|
110
|
+
|
|
111
|
+
# align genes
|
|
112
|
+
if counts_var is not None and proc_var is not None and list(counts_var) != list(proc_var):
|
|
113
|
+
pos = {g: i for i, g in enumerate(counts_var)}
|
|
114
|
+
cols = [pos.get(g, -1) for g in proc_var]
|
|
115
|
+
matched = [c >= 0 for c in cols]
|
|
116
|
+
if sum(matched) < 0.5 * len(cols):
|
|
117
|
+
return Finding(
|
|
118
|
+
"warn",
|
|
119
|
+
"slots.gene_mismatch",
|
|
120
|
+
f"{proc.slot} and {counts.slot} share few gene names",
|
|
121
|
+
advice="They may come from different references; check before combining them.",
|
|
122
|
+
)
|
|
123
|
+
keep_proc = np.flatnonzero(matched)
|
|
124
|
+
C = counts_sample[:, [cols[i] for i in keep_proc]]
|
|
125
|
+
P = proc_sample[:, keep_proc]
|
|
126
|
+
aligned_by = "gene name"
|
|
127
|
+
elif counts_sample.shape[1] == proc_sample.shape[1]:
|
|
128
|
+
C, P = counts_sample, proc_sample
|
|
129
|
+
aligned_by = "position"
|
|
130
|
+
else:
|
|
131
|
+
return None
|
|
132
|
+
|
|
133
|
+
C = C.tocsr()
|
|
134
|
+
P = P.tocsr()
|
|
135
|
+
good = considered = 0
|
|
136
|
+
with np.errstate(over="ignore", invalid="ignore", divide="ignore"):
|
|
137
|
+
for i in range(C.shape[0]):
|
|
138
|
+
c = np.asarray(C[i].toarray()).ravel()
|
|
139
|
+
p = np.asarray(P[i].toarray()).ravel()
|
|
140
|
+
nz = (c > 0) | (p > 0)
|
|
141
|
+
if nz.sum() < 5:
|
|
142
|
+
continue
|
|
143
|
+
considered += 1
|
|
144
|
+
y = inverse(p[nz])
|
|
145
|
+
cc = c[nz]
|
|
146
|
+
if np.any((cc > 0) != (y > 1e-9)):
|
|
147
|
+
continue
|
|
148
|
+
ratio = y / cc
|
|
149
|
+
if np.std(ratio) <= 1e-3 * np.mean(ratio):
|
|
150
|
+
good += 1
|
|
151
|
+
if considered < 10:
|
|
152
|
+
return None
|
|
153
|
+
frac = good / considered
|
|
154
|
+
proc.details[f"derived_from_{counts.slot}"] = round(frac, 3)
|
|
155
|
+
if frac >= 0.9:
|
|
156
|
+
return Finding(
|
|
157
|
+
"ok",
|
|
158
|
+
"slots.derived_ok",
|
|
159
|
+
f"{proc.slot} is consistent with {counts.slot}",
|
|
160
|
+
f"{frac:.0%} of sampled cells match exactly (genes aligned by {aligned_by}).",
|
|
161
|
+
)
|
|
162
|
+
return Finding(
|
|
163
|
+
"warn",
|
|
164
|
+
"slots.derived_mismatch",
|
|
165
|
+
f"{proc.slot} does NOT match a normalization of {counts.slot}",
|
|
166
|
+
f"Only {frac:.0%} of sampled cells match (genes aligned by {aligned_by}). The counts may be from "
|
|
167
|
+
"different processing (ambient correction, different cells), or genes may be in a different order.",
|
|
168
|
+
"Do not assume these two matrices describe the same values. Check where each came from.",
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def pick_counts(states: Sequence[MatrixState]) -> MatrixState | None:
|
|
173
|
+
order = sorted(
|
|
174
|
+
(s for s in states if s.kind == "raw_counts"),
|
|
175
|
+
key=lambda s: (0 if "count" in s.slot.lower() else 1 if s.slot == "raw.X" else 2 if s.slot == "X" else 3),
|
|
176
|
+
)
|
|
177
|
+
return order[0] if order else None
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def pick_lognorm(states: Sequence[MatrixState]) -> MatrixState | None:
|
|
181
|
+
cands = [s for s in states if s.kind == "log1p_normalized"]
|
|
182
|
+
if not cands:
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
def score(s: MatrixState) -> tuple[int, int]:
|
|
186
|
+
d = s.details
|
|
187
|
+
std = d.get("log_base") == "e" and d.get("target_sum") and abs(d["target_sum"] - 1e4) < 100
|
|
188
|
+
return (0 if std else 1, 0 if s.slot == "X" else 1)
|
|
189
|
+
|
|
190
|
+
return sorted(cands, key=score)[0]
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def summarize_counts_hint(states: Sequence[MatrixState]) -> dict[str, Any]:
|
|
194
|
+
c = pick_counts(states)
|
|
195
|
+
ln = pick_lognorm(states)
|
|
196
|
+
return {"counts_slot": c.slot if c else None, "lognorm_slot": ln.slot if ln else None}
|