scinspect 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yash Bhida
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,214 @@
1
+ Metadata-Version: 2.4
2
+ Name: scinspect
3
+ Version: 0.1.0
4
+ Summary: Find out what is really inside a single-cell dataset (raw counts or normalized, log base, scaled, gene ID problems) before you analyze it.
5
+ Author: Yash Bhida
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/bhodayasa/scinspect
8
+ Project-URL: Issues, https://github.com/bhodayasa/scinspect/issues
9
+ Keywords: single-cell,scRNA-seq,anndata,scanpy,quality control,bioinformatics,normalization
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
14
+ Classifier: Environment :: Console
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.21
19
+ Requires-Dist: scipy>=1.8
20
+ Requires-Dist: pandas>=1.3
21
+ Requires-Dist: h5py>=3.0
22
+ Provides-Extra: anndata
23
+ Requires-Dist: anndata>=0.8; extra == "anndata"
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=7; extra == "test"
26
+ Requires-Dist: anndata>=0.8; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # scinspect
30
+
31
+ **Find out what is really inside a single-cell dataset before you analyze it.**
32
+
33
+ You download an `.h5ad` from CELLxGENE, a 10x folder from GEO, or a CSV from a paper's supplement.
34
+ Is `adata.X` raw counts? Normalized? Log-transformed, and in which base? Scaled? Is `adata.raw`
35
+ counts or log data? Are the genes Ensembl IDs, mouse or human, mangled by Excel?
36
+
37
+ The file usually doesn't say, and guessing wrong fails **silently**: you log-transform twice, feed
38
+ scaled data to a differential-expression test, or give scVI normalized values. These questions come
39
+ up again and again on the scverse forum, Biostars and GitHub issues.
40
+
41
+ `scinspect` answers them in one command:
42
+
43
+ ```bash
44
+ pip install scinspect
45
+ scinspect downloaded_atlas.h5ad
46
+ ```
47
+
48
+ ```
49
+ scinspect 0.1.0 downloaded_atlas.h5ad
50
+ h5ad · 8,000 cells × 2,000 features · checked a random sample of 2,000 cells
51
+
52
+ MATRICES
53
+ X Scaled / z-scored (per-gene mean 0, unit variance) — clipped at 10 (sc.pp.scale(max_value=10) / Seurat ScaleData) [high confidence]
54
+ layers['counts'] Raw counts (non-negative integers) [high confidence]
55
+ median 2,095 counts and 630 genes per cell
56
+ raw.X Log-transformed, size-normalized counts: ln(1+x), each cell normalized to 10,000 (Scanpy / Seurat default) [high confidence]
57
+ original depth ≈ 2,996 counts/cell (median)
58
+
59
+ FEATURES
60
+ gene symbols · human-style symbols (ALL CAPS) · 3 mitochondrial genes
61
+
62
+ FINDINGS
63
+ ✖ ERROR 2 gene names look like Excel-converted dates or numbers
64
+ Examples: 1-Mar, 2-Sep. Likely originals: MARCH*/MARCHF*, SEPT*/SEPTIN*
65
+ → These genes were corrupted by opening the file in a spreadsheet. Recover the originals from
66
+ the source (e.g. GEO feature file) instead of guessing.
67
+ i INFO adata.raw holds normalized values, not raw counts
68
+ → Do not feed adata.raw to count-based models.
69
+ i INFO X is scaled data
70
+ → Do not use this matrix for differential expression, marker genes, or cell-type annotation.
71
+ ✓ OK raw.X is consistent with layers['counts']
72
+ 100% of sampled cells match exactly (genes aligned by gene name).
73
+
74
+ WHAT TO USE FOR WHAT
75
+ ✓ scVI / scANVI / totalVI adata.layers['counts']
76
+ ✓ Pseudobulk differential expression (DESeq2, edgeR) adata.layers['counts']
77
+ ✓ Highly variable genes, flavor='seurat_v3' adata.layers['counts']
78
+ – sc.pp.normalize_total + sc.pp.log1p already done in adata.raw.X
79
+ ✓ PCA, neighbors, clustering, UMAP adata.X
80
+ ✓ Marker genes (sc.tl.rank_genes_groups) adata.raw.X
81
+ ✓ CellTypist annotation adata.raw.X
82
+ ! Plotting expression (violin, dot plots) adata.raw.X
83
+
84
+ VERDICT: 1 error.
85
+ ```
86
+
87
+ ## What it checks
88
+
89
+ **Every matrix in the file** (`X`, every layer, `raw.X`), each classified as:
90
+
91
+ | State | How it is recognized |
92
+ |---|---|
93
+ | Raw counts | non-negative integers (also flags full-length read counts vs UMIs) |
94
+ | log1p of size-normalized counts | undoing the log gives integer multiples per cell; reports **log base** (e, 2, 10) and **target sum** (10,000, CPM, median) |
95
+ | log1p applied **twice** | only a double inverse gives integers back |
96
+ | log of counts with no normalization | inverse gives exact integers, cell totals vary |
97
+ | Normalized but not logged | values are integer multiples per cell, totals constant |
98
+ | Scaled / z-scored | per-gene mean 0 and unit variance; detects clipping at 10 |
99
+ | Residuals / batch-corrected | negative values that are not z-scores |
100
+ | TPM-like, log-TPM | totals are constant but values are not count multiples |
101
+ | Fractional counts | Salmon/RSEM estimates, ambient-corrected counts |
102
+ | Binary | scATAC-style 0/1 |
103
+
104
+ It also recovers the **original sequencing depth** from normalized data, and checks that each processed
105
+ matrix really is a normalization of the counts matrix (same cells, same gene order).
106
+
107
+ **Genes and cells**
108
+
109
+ - Excel-mangled gene names (`1-Mar`, `Sep-07`, `2.31E+13`)
110
+ - Ensembl IDs vs symbols vs a mix; species from Ensembl prefix or symbol case; mixed ID versions
111
+ - Mixed-species (barnyard) references such as `GRCh38_` + `mm10___` prefixes
112
+ - Duplicated gene names and duplicated cell barcodes
113
+ - Missing mitochondrial genes (so %-mito QC is impossible)
114
+ - Matrices stored the wrong way round (genes × cells)
115
+ - Unfiltered droplet matrices full of empty barcodes (including exact 10x whitelist sizes)
116
+ - scATAC peak matrices, small protein (ADT) panels
117
+
118
+ **Slot mix-ups**
119
+
120
+ - `layers['counts']` that does not contain counts
121
+ - `adata.raw` holding log data (the Scanpy habit) or counts (so `rank_genes_groups` needs `use_raw=False`)
122
+ - Which matrix to use for scVI, pseudobulk DE, `seurat_v3` HVGs, PCA, marker genes and CellTypist
123
+
124
+ ## Supported inputs
125
+
126
+ | Input | Notes |
127
+ |---|---|
128
+ | `.h5ad` | read lazily with h5py, so multi-GB atlases are fine |
129
+ | 10x Genomics `.h5` | Cell Ranger v2 and v3+, multimodal (gene expression + antibody capture) |
130
+ | 10x folder / `.mtx` | `matrix.mtx(.gz)` + `features.tsv`/`genes.tsv` + `barcodes.tsv`, including GEO `GSM123_` prefixes |
131
+ | `.loom` | including layers (velocyto spliced/unspliced) |
132
+ | `.csv`, `.tsv`, `.txt` (+ `.gz`) | genes × cells tables are detected and transposed |
133
+ | AnnData object | `scinspect.check(adata)` in Python |
134
+
135
+ Seurat `.rds` files cannot be read from Python; the error message explains how to export them.
136
+
137
+ ## Usage
138
+
139
+ ```bash
140
+ scinspect data.h5ad # readable report
141
+ scinspect data.h5ad --markdown # paste into a lab notebook, README or PR
142
+ scinspect data.h5ad --json # for scripts
143
+ scinspect *.h5ad --fail-on warn # exit 1 on warnings: use in CI or pipelines
144
+ scinspect data.h5ad --sample 5000 # check more cells (default 2,000)
145
+ ```
146
+
147
+ ```python
148
+ import scanpy as sc
149
+ import scinspect
150
+
151
+ adata = sc.read_h5ad("data.h5ad")
152
+ report = scinspect.check(adata)
153
+ print(report) # same text report
154
+ report.matrix("X").kind # 'log1p_normalized'
155
+ report.matrix("X").details["log_base"] # 'e'
156
+ report.matrix("X").details["target_sum"] # 10000.0
157
+ report.worst_level # 'ok' | 'info' | 'warn' | 'error'
158
+ ```
159
+
160
+ Exit codes: `0` passed, `1` findings at or above `--fail-on` (default `error`), `2` file could not be read.
161
+
162
+ ## How it works
163
+
164
+ Most normalizations leave a fingerprint you can reverse. Scanpy's default is
165
+ `x = ln(1 + counts × 10,000 / total)`. Applying `exp(x) − 1` gives `counts × c` for one constant
166
+ `c` per cell. Divide by the cell's smallest non-zero value and you get integers back, and the cell
167
+ sums equal exactly 10,000. A wrong log base gives non-integers, so the base can be identified.
168
+ `scinspect` runs these tests on a random sample of cells (2,000 by default), so even very large
169
+ files are checked in seconds.
170
+
171
+ ## Related tools
172
+
173
+ Some pieces of this exist; `scinspect` puts them in one report that covers every matrix in a
174
+ file plus gene and layout problems.
175
+
176
+ - [stancounts](https://pypi.org/project/stancounts/) detects log1p and its base for one matrix and recovers counts.
177
+ - [scDenorm](https://www.biorxiv.org/content/10.1101/2025.05.10.653289) and `omicverse.pp.recover_counts` recover counts from normalized data.
178
+ - [hca-validation-tools](https://github.com/clevercanary/hca-validation-tools) has an internal raw-vs-normalized check for HCA atlas curation.
179
+ - [Truke](https://pmc.ncbi.nlm.nih.gov/articles/PMC5359807/) and [Escape Excel](https://github.com/pstew/escape_excel) handle Excel gene-name damage.
180
+
181
+ If you need the counts back, use `scinspect` to find out whether they are recoverable, then one of
182
+ the recovery tools above.
183
+
184
+ ## Tested on
185
+
186
+ Besides 71 unit tests on simulated pipelines, `scinspect` was run on the real test files that ship
187
+ with Scanpy and AnnData:
188
+
189
+ - 10x Genomics Cell Ranger v2 and v3 `.h5` files and `.mtx` folders, including a multi-genome file
190
+ - 10x Visium spatial `.h5` files (v1.0 and v2.1 probe-based)
191
+ - `.h5ad` files written by AnnData 0.5, 0.7, 0.11 and 0.13, including the reduced PBMC 68k dataset,
192
+ where it correctly finds scaled `X` and ln(1+x) normalized `raw.X` stored with 3 decimals
193
+
194
+ ## Limitations
195
+
196
+ - It infers state from the numbers; it cannot know your methods section. Check `confidence`.
197
+ - SCTransform-corrected counts are integers and are reported as raw counts.
198
+ - Species from gene symbols is a guess from capitalization (ALL CAPS vs Capitalized).
199
+ - Seurat `.rds` is not read directly.
200
+ - Files compressed with uncommon HDF5 filters are skipped slot by slot, with a note, rather than failing.
201
+
202
+ ## Contributing
203
+
204
+ Bug reports with a (small or public) file that is classified wrongly are the most useful contribution.
205
+ Run the tests with:
206
+
207
+ ```bash
208
+ pip install -e ".[test]"
209
+ pytest
210
+ ```
211
+
212
+ ## License
213
+
214
+ MIT
@@ -0,0 +1,186 @@
1
+ # scinspect
2
+
3
+ **Find out what is really inside a single-cell dataset before you analyze it.**
4
+
5
+ You download an `.h5ad` from CELLxGENE, a 10x folder from GEO, or a CSV from a paper's supplement.
6
+ Is `adata.X` raw counts? Normalized? Log-transformed, and in which base? Scaled? Is `adata.raw`
7
+ counts or log data? Are the genes Ensembl IDs, mouse or human, mangled by Excel?
8
+
9
+ The file usually doesn't say, and guessing wrong fails **silently**: you log-transform twice, feed
10
+ scaled data to a differential-expression test, or give scVI normalized values. These questions come
11
+ up again and again on the scverse forum, Biostars and GitHub issues.
12
+
13
+ `scinspect` answers them in one command:
14
+
15
+ ```bash
16
+ pip install scinspect
17
+ scinspect downloaded_atlas.h5ad
18
+ ```
19
+
20
+ ```
21
+ scinspect 0.1.0 downloaded_atlas.h5ad
22
+ h5ad · 8,000 cells × 2,000 features · checked a random sample of 2,000 cells
23
+
24
+ MATRICES
25
+ X Scaled / z-scored (per-gene mean 0, unit variance) — clipped at 10 (sc.pp.scale(max_value=10) / Seurat ScaleData) [high confidence]
26
+ layers['counts'] Raw counts (non-negative integers) [high confidence]
27
+ median 2,095 counts and 630 genes per cell
28
+ raw.X Log-transformed, size-normalized counts: ln(1+x), each cell normalized to 10,000 (Scanpy / Seurat default) [high confidence]
29
+ original depth ≈ 2,996 counts/cell (median)
30
+
31
+ FEATURES
32
+ gene symbols · human-style symbols (ALL CAPS) · 3 mitochondrial genes
33
+
34
+ FINDINGS
35
+ ✖ ERROR 2 gene names look like Excel-converted dates or numbers
36
+ Examples: 1-Mar, 2-Sep. Likely originals: MARCH*/MARCHF*, SEPT*/SEPTIN*
37
+ → These genes were corrupted by opening the file in a spreadsheet. Recover the originals from
38
+ the source (e.g. GEO feature file) instead of guessing.
39
+ i INFO adata.raw holds normalized values, not raw counts
40
+ → Do not feed adata.raw to count-based models.
41
+ i INFO X is scaled data
42
+ → Do not use this matrix for differential expression, marker genes, or cell-type annotation.
43
+ ✓ OK raw.X is consistent with layers['counts']
44
+ 100% of sampled cells match exactly (genes aligned by gene name).
45
+
46
+ WHAT TO USE FOR WHAT
47
+ ✓ scVI / scANVI / totalVI adata.layers['counts']
48
+ ✓ Pseudobulk differential expression (DESeq2, edgeR) adata.layers['counts']
49
+ ✓ Highly variable genes, flavor='seurat_v3' adata.layers['counts']
50
+ – sc.pp.normalize_total + sc.pp.log1p already done in adata.raw.X
51
+ ✓ PCA, neighbors, clustering, UMAP adata.X
52
+ ✓ Marker genes (sc.tl.rank_genes_groups) adata.raw.X
53
+ ✓ CellTypist annotation adata.raw.X
54
+ ! Plotting expression (violin, dot plots) adata.raw.X
55
+
56
+ VERDICT: 1 error.
57
+ ```
58
+
59
+ ## What it checks
60
+
61
+ **Every matrix in the file** (`X`, every layer, `raw.X`), each classified as:
62
+
63
+ | State | How it is recognized |
64
+ |---|---|
65
+ | Raw counts | non-negative integers (also flags full-length read counts vs UMIs) |
66
+ | log1p of size-normalized counts | undoing the log gives integer multiples per cell; reports **log base** (e, 2, 10) and **target sum** (10,000, CPM, median) |
67
+ | log1p applied **twice** | only a double inverse gives integers back |
68
+ | log of counts with no normalization | inverse gives exact integers, cell totals vary |
69
+ | Normalized but not logged | values are integer multiples per cell, totals constant |
70
+ | Scaled / z-scored | per-gene mean 0 and unit variance; detects clipping at 10 |
71
+ | Residuals / batch-corrected | negative values that are not z-scores |
72
+ | TPM-like, log-TPM | totals are constant but values are not count multiples |
73
+ | Fractional counts | Salmon/RSEM estimates, ambient-corrected counts |
74
+ | Binary | scATAC-style 0/1 |
75
+
76
+ It also recovers the **original sequencing depth** from normalized data, and checks that each processed
77
+ matrix really is a normalization of the counts matrix (same cells, same gene order).
78
+
79
+ **Genes and cells**
80
+
81
+ - Excel-mangled gene names (`1-Mar`, `Sep-07`, `2.31E+13`)
82
+ - Ensembl IDs vs symbols vs a mix; species from Ensembl prefix or symbol case; mixed ID versions
83
+ - Mixed-species (barnyard) references such as `GRCh38_` + `mm10___` prefixes
84
+ - Duplicated gene names and duplicated cell barcodes
85
+ - Missing mitochondrial genes (so %-mito QC is impossible)
86
+ - Matrices stored the wrong way round (genes × cells)
87
+ - Unfiltered droplet matrices full of empty barcodes (including exact 10x whitelist sizes)
88
+ - scATAC peak matrices, small protein (ADT) panels
89
+
90
+ **Slot mix-ups**
91
+
92
+ - `layers['counts']` that does not contain counts
93
+ - `adata.raw` holding log data (the Scanpy habit) or counts (so `rank_genes_groups` needs `use_raw=False`)
94
+ - Which matrix to use for scVI, pseudobulk DE, `seurat_v3` HVGs, PCA, marker genes and CellTypist
95
+
96
+ ## Supported inputs
97
+
98
+ | Input | Notes |
99
+ |---|---|
100
+ | `.h5ad` | read lazily with h5py, so multi-GB atlases are fine |
101
+ | 10x Genomics `.h5` | Cell Ranger v2 and v3+, multimodal (gene expression + antibody capture) |
102
+ | 10x folder / `.mtx` | `matrix.mtx(.gz)` + `features.tsv`/`genes.tsv` + `barcodes.tsv`, including GEO `GSM123_` prefixes |
103
+ | `.loom` | including layers (velocyto spliced/unspliced) |
104
+ | `.csv`, `.tsv`, `.txt` (+ `.gz`) | genes × cells tables are detected and transposed |
105
+ | AnnData object | `scinspect.check(adata)` in Python |
106
+
107
+ Seurat `.rds` files cannot be read from Python; the error message explains how to export them.
108
+
109
+ ## Usage
110
+
111
+ ```bash
112
+ scinspect data.h5ad # readable report
113
+ scinspect data.h5ad --markdown # paste into a lab notebook, README or PR
114
+ scinspect data.h5ad --json # for scripts
115
+ scinspect *.h5ad --fail-on warn # exit 1 on warnings: use in CI or pipelines
116
+ scinspect data.h5ad --sample 5000 # check more cells (default 2,000)
117
+ ```
118
+
119
+ ```python
120
+ import scanpy as sc
121
+ import scinspect
122
+
123
+ adata = sc.read_h5ad("data.h5ad")
124
+ report = scinspect.check(adata)
125
+ print(report) # same text report
126
+ report.matrix("X").kind # 'log1p_normalized'
127
+ report.matrix("X").details["log_base"] # 'e'
128
+ report.matrix("X").details["target_sum"] # 10000.0
129
+ report.worst_level # 'ok' | 'info' | 'warn' | 'error'
130
+ ```
131
+
132
+ Exit codes: `0` passed, `1` findings at or above `--fail-on` (default `error`), `2` file could not be read.
133
+
134
+ ## How it works
135
+
136
+ Most normalizations leave a fingerprint you can reverse. Scanpy's default is
137
+ `x = ln(1 + counts × 10,000 / total)`. Applying `exp(x) − 1` gives `counts × c` for one constant
138
+ `c` per cell. Divide by the cell's smallest non-zero value and you get integers back, and the cell
139
+ sums equal exactly 10,000. A wrong log base gives non-integers, so the base can be identified.
140
+ `scinspect` runs these tests on a random sample of cells (2,000 by default), so even very large
141
+ files are checked in seconds.
142
+
143
+ ## Related tools
144
+
145
+ Some pieces of this exist; `scinspect` puts them in one report that covers every matrix in a
146
+ file plus gene and layout problems.
147
+
148
+ - [stancounts](https://pypi.org/project/stancounts/) detects log1p and its base for one matrix and recovers counts.
149
+ - [scDenorm](https://www.biorxiv.org/content/10.1101/2025.05.10.653289) and `omicverse.pp.recover_counts` recover counts from normalized data.
150
+ - [hca-validation-tools](https://github.com/clevercanary/hca-validation-tools) has an internal raw-vs-normalized check for HCA atlas curation.
151
+ - [Truke](https://pmc.ncbi.nlm.nih.gov/articles/PMC5359807/) and [Escape Excel](https://github.com/pstew/escape_excel) handle Excel gene-name damage.
152
+
153
+ If you need the counts back, use `scinspect` to find out whether they are recoverable, then one of
154
+ the recovery tools above.
155
+
156
+ ## Tested on
157
+
158
+ Besides 71 unit tests on simulated pipelines, `scinspect` was run on the real test files that ship
159
+ with Scanpy and AnnData:
160
+
161
+ - 10x Genomics Cell Ranger v2 and v3 `.h5` files and `.mtx` folders, including a multi-genome file
162
+ - 10x Visium spatial `.h5` files (v1.0 and v2.1 probe-based)
163
+ - `.h5ad` files written by AnnData 0.5, 0.7, 0.11 and 0.13, including the reduced PBMC 68k dataset,
164
+ where it correctly finds scaled `X` and ln(1+x) normalized `raw.X` stored with 3 decimals
165
+
166
+ ## Limitations
167
+
168
+ - It infers state from the numbers; it cannot know your methods section. Check `confidence`.
169
+ - SCTransform-corrected counts are integers and are reported as raw counts.
170
+ - Species from gene symbols is a guess from capitalization (ALL CAPS vs Capitalized).
171
+ - Seurat `.rds` is not read directly.
172
+ - Files compressed with uncommon HDF5 filters are skipped slot by slot, with a note, rather than failing.
173
+
174
+ ## Contributing
175
+
176
+ Bug reports with a (small or public) file that is classified wrongly are the most useful contribution.
177
+ Run the tests with:
178
+
179
+ ```bash
180
+ pip install -e ".[test]"
181
+ pytest
182
+ ```
183
+
184
+ ## License
185
+
186
+ MIT
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "scinspect"
7
+ dynamic = ["version"]
8
+ description = "Find out what is really inside a single-cell dataset (raw counts or normalized, log base, scaled, gene ID problems) before you analyze it."
9
+ readme = "README.md"
10
+ license = { text = "MIT" }
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Yash Bhida" }]
13
+ keywords = ["single-cell", "scRNA-seq", "anndata", "scanpy", "quality control", "bioinformatics", "normalization"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Science/Research",
17
+ "Programming Language :: Python :: 3",
18
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
19
+ "Environment :: Console",
20
+ ]
21
+ dependencies = ["numpy>=1.21", "scipy>=1.8", "pandas>=1.3", "h5py>=3.0"]
22
+
23
+ [project.optional-dependencies]
24
+ anndata = ["anndata>=0.8"]
25
+ test = ["pytest>=7", "anndata>=0.8"]
26
+
27
+ [project.scripts]
28
+ scinspect = "scinspect.cli:main"
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/bhodayasa/scinspect"
32
+ Issues = "https://github.com/bhodayasa/scinspect/issues"
33
+
34
+ [tool.setuptools.dynamic]
35
+ version = { attr = "scinspect.__version__" }
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
42
+ pythonpath = ["src", "tests"]
43
+
44
+ [tool.ruff]
45
+ line-length = 120
46
+ target-version = "py39"
47
+
48
+ [tool.ruff.lint]
49
+ select = ["E", "F", "W", "I", "B", "UP"]
50
+ ignore = ["E501"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -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
@@ -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