stancounts 0.3.0__tar.gz
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-0.3.0/.claude-plugin/plugin.json +20 -0
- stancounts-0.3.0/.gitignore +8 -0
- stancounts-0.3.0/LICENSE +21 -0
- stancounts-0.3.0/PKG-INFO +207 -0
- stancounts-0.3.0/README.md +174 -0
- stancounts-0.3.0/hooks/hooks.json +15 -0
- stancounts-0.3.0/hooks/post_stancounts_success.py +165 -0
- stancounts-0.3.0/logo.svg +57 -0
- stancounts-0.3.0/pyproject.toml +53 -0
- stancounts-0.3.0/scripts/exploration/explore_larger.py +163 -0
- stancounts-0.3.0/scripts/exploration/explore_logbase_and_fix.py +280 -0
- stancounts-0.3.0/scripts/exploration/explore_reverse_log1p.py +171 -0
- stancounts-0.3.0/scripts/exploration/explore_robustness.py +249 -0
- stancounts-0.3.0/scripts/exploration/test_chondro.py +119 -0
- stancounts-0.3.0/skills/stancounts/SKILL.md +119 -0
- stancounts-0.3.0/src/stancounts/__init__.py +15 -0
- stancounts-0.3.0/src/stancounts/core.py +213 -0
- stancounts-0.3.0/src/stancounts/counts.py +132 -0
- stancounts-0.3.0/src/stancounts/detect.py +129 -0
- stancounts-0.3.0/tests/conftest.py +34 -0
- stancounts-0.3.0/tests/test_core.py +213 -0
- stancounts-0.3.0/tests/test_counts.py +130 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "stancounts",
|
|
3
|
+
"displayName": "stancounts",
|
|
4
|
+
"description": "Recover raw counts from log1p-normalized single-cell expression matrices",
|
|
5
|
+
"version": "0.1.0",
|
|
6
|
+
"author": {
|
|
7
|
+
"name": "chansigit"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://github.com/chansigit/stancounts",
|
|
10
|
+
"repository": "https://github.com/chansigit/stancounts",
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"single-cell",
|
|
14
|
+
"scRNA-seq",
|
|
15
|
+
"normalization",
|
|
16
|
+
"counts",
|
|
17
|
+
"log1p",
|
|
18
|
+
"bioinformatics"
|
|
19
|
+
]
|
|
20
|
+
}
|
stancounts-0.3.0/LICENSE
ADDED
|
@@ -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.
|
|
@@ -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,174 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="logo.svg" alt="stancounts logo" width="480">
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<p align="center">
|
|
6
|
+
<strong>Recover raw counts from log1p-normalized single-cell expression matrices</strong>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<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>
|
|
11
|
+
<a href="https://github.com/chansigit/stancounts/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-green" alt="License: MIT"></a>
|
|
12
|
+
<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>
|
|
13
|
+
<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>
|
|
14
|
+
</p>
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Why
|
|
19
|
+
|
|
20
|
+
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.
|
|
21
|
+
|
|
22
|
+
`stancounts` reverses the normalization — **exactly**, in one line — without needing to know the original `target_sum`.
|
|
23
|
+
|
|
24
|
+
## How it works
|
|
25
|
+
|
|
26
|
+
Standard scRNA-seq normalization:
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
y = log1p(count / library_size × target_sum)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
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.
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
scale_factor = min_nonzero(expm1(y)) # per cell
|
|
36
|
+
counts = round(expm1(y) / scale_factor)
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
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).
|
|
40
|
+
|
|
41
|
+
## Installation
|
|
42
|
+
|
|
43
|
+
### Python package
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install git+https://github.com/chansigit/stancounts.git
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Or from source:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
git clone https://github.com/chansigit/stancounts.git
|
|
53
|
+
cd stancounts
|
|
54
|
+
pip install -e .
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Claude Code plugin
|
|
58
|
+
|
|
59
|
+
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:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
/plugins add chansigit/stancounts
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Once installed, simply ask Claude to "recover counts" or "reverse log1p" and the skill activates automatically.
|
|
66
|
+
|
|
67
|
+
## Quick start
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import stancounts
|
|
71
|
+
import scanpy as sc
|
|
72
|
+
|
|
73
|
+
adata = sc.read_h5ad("my_dataset.h5ad")
|
|
74
|
+
|
|
75
|
+
# One-liner: recover counts into a new layer
|
|
76
|
+
stancounts.reverse_log1p_anndata(adata)
|
|
77
|
+
# → adata.layers["counts_recovered"]
|
|
78
|
+
# → adata.obs["stancounts_scale_factor"]
|
|
79
|
+
# → adata.obs["stancounts_library_size"]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Auto-detect normalization
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
det = stancounts.detect_normalization(adata.X)
|
|
86
|
+
print(det)
|
|
87
|
+
# {'is_log1p': True, 'base': 'e', 'scores': {'e': 1.0, '2': 0.32, '10': 0.31},
|
|
88
|
+
# 'is_integer': False, 'max_value': 7.26}
|
|
89
|
+
|
|
90
|
+
if det["is_log1p"]:
|
|
91
|
+
stancounts.reverse_log1p_anndata(adata, base=det["base"])
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Low-level API
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
result = stancounts.reverse_log1p(
|
|
98
|
+
adata.X, # sparse or dense matrix
|
|
99
|
+
base="e", # "e", "2", or "10"
|
|
100
|
+
robust=True, # handle rare min_count > 1 cells
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
counts = result["counts"] # recovered count matrix
|
|
104
|
+
scale_factors = result["scale_factors"] # per-cell scale factors
|
|
105
|
+
library_sizes = result["library_sizes"] # recovered library sizes
|
|
106
|
+
corrections = result["corrections"] # robust correction flags
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Validation
|
|
110
|
+
|
|
111
|
+
Tested on **256,000+ real cells** with ground-truth counts:
|
|
112
|
+
|
|
113
|
+
| Dataset | Cells | Genes | Recovery |
|
|
114
|
+
|---------|------:|------:|---------:|
|
|
115
|
+
| PBMC3k | 2,638 | 13,714 | **100%** |
|
|
116
|
+
| Purified PBMC | 105,753 | 19,512 | **100%** |
|
|
117
|
+
| CITE-seq PBMC | 147,582 | 20,729 | **100%** |
|
|
118
|
+
|
|
119
|
+
All three datasets: **every element, every cell, exactly recovered**.
|
|
120
|
+
|
|
121
|
+
### Robustness
|
|
122
|
+
|
|
123
|
+
| Scenario | Result |
|
|
124
|
+
|----------|--------|
|
|
125
|
+
| `target_sum` = 100, 1e3, 1e4, 1e5, 1e6 | 100% |
|
|
126
|
+
| `target_sum` = median(library_size) | 100% |
|
|
127
|
+
| scran-style arbitrary size factors | 100% |
|
|
128
|
+
| log2(1+x) and log10(1+x) | 100% |
|
|
129
|
+
| Cells with min_count > 1 (robust mode) | 100% |
|
|
130
|
+
| Deeply sequenced cells (high counts) | 100% |
|
|
131
|
+
|
|
132
|
+
## API reference
|
|
133
|
+
|
|
134
|
+
### `stancounts.reverse_log1p(X, *, base="e", robust=True)`
|
|
135
|
+
|
|
136
|
+
Reverse log1p normalization to recover raw counts.
|
|
137
|
+
|
|
138
|
+
**Parameters:**
|
|
139
|
+
- `X` — expression matrix (cells × genes), sparse or dense
|
|
140
|
+
- `base` — log base: `"e"` (default), `"2"`, or `"10"`
|
|
141
|
+
- `robust` — detect and correct cells whose minimum nonzero count > 1
|
|
142
|
+
|
|
143
|
+
**Returns** `dict` with keys: `counts`, `scale_factors`, `library_sizes`, `corrections`
|
|
144
|
+
|
|
145
|
+
### `stancounts.reverse_log1p_anndata(adata, *, source="X", target_layer="counts_recovered", base="e", robust=True)`
|
|
146
|
+
|
|
147
|
+
Convenience wrapper for AnnData objects. Stores recovered counts in `adata.layers[target_layer]` and scale factors in `adata.obs`.
|
|
148
|
+
|
|
149
|
+
### `stancounts.detect_normalization(X, *, n_sample=200, seed=0)`
|
|
150
|
+
|
|
151
|
+
Auto-detect whether data is log1p-normalized and determine the log base.
|
|
152
|
+
|
|
153
|
+
**Returns** `dict` with keys: `is_log1p`, `base`, `scores`, `is_integer`, `max_value`
|
|
154
|
+
|
|
155
|
+
### `stancounts.is_log1p_normalized(X, **kwargs)`
|
|
156
|
+
|
|
157
|
+
Convenience wrapper: returns `True` if data appears log1p-normalized.
|
|
158
|
+
|
|
159
|
+
## When it won't work
|
|
160
|
+
|
|
161
|
+
- **Batch-corrected data** (e.g., Harmony, scVI latent space) — the linear count→normalized relationship is broken
|
|
162
|
+
- **scTransform** (Pearson residuals) — not a log1p(scaled_counts) transform
|
|
163
|
+
- **Aggregated/pseudobulk** data — may still work if the aggregation preserves the structure
|
|
164
|
+
- **Fractional counts** (e.g., from imputation) — no integer counts to recover
|
|
165
|
+
|
|
166
|
+
## Dependencies
|
|
167
|
+
|
|
168
|
+
- `numpy >= 1.22`
|
|
169
|
+
- `scipy >= 1.7`
|
|
170
|
+
- `anndata >= 0.8` *(optional, for AnnData integration)*
|
|
171
|
+
|
|
172
|
+
## License
|
|
173
|
+
|
|
174
|
+
MIT
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
stancounts PostToolUse hook — family handoff to QC stage.
|
|
4
|
+
|
|
5
|
+
stancounts ships as a Python library (no CLI), so this hook is best-effort:
|
|
6
|
+
it triggers when a Bash ``python …`` invocation mentions ``stancounts`` as
|
|
7
|
+
a module/import, e.g.::
|
|
8
|
+
|
|
9
|
+
python -c "from stancounts import reverse_log1p_anndata; ..."
|
|
10
|
+
python some_script.py # NOT detectable — script may import internally
|
|
11
|
+
python -m stancounts.xxx # detectable (though stancounts has no CLI today)
|
|
12
|
+
|
|
13
|
+
When the Python process exits 0, inject a handoff hint: the next step in
|
|
14
|
+
the stan* family pipeline is the QC stage (eca-curation's 03_qc / future
|
|
15
|
+
stanqc module; presently implemented on top of scanpy).
|
|
16
|
+
|
|
17
|
+
Design rules:
|
|
18
|
+
- Never block. This is PostToolUse — the tool already executed.
|
|
19
|
+
- No-op unless the Bash command is a ``python …`` that explicitly mentions
|
|
20
|
+
``stancounts`` (prevents false positives like ``pip install stancounts``).
|
|
21
|
+
- No-op on non-zero exit, parse error, or missing field.
|
|
22
|
+
- Exit 0 in all cases. Feedback is delivered via JSON stdout
|
|
23
|
+
(``hookSpecificOutput.additionalContext``), with stderr as a
|
|
24
|
+
best-effort fallback for older runtimes.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import json
|
|
30
|
+
import re
|
|
31
|
+
import sys
|
|
32
|
+
from typing import Optional
|
|
33
|
+
|
|
34
|
+
# Match: `python[3] … stancounts …` within a single shell command.
|
|
35
|
+
# Anchoring to `python` prevents false positives on `cat stancounts_notes.md`,
|
|
36
|
+
# `conda install -c bioconda stancounts`, etc. The explicit package-manager
|
|
37
|
+
# filter below covers `python -m pip install stancounts` and similar forms
|
|
38
|
+
# where `python` itself is the package-manager launcher.
|
|
39
|
+
_STANCOUNTS_CMD = re.compile(
|
|
40
|
+
r"(?:^|[\s;|&\n])python\d?\s[^\n]*?\bstancounts\b"
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
_PKG_MGR_CMD = re.compile(
|
|
44
|
+
r"\b(?:pip|pip3|conda|mamba|micromamba|uv|poetry|pipx)"
|
|
45
|
+
r"\s+(?:install|uninstall|add|remove|show|list|search|info|update|upgrade|sync)\b"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
_HANDOFF = (
|
|
49
|
+
"✅ stancounts 执行成功(已反向 log1p,恢复 integer counts)。\n"
|
|
50
|
+
"\n"
|
|
51
|
+
"家族流水线中 stancounts 的下游是 **stanqc**(QC stage)。stanqc 是\n"
|
|
52
|
+
"tissue / species / platform 不可知的两层 QC(Tier-1 sample health +\n"
|
|
53
|
+
"Tier-2 per-group MAD),不自动删 cell,只在 obs 加 `out_*` flag 列。\n"
|
|
54
|
+
"\n"
|
|
55
|
+
"建议的下一步:\n"
|
|
56
|
+
" • 如果当前在 eca-curation pipeline session 里:运行\n"
|
|
57
|
+
" /eca-run <dataset>\n"
|
|
58
|
+
" pipeline 会调用 stanqc 推进到 03_qc 阶段(默认 iterative,直到\n"
|
|
59
|
+
" flagged 比例收敛)。\n"
|
|
60
|
+
" • 否则直接调 stanqc:\n"
|
|
61
|
+
" import stanqc\n"
|
|
62
|
+
" result = stanqc.run_qc(\n"
|
|
63
|
+
" adata, sample_key=...,\n"
|
|
64
|
+
" cell_type_key=..., # 可选,有标注则 per-celltype MAD\n"
|
|
65
|
+
" species=None, # None = 自动检测\n"
|
|
66
|
+
" platform=None, # None = 自动检测\n"
|
|
67
|
+
" outdir='qc_out/',\n"
|
|
68
|
+
" )\n"
|
|
69
|
+
" # adata.obs 多了 out_* 列;最终是否 drop 由用户决定:\n"
|
|
70
|
+
" # clean = adata[~adata.obs['out_any']].copy()"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _read_payload() -> dict:
|
|
75
|
+
try:
|
|
76
|
+
raw = sys.stdin.read()
|
|
77
|
+
except OSError:
|
|
78
|
+
return {}
|
|
79
|
+
if not raw:
|
|
80
|
+
return {}
|
|
81
|
+
try:
|
|
82
|
+
return json.loads(raw)
|
|
83
|
+
except json.JSONDecodeError:
|
|
84
|
+
return {}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _get_bash_command(payload: dict) -> Optional[str]:
|
|
88
|
+
tool_name = (
|
|
89
|
+
payload.get("tool_name")
|
|
90
|
+
or (payload.get("tool_use") or {}).get("name")
|
|
91
|
+
or (payload.get("toolUse") or {}).get("name")
|
|
92
|
+
)
|
|
93
|
+
if tool_name != "Bash":
|
|
94
|
+
return None
|
|
95
|
+
tool_input = (
|
|
96
|
+
payload.get("tool_input")
|
|
97
|
+
or (payload.get("tool_use") or {}).get("input")
|
|
98
|
+
or (payload.get("toolUse") or {}).get("input")
|
|
99
|
+
or {}
|
|
100
|
+
)
|
|
101
|
+
cmd = tool_input.get("command")
|
|
102
|
+
return cmd if isinstance(cmd, str) else None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _exit_code(payload: dict) -> int:
|
|
106
|
+
res = (
|
|
107
|
+
payload.get("tool_response")
|
|
108
|
+
or payload.get("tool_result")
|
|
109
|
+
or payload.get("toolResult")
|
|
110
|
+
or {}
|
|
111
|
+
)
|
|
112
|
+
if not isinstance(res, dict):
|
|
113
|
+
return 0
|
|
114
|
+
for key in ("exit_code", "exitCode", "returncode", "returnCode"):
|
|
115
|
+
code = res.get(key)
|
|
116
|
+
if code is not None:
|
|
117
|
+
try:
|
|
118
|
+
return int(code)
|
|
119
|
+
except (TypeError, ValueError):
|
|
120
|
+
return 1
|
|
121
|
+
if res.get("is_error") or res.get("isError"):
|
|
122
|
+
return 1
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main() -> int:
|
|
127
|
+
payload = _read_payload()
|
|
128
|
+
cmd = _get_bash_command(payload)
|
|
129
|
+
if not cmd:
|
|
130
|
+
return 0
|
|
131
|
+
if _exit_code(payload) != 0:
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
# Split by shell operators so chained commands like
|
|
135
|
+
# ``pip install stancounts && python -c "from stancounts ..."`` still
|
|
136
|
+
# trigger on the run segment while the install segment is skipped.
|
|
137
|
+
matched = False
|
|
138
|
+
for seg in re.split(r"(?:&&|\|\||;|\|)", cmd):
|
|
139
|
+
if _PKG_MGR_CMD.search(seg):
|
|
140
|
+
continue
|
|
141
|
+
if _STANCOUNTS_CMD.search(seg):
|
|
142
|
+
matched = True
|
|
143
|
+
break
|
|
144
|
+
if not matched:
|
|
145
|
+
return 0
|
|
146
|
+
|
|
147
|
+
out = {
|
|
148
|
+
"hookSpecificOutput": {
|
|
149
|
+
"hookEventName": "PostToolUse",
|
|
150
|
+
"additionalContext": _HANDOFF,
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
try:
|
|
154
|
+
print(json.dumps(out))
|
|
155
|
+
except Exception:
|
|
156
|
+
pass
|
|
157
|
+
try:
|
|
158
|
+
print(_HANDOFF, file=sys.stderr)
|
|
159
|
+
except Exception:
|
|
160
|
+
pass
|
|
161
|
+
return 0
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
if __name__ == "__main__":
|
|
165
|
+
sys.exit(main())
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 120" width="480" height="120">
|
|
2
|
+
<defs>
|
|
3
|
+
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
|
|
4
|
+
<stop offset="0%" style="stop-color:#1a1a2e;stop-opacity:1" />
|
|
5
|
+
<stop offset="100%" style="stop-color:#16213e;stop-opacity:1" />
|
|
6
|
+
</linearGradient>
|
|
7
|
+
<linearGradient id="accent" x1="0%" y1="0%" x2="100%" y2="0%">
|
|
8
|
+
<stop offset="0%" style="stop-color:#e94560;stop-opacity:1" />
|
|
9
|
+
<stop offset="100%" style="stop-color:#ff6b6b;stop-opacity:1" />
|
|
10
|
+
</linearGradient>
|
|
11
|
+
<linearGradient id="curve" x1="0%" y1="0%" x2="100%" y2="0%">
|
|
12
|
+
<stop offset="0%" style="stop-color:#0f3460;stop-opacity:1" />
|
|
13
|
+
<stop offset="100%" style="stop-color:#533483;stop-opacity:1" />
|
|
14
|
+
</linearGradient>
|
|
15
|
+
</defs>
|
|
16
|
+
|
|
17
|
+
<!-- Background -->
|
|
18
|
+
<rect width="480" height="120" rx="16" fill="url(#bg)" />
|
|
19
|
+
|
|
20
|
+
<!-- Log1p curve (forward) - faded -->
|
|
21
|
+
<path d="M 25 95 Q 40 55, 55 45 Q 70 35, 85 30 Q 100 26, 115 24"
|
|
22
|
+
stroke="#334155" stroke-width="2.5" fill="none" stroke-linecap="round" opacity="0.6"/>
|
|
23
|
+
|
|
24
|
+
<!-- Arrow showing reversal -->
|
|
25
|
+
<path d="M 75 58 L 65 52 M 75 58 L 65 64"
|
|
26
|
+
stroke="url(#accent)" stroke-width="2" fill="none" stroke-linecap="round"/>
|
|
27
|
+
<line x1="75" y1="58" x2="55" y2="58"
|
|
28
|
+
stroke="url(#accent)" stroke-width="2" stroke-linecap="round"/>
|
|
29
|
+
|
|
30
|
+
<!-- Count bars (discrete, recovered) -->
|
|
31
|
+
<rect x="30" y="78" width="6" height="17" rx="1.5" fill="#e94560" opacity="0.9"/>
|
|
32
|
+
<rect x="40" y="68" width="6" height="27" rx="1.5" fill="#e94560" opacity="0.8"/>
|
|
33
|
+
<rect x="50" y="83" width="6" height="12" rx="1.5" fill="#e94560" opacity="0.7"/>
|
|
34
|
+
<rect x="60" y="73" width="6" height="22" rx="1.5" fill="#ff6b6b" opacity="0.8"/>
|
|
35
|
+
<rect x="70" y="88" width="6" height="7" rx="1.5" fill="#ff6b6b" opacity="0.6"/>
|
|
36
|
+
<rect x="80" y="63" width="6" height="32" rx="1.5" fill="#ff6b6b" opacity="0.9"/>
|
|
37
|
+
<rect x="90" y="78" width="6" height="17" rx="1.5" fill="#e94560" opacity="0.7"/>
|
|
38
|
+
<rect x="100" y="85" width="6" height="10" rx="1.5" fill="#e94560" opacity="0.6"/>
|
|
39
|
+
<rect x="110" y="70" width="6" height="25" rx="1.5" fill="#ff6b6b" opacity="0.8"/>
|
|
40
|
+
|
|
41
|
+
<!-- Text: stan -->
|
|
42
|
+
<text x="140" y="72" font-family="'SF Mono','Fira Code','Cascadia Code',monospace"
|
|
43
|
+
font-size="42" font-weight="300" fill="#94a3b8" letter-spacing="-1">stan</text>
|
|
44
|
+
|
|
45
|
+
<!-- Text: counts -->
|
|
46
|
+
<text x="258" y="72" font-family="'SF Mono','Fira Code','Cascadia Code',monospace"
|
|
47
|
+
font-size="42" font-weight="700" fill="url(#accent)" letter-spacing="-1">counts</text>
|
|
48
|
+
|
|
49
|
+
<!-- Tagline -->
|
|
50
|
+
<text x="140" y="96" font-family="'Inter','Helvetica Neue',sans-serif"
|
|
51
|
+
font-size="13" fill="#64748b" letter-spacing="0.5">log1p(x) → counts</text>
|
|
52
|
+
|
|
53
|
+
<!-- Formula badge -->
|
|
54
|
+
<rect x="280" y="84" width="160" height="22" rx="11" fill="#1e293b" stroke="#334155" stroke-width="0.8"/>
|
|
55
|
+
<text x="360" y="99" font-family="'SF Mono',monospace" font-size="11" fill="#e94560"
|
|
56
|
+
text-anchor="middle" letter-spacing="0.3">round(expm1(y)/sf)</text>
|
|
57
|
+
</svg>
|