stancounts 0.3.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.
- stancounts/__init__.py +15 -0
- stancounts/core.py +213 -0
- stancounts/counts.py +132 -0
- stancounts/detect.py +129 -0
- stancounts-0.3.0.dist-info/METADATA +207 -0
- stancounts-0.3.0.dist-info/RECORD +8 -0
- stancounts-0.3.0.dist-info/WHEEL +4 -0
- stancounts-0.3.0.dist-info/licenses/LICENSE +21 -0
stancounts/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""stancounts: Recover raw counts from log1p-normalized single-cell expression matrices."""
|
|
2
|
+
|
|
3
|
+
from stancounts.core import reverse_log1p, reverse_log1p_anndata
|
|
4
|
+
from stancounts.counts import CountsUnavailable, get_counts
|
|
5
|
+
from stancounts.detect import detect_normalization, is_log1p_normalized
|
|
6
|
+
|
|
7
|
+
__version__ = "0.3.0"
|
|
8
|
+
__all__ = [
|
|
9
|
+
"reverse_log1p",
|
|
10
|
+
"reverse_log1p_anndata",
|
|
11
|
+
"get_counts",
|
|
12
|
+
"CountsUnavailable",
|
|
13
|
+
"detect_normalization",
|
|
14
|
+
"is_log1p_normalized",
|
|
15
|
+
]
|
stancounts/core.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Core algorithm for reversing log1p normalization to recover raw counts.
|
|
2
|
+
|
|
3
|
+
Math
|
|
4
|
+
----
|
|
5
|
+
Standard single-cell normalization:
|
|
6
|
+
|
|
7
|
+
y = log1p(count / library_size * target_sum)
|
|
8
|
+
|
|
9
|
+
Reverse:
|
|
10
|
+
|
|
11
|
+
1. expm1(y) → count * (target_sum / library_size) = count * scale_factor
|
|
12
|
+
2. Per-cell min nonzero after expm1 ≈ scale_factor (assumes min count = 1)
|
|
13
|
+
3. round(expm1(y) / scale_factor) → recovered counts
|
|
14
|
+
|
|
15
|
+
The algorithm is agnostic to target_sum and works with any per-cell size
|
|
16
|
+
factor normalization (scanpy, scran, Seurat, etc.).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Literal
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import scipy.sparse as sp
|
|
25
|
+
|
|
26
|
+
# Inverse of log_base(1+x), shared with detect.py
|
|
27
|
+
INV_LOG1P = {
|
|
28
|
+
"e": np.expm1,
|
|
29
|
+
"2": lambda x: np.power(2.0, x) - 1.0,
|
|
30
|
+
"10": lambda x: np.power(10.0, x) - 1.0,
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _inv_log1p(x: np.ndarray, base: str = "e") -> np.ndarray:
|
|
35
|
+
try:
|
|
36
|
+
return INV_LOG1P[base](x)
|
|
37
|
+
except KeyError:
|
|
38
|
+
raise ValueError(f"Unsupported log base: {base!r}. Use 'e', '2', or '10'.")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _min_nonzero_per_row_sparse(csr: sp.csr_matrix) -> np.ndarray:
|
|
42
|
+
"""Vectorized min-nonzero per row of CSR. NaN for empty rows."""
|
|
43
|
+
n = csr.shape[0]
|
|
44
|
+
mins = np.full(n, np.nan)
|
|
45
|
+
data, indptr = csr.data, csr.indptr
|
|
46
|
+
if data.size == 0:
|
|
47
|
+
return mins
|
|
48
|
+
nonempty = np.diff(indptr) > 0
|
|
49
|
+
# reduceat requires all indices < len(data); substitute 0 for empty rows then mask out
|
|
50
|
+
safe_idx = np.where(nonempty, indptr[:-1], 0)
|
|
51
|
+
reduced = np.minimum.reduceat(data, safe_idx)
|
|
52
|
+
mins[nonempty] = reduced[nonempty]
|
|
53
|
+
return mins
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _detect_half_integer_rows(
|
|
57
|
+
csr: sp.csr_matrix,
|
|
58
|
+
scale_factors: np.ndarray,
|
|
59
|
+
threshold: float = 0.15,
|
|
60
|
+
min_nnz: int = 10,
|
|
61
|
+
) -> np.ndarray:
|
|
62
|
+
"""Detect rows where scale_factor should be halved (min_count was 2, not 1).
|
|
63
|
+
|
|
64
|
+
Vectorized: for every nonzero entry compute ratio / scale_factor and check
|
|
65
|
+
how close it is to a half-integer (…, 0.5, 1.5, …). Rows with a large
|
|
66
|
+
fraction of such entries have their correction set to 2.
|
|
67
|
+
"""
|
|
68
|
+
n = csr.shape[0]
|
|
69
|
+
data, indptr = csr.data, csr.indptr
|
|
70
|
+
corrections = np.ones(n, dtype=np.int32)
|
|
71
|
+
if data.size == 0:
|
|
72
|
+
return corrections
|
|
73
|
+
|
|
74
|
+
row_lengths = np.diff(indptr)
|
|
75
|
+
row_ids = np.repeat(np.arange(n), row_lengths)
|
|
76
|
+
sf = scale_factors[row_ids]
|
|
77
|
+
valid = np.isfinite(sf) & (sf > 0)
|
|
78
|
+
|
|
79
|
+
ratios = np.divide(data, sf, out=np.zeros_like(data, dtype=np.float64), where=valid)
|
|
80
|
+
devs = np.abs(ratios - np.round(ratios))
|
|
81
|
+
is_half = (np.abs(devs - 0.5) < 0.05) & valid
|
|
82
|
+
|
|
83
|
+
totals = np.bincount(row_ids, weights=valid.astype(np.float64), minlength=n)
|
|
84
|
+
halves = np.bincount(row_ids, weights=is_half.astype(np.float64), minlength=n)
|
|
85
|
+
|
|
86
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
87
|
+
frac = np.where(totals >= min_nnz, halves / np.maximum(totals, 1), 0.0)
|
|
88
|
+
corrections[frac > threshold] = 2
|
|
89
|
+
return corrections
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def reverse_log1p(
|
|
93
|
+
X,
|
|
94
|
+
*,
|
|
95
|
+
base: Literal["e", "2", "10"] = "e",
|
|
96
|
+
robust: bool = True,
|
|
97
|
+
) -> dict:
|
|
98
|
+
"""Reverse log1p normalization to recover raw counts.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
X : array-like or sparse matrix, shape (n_cells, n_genes)
|
|
103
|
+
Log1p-normalized expression matrix. Accepts dense arrays,
|
|
104
|
+
scipy sparse matrices, or anything convertible via ``np.asarray``.
|
|
105
|
+
base : ``'e'``, ``'2'``, or ``'10'``
|
|
106
|
+
Logarithm base used in the normalization.
|
|
107
|
+
robust : bool
|
|
108
|
+
If True, detect and correct for cells whose minimum nonzero count
|
|
109
|
+
is >1 (rare but possible in very deeply sequenced cells).
|
|
110
|
+
|
|
111
|
+
Returns
|
|
112
|
+
-------
|
|
113
|
+
dict with keys:
|
|
114
|
+
``counts`` : sparse CSR matrix or dense array, same shape as X
|
|
115
|
+
Recovered integer count matrix (int32).
|
|
116
|
+
``scale_factors`` : ndarray, shape (n_cells,)
|
|
117
|
+
Inferred normalization scale factor per cell
|
|
118
|
+
(= target_sum / library_size for standard normalization).
|
|
119
|
+
``library_sizes`` : ndarray, shape (n_cells,)
|
|
120
|
+
Recovered library size per cell (= row sums of counts).
|
|
121
|
+
``corrections`` : ndarray of int, shape (n_cells,)
|
|
122
|
+
Per-cell correction multiplier (1 = no correction, 2 = halved scale factor).
|
|
123
|
+
"""
|
|
124
|
+
is_sparse = sp.issparse(X)
|
|
125
|
+
|
|
126
|
+
# --- Step 1: inverse log ---
|
|
127
|
+
if is_sparse:
|
|
128
|
+
normed = X.tocsr(copy=True)
|
|
129
|
+
normed.data = _inv_log1p(normed.data.astype(np.float64), base)
|
|
130
|
+
else:
|
|
131
|
+
normed = _inv_log1p(np.asarray(X, dtype=np.float64), base)
|
|
132
|
+
|
|
133
|
+
n_cells = normed.shape[0]
|
|
134
|
+
|
|
135
|
+
# --- Step 2: min nonzero per cell = scale factor ---
|
|
136
|
+
if is_sparse:
|
|
137
|
+
scale_factors = _min_nonzero_per_row_sparse(normed)
|
|
138
|
+
else:
|
|
139
|
+
masked = np.where(normed > 0, normed, np.inf)
|
|
140
|
+
scale_factors = np.min(masked, axis=1)
|
|
141
|
+
scale_factors[np.isinf(scale_factors)] = np.nan
|
|
142
|
+
|
|
143
|
+
# --- Step 2b: robust correction for min_count > 1 ---
|
|
144
|
+
if robust:
|
|
145
|
+
csr_for_check = normed if is_sparse else sp.csr_matrix(normed)
|
|
146
|
+
corrections = _detect_half_integer_rows(csr_for_check, scale_factors)
|
|
147
|
+
scale_factors = scale_factors / corrections
|
|
148
|
+
else:
|
|
149
|
+
corrections = np.ones(n_cells, dtype=np.int32)
|
|
150
|
+
|
|
151
|
+
# --- Step 3: divide and round ---
|
|
152
|
+
if is_sparse:
|
|
153
|
+
indptr = normed.indptr
|
|
154
|
+
row_ids = np.repeat(np.arange(n_cells), np.diff(indptr))
|
|
155
|
+
sf_expanded = scale_factors[row_ids]
|
|
156
|
+
valid = np.isfinite(sf_expanded) & (sf_expanded > 0)
|
|
157
|
+
new_data = np.zeros_like(normed.data)
|
|
158
|
+
new_data[valid] = np.round(normed.data[valid] / sf_expanded[valid])
|
|
159
|
+
recovered = sp.csr_matrix((new_data.astype(np.int32), normed.indices.copy(), indptr.copy()),
|
|
160
|
+
shape=normed.shape)
|
|
161
|
+
recovered.eliminate_zeros()
|
|
162
|
+
else:
|
|
163
|
+
sf_col = scale_factors[:, np.newaxis]
|
|
164
|
+
valid = np.isfinite(sf_col) & (sf_col > 0)
|
|
165
|
+
recovered = np.where(valid, np.round(normed / np.where(valid, sf_col, 1.0)), 0).astype(np.int32)
|
|
166
|
+
|
|
167
|
+
library_sizes = np.asarray(recovered.sum(axis=1)).ravel()
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
"counts": recovered,
|
|
171
|
+
"scale_factors": scale_factors,
|
|
172
|
+
"library_sizes": library_sizes,
|
|
173
|
+
"corrections": corrections,
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def reverse_log1p_anndata(
|
|
178
|
+
adata,
|
|
179
|
+
*,
|
|
180
|
+
source: str = "X",
|
|
181
|
+
target_layer: str = "counts_recovered",
|
|
182
|
+
base: Literal["e", "2", "10"] = "e",
|
|
183
|
+
robust: bool = True,
|
|
184
|
+
):
|
|
185
|
+
"""Reverse log1p normalization and store results in an AnnData object.
|
|
186
|
+
|
|
187
|
+
Parameters
|
|
188
|
+
----------
|
|
189
|
+
adata : AnnData
|
|
190
|
+
Annotated data matrix. Modified in place.
|
|
191
|
+
source : str
|
|
192
|
+
Which slot to read. ``'X'`` reads ``adata.X``; any other string
|
|
193
|
+
reads ``adata.layers[source]``.
|
|
194
|
+
target_layer : str
|
|
195
|
+
Layer name to store the recovered counts.
|
|
196
|
+
base, robust
|
|
197
|
+
Passed to :func:`reverse_log1p`.
|
|
198
|
+
|
|
199
|
+
Returns
|
|
200
|
+
-------
|
|
201
|
+
dict
|
|
202
|
+
Same as :func:`reverse_log1p`, plus the AnnData is modified in place
|
|
203
|
+
with recovered counts in ``adata.layers[target_layer]`` and
|
|
204
|
+
scale factors in ``adata.obs['stancounts_scale_factor']``.
|
|
205
|
+
"""
|
|
206
|
+
X = adata.X if source == "X" else adata.layers[source]
|
|
207
|
+
result = reverse_log1p(X, base=base, robust=robust)
|
|
208
|
+
|
|
209
|
+
adata.layers[target_layer] = result["counts"]
|
|
210
|
+
adata.obs["stancounts_scale_factor"] = result["scale_factors"]
|
|
211
|
+
adata.obs["stancounts_library_size"] = result["library_sizes"]
|
|
212
|
+
|
|
213
|
+
return result
|
stancounts/counts.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Obtain integer counts from any AnnData: existing layer, X, .raw, or recover."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import scipy.sparse as sp
|
|
7
|
+
|
|
8
|
+
from stancounts.core import reverse_log1p
|
|
9
|
+
from stancounts.detect import detect_normalization
|
|
10
|
+
|
|
11
|
+
DEFAULT_PREFER_LAYERS = (
|
|
12
|
+
"counts", "count", "raw_counts", "counts_raw",
|
|
13
|
+
"umi", "umis", "umi_counts", "X_counts",
|
|
14
|
+
)
|
|
15
|
+
DEFAULT_EXCLUDE_LAYERS = (
|
|
16
|
+
"spliced", "unspliced", "ambiguous",
|
|
17
|
+
"spliced_counts", "unspliced_counts", "matrix",
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CountsUnavailable(ValueError):
|
|
22
|
+
"""Integer counts could not be found in layers/X/.raw nor recovered from X."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _sample_idx(n_rows: int, n_sample: int, seed: int) -> np.ndarray:
|
|
26
|
+
rng = np.random.RandomState(seed)
|
|
27
|
+
if n_rows <= n_sample:
|
|
28
|
+
return np.arange(n_rows)
|
|
29
|
+
return rng.choice(n_rows, n_sample, replace=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_integer_matrix(M, *, n_sample: int = 200, seed: int = 0) -> bool:
|
|
33
|
+
"""True if sampled nonzero values are finite, non-negative, near-integer."""
|
|
34
|
+
if M is None:
|
|
35
|
+
return False
|
|
36
|
+
idx = _sample_idx(M.shape[0], n_sample, seed)
|
|
37
|
+
if sp.issparse(M):
|
|
38
|
+
csr = M.tocsr()
|
|
39
|
+
parts = [csr.data[csr.indptr[i]:csr.indptr[i + 1]] for i in idx]
|
|
40
|
+
data = np.concatenate(parts) if parts else np.array([], dtype=float)
|
|
41
|
+
else:
|
|
42
|
+
sub = np.asarray(M[idx])
|
|
43
|
+
data = sub[sub != 0].ravel()
|
|
44
|
+
if data.size == 0:
|
|
45
|
+
return False
|
|
46
|
+
data = data.astype(np.float64)
|
|
47
|
+
if not np.all(np.isfinite(data)) or np.any(data < 0):
|
|
48
|
+
return False
|
|
49
|
+
return bool(np.allclose(data, np.round(data), rtol=0, atol=1e-6))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# Layer-name substrings hinting at log-normalized data; such layers are tried
|
|
53
|
+
# first when recovering counts from a layer (X is always tried before any layer).
|
|
54
|
+
_RECOVERY_NAME_HINTS = ("lognorm", "normalized", "data")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _recovery_candidates(adata, exclude):
|
|
58
|
+
"""Yield (source_label, matrix) to try for log1p recovery.
|
|
59
|
+
|
|
60
|
+
X first (label ``"recovered"``, preserving the historical source string), then
|
|
61
|
+
non-excluded layers whose name hints at normalized data, then the remaining
|
|
62
|
+
layers in natural order. This lets a scaled/negative X — which is neither
|
|
63
|
+
integer nor log1p — fall back to a log1p-normalized layer (e.g. ``lognorm``).
|
|
64
|
+
"""
|
|
65
|
+
yield "recovered", adata.X
|
|
66
|
+
# anndata >= 0.13 exposes X as layers[None]; X is already yielded above.
|
|
67
|
+
layers = [n for n in adata.layers if n is not None and n not in exclude]
|
|
68
|
+
hinted = [n for n in layers if any(h in n.lower() for h in _RECOVERY_NAME_HINTS)]
|
|
69
|
+
rest = [n for n in layers if n not in hinted]
|
|
70
|
+
for name in hinted + rest:
|
|
71
|
+
yield f"recovered:layer:{name}", adata.layers[name]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_counts(
|
|
75
|
+
adata,
|
|
76
|
+
*,
|
|
77
|
+
prefer_layers=DEFAULT_PREFER_LAYERS,
|
|
78
|
+
exclude_layers=DEFAULT_EXCLUDE_LAYERS,
|
|
79
|
+
base: str = "e",
|
|
80
|
+
robust: bool = True,
|
|
81
|
+
allow_recovery: bool = True,
|
|
82
|
+
n_sample: int = 200,
|
|
83
|
+
seed: int = 0,
|
|
84
|
+
) -> dict:
|
|
85
|
+
"""Return integer counts (aligned to adata.var_names) from any AnnData.
|
|
86
|
+
|
|
87
|
+
Priority: whitelist integer layer -> integer X -> integer .raw (aligned)
|
|
88
|
+
-> reverse_log1p(X) if X is log1p. Raises CountsUnavailable otherwise.
|
|
89
|
+
Velocity layers (spliced/unspliced/...) are never treated as counts.
|
|
90
|
+
|
|
91
|
+
Note: the `base` parameter is currently unused — when recovering from
|
|
92
|
+
log1p, the base is auto-detected via `detect_normalization` (``det["base"]``).
|
|
93
|
+
"""
|
|
94
|
+
exclude = set(exclude_layers)
|
|
95
|
+
|
|
96
|
+
# 1. whitelist layers, in order
|
|
97
|
+
for name in prefer_layers:
|
|
98
|
+
if name in exclude or name not in adata.layers:
|
|
99
|
+
continue
|
|
100
|
+
M = adata.layers[name]
|
|
101
|
+
if _is_integer_matrix(M, n_sample=n_sample, seed=seed):
|
|
102
|
+
return {"counts": M, "source": f"layer:{name}"}
|
|
103
|
+
|
|
104
|
+
# 2. X is integer
|
|
105
|
+
if _is_integer_matrix(adata.X, n_sample=n_sample, seed=seed):
|
|
106
|
+
return {"counts": adata.X, "source": "X"}
|
|
107
|
+
|
|
108
|
+
# 3. .raw, aligned to adata.var_names (raw must cover all genes)
|
|
109
|
+
raw = adata.raw
|
|
110
|
+
if raw is not None and _is_integer_matrix(raw.X, n_sample=n_sample, seed=seed):
|
|
111
|
+
raw_pos = {g: i for i, g in enumerate(raw.var_names)}
|
|
112
|
+
if all(g in raw_pos for g in adata.var_names):
|
|
113
|
+
cols = [raw_pos[g] for g in adata.var_names]
|
|
114
|
+
rawX = raw.X
|
|
115
|
+
aligned = rawX.tocsc()[:, cols].tocsr() if sp.issparse(rawX) else np.asarray(rawX)[:, cols]
|
|
116
|
+
return {"counts": aligned, "source": "raw"}
|
|
117
|
+
|
|
118
|
+
# 4. recover from log1p-normalized X, then from a log1p-normalized layer
|
|
119
|
+
# (so a scaled/negative X falls back to e.g. layers["lognorm"]).
|
|
120
|
+
if allow_recovery:
|
|
121
|
+
for src, M in _recovery_candidates(adata, exclude):
|
|
122
|
+
if M is None:
|
|
123
|
+
continue
|
|
124
|
+
det = detect_normalization(M, n_sample=n_sample, seed=seed)
|
|
125
|
+
if det["is_log1p"]:
|
|
126
|
+
rec = reverse_log1p(M, base=det["base"], robust=robust)
|
|
127
|
+
return {"counts": rec["counts"], "source": src, "base": det["base"]}
|
|
128
|
+
|
|
129
|
+
raise CountsUnavailable(
|
|
130
|
+
"no integer counts in whitelist layers / X / .raw, and neither X nor any "
|
|
131
|
+
"layer is log1p-recoverable"
|
|
132
|
+
)
|
stancounts/detect.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Heuristics to detect whether data is log1p-normalized and determine the log base."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import scipy.sparse as sp
|
|
7
|
+
|
|
8
|
+
from stancounts.core import INV_LOG1P
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _sample_rows(X, n: int, rng: np.random.RandomState):
|
|
12
|
+
"""Get indices of up to *n* random rows."""
|
|
13
|
+
n_rows = X.shape[0]
|
|
14
|
+
if n_rows <= n:
|
|
15
|
+
return np.arange(n_rows)
|
|
16
|
+
return rng.choice(n_rows, n, replace=False)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _row_nonzero(X, i, X_csr=None):
|
|
20
|
+
"""Return the nonzero values of row *i* as a 1-D ndarray."""
|
|
21
|
+
if X_csr is not None:
|
|
22
|
+
s, e = X_csr.indptr[i], X_csr.indptr[i + 1]
|
|
23
|
+
return X_csr.data[s:e]
|
|
24
|
+
row = np.asarray(X[i]).ravel()
|
|
25
|
+
return row[row != 0]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _integer_ratio_score(values: np.ndarray, tol: float = 0.01) -> float:
|
|
29
|
+
"""Fraction of values whose ratio to the minimum is near-integer."""
|
|
30
|
+
nz = values[values > 0]
|
|
31
|
+
if len(nz) < 5:
|
|
32
|
+
return 0.0
|
|
33
|
+
min_val = nz.min()
|
|
34
|
+
ratios = nz / min_val
|
|
35
|
+
deviations = np.abs(ratios - np.round(ratios))
|
|
36
|
+
return float((deviations < tol).sum() / len(deviations))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_integer_data(X, X_csr, idx) -> bool:
|
|
40
|
+
"""Check if the data is already integer-valued (raw counts)."""
|
|
41
|
+
for i in idx:
|
|
42
|
+
row = _row_nonzero(X, i, X_csr)
|
|
43
|
+
if len(row) > 0 and not np.allclose(row, np.round(row), atol=1e-6):
|
|
44
|
+
return False
|
|
45
|
+
return True
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def detect_normalization(
|
|
49
|
+
X,
|
|
50
|
+
*,
|
|
51
|
+
n_sample: int = 200,
|
|
52
|
+
seed: int = 0,
|
|
53
|
+
) -> dict:
|
|
54
|
+
"""Detect whether *X* is log1p-normalized and determine the log base.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
X : array-like or sparse matrix
|
|
59
|
+
Expression matrix (cells x genes).
|
|
60
|
+
n_sample : int
|
|
61
|
+
Number of cells to sample for the heuristic.
|
|
62
|
+
seed : int
|
|
63
|
+
Random seed for reproducibility.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
dict with keys:
|
|
68
|
+
``is_log1p`` : bool
|
|
69
|
+
Whether the data appears to be log1p-normalized.
|
|
70
|
+
``base`` : str or None
|
|
71
|
+
Best-guess log base (``'e'``, ``'2'``, ``'10'``) or None.
|
|
72
|
+
``scores`` : dict
|
|
73
|
+
Per-base integer-ratio scores (higher = more likely).
|
|
74
|
+
``is_integer`` : bool
|
|
75
|
+
Whether the raw data is already integer-valued.
|
|
76
|
+
``max_value`` : float
|
|
77
|
+
Maximum value in the sampled data.
|
|
78
|
+
"""
|
|
79
|
+
rng = np.random.RandomState(seed)
|
|
80
|
+
idx = _sample_rows(X, n_sample, rng)
|
|
81
|
+
|
|
82
|
+
X_csr = X.tocsr() if sp.issparse(X) else None
|
|
83
|
+
|
|
84
|
+
is_int = _is_integer_data(X, X_csr, idx)
|
|
85
|
+
|
|
86
|
+
# Sample max value and cache per-row nonzero vectors (reused across bases)
|
|
87
|
+
rows = [_row_nonzero(X, i, X_csr) for i in idx]
|
|
88
|
+
max_val = float(max((r.max() for r in rows if r.size), default=0.0))
|
|
89
|
+
|
|
90
|
+
scores = {}
|
|
91
|
+
for base_name, inv_fn in INV_LOG1P.items():
|
|
92
|
+
cell_scores = []
|
|
93
|
+
for nz in rows:
|
|
94
|
+
if len(nz) < 5:
|
|
95
|
+
continue
|
|
96
|
+
with np.errstate(over="ignore", invalid="ignore"):
|
|
97
|
+
inv = inv_fn(nz.astype(np.float64))
|
|
98
|
+
if not np.all(np.isfinite(inv)):
|
|
99
|
+
continue
|
|
100
|
+
cell_scores.append(_integer_ratio_score(inv))
|
|
101
|
+
scores[base_name] = float(np.mean(cell_scores)) if cell_scores else 0.0
|
|
102
|
+
|
|
103
|
+
best_base, best_score = max(scores.items(), key=lambda kv: kv[1])
|
|
104
|
+
|
|
105
|
+
# Decision:
|
|
106
|
+
# - Integer data with large max → raw counts
|
|
107
|
+
# - Otherwise, a best-base score above 0.7 indicates log1p
|
|
108
|
+
if is_int and max_val > 20:
|
|
109
|
+
is_log1p = False
|
|
110
|
+
detected_base = None
|
|
111
|
+
elif best_score > 0.7:
|
|
112
|
+
is_log1p = True
|
|
113
|
+
detected_base = best_base
|
|
114
|
+
else:
|
|
115
|
+
is_log1p = False
|
|
116
|
+
detected_base = None
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
"is_log1p": is_log1p,
|
|
120
|
+
"base": detected_base,
|
|
121
|
+
"scores": scores,
|
|
122
|
+
"is_integer": is_int,
|
|
123
|
+
"max_value": max_val,
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def is_log1p_normalized(X, **kwargs) -> bool:
|
|
128
|
+
"""Convenience wrapper: returns True if *X* appears log1p-normalized."""
|
|
129
|
+
return detect_normalization(X, **kwargs)["is_log1p"]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: stancounts
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Recover raw counts from log1p-normalized single-cell expression matrices
|
|
5
|
+
Project-URL: Homepage, https://github.com/chansigit/stancounts
|
|
6
|
+
Project-URL: Repository, https://github.com/chansigit/stancounts
|
|
7
|
+
Project-URL: Issues, https://github.com/chansigit/stancounts/issues
|
|
8
|
+
Author: chansigit
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: counts,log1p,normalization,scRNA-seq,single-cell
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Requires-Dist: numpy>=1.22
|
|
25
|
+
Requires-Dist: scipy>=1.7
|
|
26
|
+
Provides-Extra: anndata
|
|
27
|
+
Requires-Dist: anndata>=0.8; extra == 'anndata'
|
|
28
|
+
Provides-Extra: test
|
|
29
|
+
Requires-Dist: anndata>=0.8; extra == 'test'
|
|
30
|
+
Requires-Dist: pytest>=7.0; extra == 'test'
|
|
31
|
+
Requires-Dist: scanpy>=1.9; extra == 'test'
|
|
32
|
+
Description-Content-Type: text/markdown
|
|
33
|
+
|
|
34
|
+
<p align="center">
|
|
35
|
+
<img src="logo.svg" alt="stancounts logo" width="480">
|
|
36
|
+
</p>
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
<strong>Recover raw counts from log1p-normalized single-cell expression matrices</strong>
|
|
40
|
+
</p>
|
|
41
|
+
|
|
42
|
+
<p align="center">
|
|
43
|
+
<a href="https://www.python.org/downloads/"><img src="https://img.shields.io/badge/python-%E2%89%A53.9-blue?logo=python&logoColor=white" alt="Python 3.9+"></a>
|
|
44
|
+
<a href="https://github.com/chansigit/stancounts/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License: MIT"></a>
|
|
45
|
+
<a href="https://pypi.org/project/stancounts/"><img src="https://img.shields.io/badge/pypi-v0.1.0-orange?logo=pypi&logoColor=white" alt="PyPI"></a>
|
|
46
|
+
<a href="https://github.com/chansigit/stancounts"><img src="https://img.shields.io/badge/platform-linux%20%7C%20macOS%20%7C%20windows-lightgrey" alt="Platform"></a>
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## Why
|
|
52
|
+
|
|
53
|
+
Many single-cell tools and public datasets distribute only the **log1p-normalized** expression matrix, discarding the raw counts. Some downstream methods (e.g., RNA velocity, differential expression via negative-binomial models, scVI) *require* integer counts.
|
|
54
|
+
|
|
55
|
+
`stancounts` reverses the normalization — **exactly**, in one line — without needing to know the original `target_sum`.
|
|
56
|
+
|
|
57
|
+
## How it works
|
|
58
|
+
|
|
59
|
+
Standard scRNA-seq normalization:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
y = log1p(count / library_size × target_sum)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The key insight: in every cell, the minimum nonzero value after `expm1` corresponds to a gene with **count = 1** (near-universal in sparse scRNA-seq data). This gives us the per-cell scale factor, and division + rounding recovers exact integer counts.
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
scale_factor = min_nonzero(expm1(y)) # per cell
|
|
69
|
+
counts = round(expm1(y) / scale_factor)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
The algorithm is **target_sum agnostic** — it works with any normalization target (1e4, 1e6, median, etc.) and any per-cell size factor scheme (scanpy, scran, Seurat).
|
|
73
|
+
|
|
74
|
+
## Installation
|
|
75
|
+
|
|
76
|
+
### Python package
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
pip install git+https://github.com/chansigit/stancounts.git
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Or from source:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
git clone https://github.com/chansigit/stancounts.git
|
|
86
|
+
cd stancounts
|
|
87
|
+
pip install -e .
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### Claude Code plugin
|
|
91
|
+
|
|
92
|
+
If you use [Claude Code](https://docs.anthropic.com/en/docs/claude-code), stancounts is also available as a plugin with a built-in skill that guides Claude through the detection and recovery workflow:
|
|
93
|
+
|
|
94
|
+
```
|
|
95
|
+
/plugins add chansigit/stancounts
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Once installed, simply ask Claude to "recover counts" or "reverse log1p" and the skill activates automatically.
|
|
99
|
+
|
|
100
|
+
## Quick start
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
import stancounts
|
|
104
|
+
import scanpy as sc
|
|
105
|
+
|
|
106
|
+
adata = sc.read_h5ad("my_dataset.h5ad")
|
|
107
|
+
|
|
108
|
+
# One-liner: recover counts into a new layer
|
|
109
|
+
stancounts.reverse_log1p_anndata(adata)
|
|
110
|
+
# → adata.layers["counts_recovered"]
|
|
111
|
+
# → adata.obs["stancounts_scale_factor"]
|
|
112
|
+
# → adata.obs["stancounts_library_size"]
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Auto-detect normalization
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
det = stancounts.detect_normalization(adata.X)
|
|
119
|
+
print(det)
|
|
120
|
+
# {'is_log1p': True, 'base': 'e', 'scores': {'e': 1.0, '2': 0.32, '10': 0.31},
|
|
121
|
+
# 'is_integer': False, 'max_value': 7.26}
|
|
122
|
+
|
|
123
|
+
if det["is_log1p"]:
|
|
124
|
+
stancounts.reverse_log1p_anndata(adata, base=det["base"])
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### Low-level API
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
result = stancounts.reverse_log1p(
|
|
131
|
+
adata.X, # sparse or dense matrix
|
|
132
|
+
base="e", # "e", "2", or "10"
|
|
133
|
+
robust=True, # handle rare min_count > 1 cells
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
counts = result["counts"] # recovered count matrix
|
|
137
|
+
scale_factors = result["scale_factors"] # per-cell scale factors
|
|
138
|
+
library_sizes = result["library_sizes"] # recovered library sizes
|
|
139
|
+
corrections = result["corrections"] # robust correction flags
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## Validation
|
|
143
|
+
|
|
144
|
+
Tested on **256,000+ real cells** with ground-truth counts:
|
|
145
|
+
|
|
146
|
+
| Dataset | Cells | Genes | Recovery |
|
|
147
|
+
|---------|------:|------:|---------:|
|
|
148
|
+
| PBMC3k | 2,638 | 13,714 | **100%** |
|
|
149
|
+
| Purified PBMC | 105,753 | 19,512 | **100%** |
|
|
150
|
+
| CITE-seq PBMC | 147,582 | 20,729 | **100%** |
|
|
151
|
+
|
|
152
|
+
All three datasets: **every element, every cell, exactly recovered**.
|
|
153
|
+
|
|
154
|
+
### Robustness
|
|
155
|
+
|
|
156
|
+
| Scenario | Result |
|
|
157
|
+
|----------|--------|
|
|
158
|
+
| `target_sum` = 100, 1e3, 1e4, 1e5, 1e6 | 100% |
|
|
159
|
+
| `target_sum` = median(library_size) | 100% |
|
|
160
|
+
| scran-style arbitrary size factors | 100% |
|
|
161
|
+
| log2(1+x) and log10(1+x) | 100% |
|
|
162
|
+
| Cells with min_count > 1 (robust mode) | 100% |
|
|
163
|
+
| Deeply sequenced cells (high counts) | 100% |
|
|
164
|
+
|
|
165
|
+
## API reference
|
|
166
|
+
|
|
167
|
+
### `stancounts.reverse_log1p(X, *, base="e", robust=True)`
|
|
168
|
+
|
|
169
|
+
Reverse log1p normalization to recover raw counts.
|
|
170
|
+
|
|
171
|
+
**Parameters:**
|
|
172
|
+
- `X` — expression matrix (cells × genes), sparse or dense
|
|
173
|
+
- `base` — log base: `"e"` (default), `"2"`, or `"10"`
|
|
174
|
+
- `robust` — detect and correct cells whose minimum nonzero count > 1
|
|
175
|
+
|
|
176
|
+
**Returns** `dict` with keys: `counts`, `scale_factors`, `library_sizes`, `corrections`
|
|
177
|
+
|
|
178
|
+
### `stancounts.reverse_log1p_anndata(adata, *, source="X", target_layer="counts_recovered", base="e", robust=True)`
|
|
179
|
+
|
|
180
|
+
Convenience wrapper for AnnData objects. Stores recovered counts in `adata.layers[target_layer]` and scale factors in `adata.obs`.
|
|
181
|
+
|
|
182
|
+
### `stancounts.detect_normalization(X, *, n_sample=200, seed=0)`
|
|
183
|
+
|
|
184
|
+
Auto-detect whether data is log1p-normalized and determine the log base.
|
|
185
|
+
|
|
186
|
+
**Returns** `dict` with keys: `is_log1p`, `base`, `scores`, `is_integer`, `max_value`
|
|
187
|
+
|
|
188
|
+
### `stancounts.is_log1p_normalized(X, **kwargs)`
|
|
189
|
+
|
|
190
|
+
Convenience wrapper: returns `True` if data appears log1p-normalized.
|
|
191
|
+
|
|
192
|
+
## When it won't work
|
|
193
|
+
|
|
194
|
+
- **Batch-corrected data** (e.g., Harmony, scVI latent space) — the linear count→normalized relationship is broken
|
|
195
|
+
- **scTransform** (Pearson residuals) — not a log1p(scaled_counts) transform
|
|
196
|
+
- **Aggregated/pseudobulk** data — may still work if the aggregation preserves the structure
|
|
197
|
+
- **Fractional counts** (e.g., from imputation) — no integer counts to recover
|
|
198
|
+
|
|
199
|
+
## Dependencies
|
|
200
|
+
|
|
201
|
+
- `numpy >= 1.22`
|
|
202
|
+
- `scipy >= 1.7`
|
|
203
|
+
- `anndata >= 0.8` *(optional, for AnnData integration)*
|
|
204
|
+
|
|
205
|
+
## License
|
|
206
|
+
|
|
207
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
stancounts/__init__.py,sha256=QxWQMtqO95_YDE__pQDEIYAgEXwbs6IfI5V2AnTgtGA,475
|
|
2
|
+
stancounts/core.py,sha256=IMqW2xm53HqoxN2LFhnLCdsGsNUm8M8AU3ofQT1WocI,7342
|
|
3
|
+
stancounts/counts.py,sha256=CFRqF1CNzPQiyO-j-FeG_QfckObrhzd6CEGnTa9lvSA,5109
|
|
4
|
+
stancounts/detect.py,sha256=j5GKdOgtaNbOFKZ1i7efir2ZjsVJ23mmR3uipIaEEtg,3948
|
|
5
|
+
stancounts-0.3.0.dist-info/METADATA,sha256=4nifQxYD0AcuxjDbNySL-EoCNXEuMj0Tt-ruVXkFQik,7228
|
|
6
|
+
stancounts-0.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
7
|
+
stancounts-0.3.0.dist-info/licenses/LICENSE,sha256=KZr26TuTggVD50ltjtmSdMtsOst1tlkzI3mk6jPUbrM,1066
|
|
8
|
+
stancounts-0.3.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 chansigit
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|