scRNA Preprocessing And Clustering
Version Compatibility
Reference examples assume:
scanpy 1.10+
anndata 0.10+
pandas 2.2+
matplotlib 3.8+
Before using code patterns, verify installed versions match the environment:
- Python:
python -c "import scanpy, anndata; print(scanpy.__version__, anndata.__version__)"
- If signatures differ, inspect the installed API and adapt the pattern instead of retrying unchanged.
Overview
Use this skill to turn raw or minimally processed scRNA-seq data into an analysis-ready object with:
- QC-filtered cells and genes
- normalized expression values
- highly variable genes
- PCA and UMAP embeddings
- Leiden clusters
- saved
h5ad artifact for annotation, DE, integration, or trajectory analysis
When To Use This Skill
- raw 10x matrices, filtered count matrices, or
h5ad inputs need standard preprocessing
- the user wants UMAP, clustering, or marker discovery
- downstream tasks depend on a stable single-cell object rather than ad hoc plots
Quick Route
- If the input is already a processed
h5ad, inspect adata.raw, embeddings, cluster columns, and QC columns before rerunning preprocessing.
- If the input is raw counts, do QC first and only normalize after filtering obvious low-quality cells.
- If multiple batches are present, preprocess cleanly first, then consider integration instead of hiding batch effects with aggressive filtering.
Progressive Disclosure
- Read technical_reference.md for QC decision rules, assay caveats, and integration branching.
- Read commands_and_thresholds.md for concrete Scanpy code, default thresholds, and output conventions.
Default Rules
- Keep raw counts recoverable. Prefer
adata.raw = adata.copy() before regression or scaling.
- Report thresholds explicitly. Do not silently drop cells or genes.
- Show QC distributions before applying hard filters.
- Use vector outputs such as
.pdf or .svg for final figures when possible.
Expected Inputs
- 10x directory,
.h5, .h5ad, or count matrix
- cell metadata if available
- species context for mitochondrial or ribosomal gene detection
Expected Outputs
results/processed.h5ad
qc/cell_qc_metrics.tsv
qc/gene_qc_metrics.tsv
figures/qc_violin.pdf
figures/pca_variance_ratio.pdf
figures/umap_leiden.pdf
Preferred Tools
scanpy
anndata
pandas
matplotlib
seaborn
Starter Pattern
import scanpy as sc
adata = sc.read_10x_mtx("counts/")
adata.var_names_make_unique()
adata.var["mt"] = adata.var_names.str.upper().str.startswith("MT-")
sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], inplace=True)
adata = adata[
(adata.obs["n_genes_by_counts"] >= 200)
& (adata.obs["n_genes_by_counts"] <= 6000)
& (adata.obs["pct_counts_mt"] < 15),
:
].copy()
sc.pp.filter_genes(adata, min_cells=3)
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
adata.raw = adata.copy()
sc.pp.highly_variable_genes(adata, n_top_genes=3000, flavor="seurat_v3")
adata = adata[:, adata.var["highly_variable"]].copy()
sc.pp.scale(adata, max_value=10)
sc.tl.pca(adata, svd_solver="arpack")
sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
sc.tl.umap(adata)
sc.tl.leiden(adata, resolution=0.5, key_added="leiden_r05")
adata.write("results/processed.h5ad")
Workflow
1. Load and validate the object
- confirm orientation is cells by genes
- make gene names unique
- record sample IDs and batch labels before merging or filtering
2. Compute QC metrics and inspect distributions
n_genes_by_counts
total_counts
pct_counts_mt
- optional ribosomal or hemoglobin fractions
Plot distributions before filtering. Thresholds vary by chemistry, tissue, and nucleus versus whole-cell assay.
3. Filter cells and genes
Use dataset-aware thresholds. Good first-pass defaults:
min_genes >= 200
max_genes <= 5000-8000 to remove likely doublets in many droplet datasets
pct_counts_mt < 10-20 depending on tissue stress
min_cells >= 3 for genes
4. Normalize, log-transform, and select HVGs
- normalize with
target_sum=1e4
log1p
- select
2000-4000 HVGs
- save raw counts before heavy transformations
5. Reduce dimensions and cluster
- PCA on HVGs
- neighbor graph using
10-30 PCs and 10-30 neighbors as a starting range
- UMAP for visualization
- Leiden across a small resolution grid such as
0.2, 0.5, 0.8, 1.0
6. Export analysis-ready artifacts
Always save:
- processed
h5ad
- QC tables
- cluster assignments
- publication-ready QC and UMAP figures
Output Artifacts
results/processed.h5ad: main reusable AnnData object
results/cluster_assignments.tsv: barcode plus cluster labels
qc/filter_summary.tsv: counts before and after filtering
figures/umap_leiden.pdf: main embedding figure
Quality Review
- Median genes per cell should be plausible for the chemistry and tissue.
- Mitochondrial fraction should not dominate retained cells.
- PCA variance should decay smoothly rather than showing obvious technical axes only.
- UMAP should be reviewed together with QC metrics and batch labels, not alone.
- Cluster labels should not be finalized before marker inspection.
Anti-Patterns
- reprocessing an already integrated object as if it were raw counts
- using a single universal mitochondrial threshold for every tissue
- interpreting UMAP separation as biology before checking batch and QC covariates
- discarding raw counts needed later for DE or pseudobulk
Related Skills
- Cell Annotation
- Cell Communication
- Trajectory And Lineage
- Multiome And scATAC
Optional Supplements
1---2name: scrna-preprocessing-clustering3description: Standard scRNA-seq preprocessing and clustering with Scanpy. Use for QC, normalization, HVG selection, PCA, neighbor graph construction, UMAP, Leiden clustering, and export of an analysis-ready AnnData object.4---5
6# scRNA Preprocessing And Clustering
7
8## Version Compatibility
9
10Reference examples assume:
11
12- `scanpy` 1.10+
13- `anndata` 0.10+
14- `pandas` 2.2+
15- `matplotlib` 3.8+
16
17Before using code patterns, verify installed versions match the environment:
18
19- Python: `python -c "import scanpy, anndata; print(scanpy.__version__, anndata.__version__)"`
20- If signatures differ, inspect the installed API and adapt the pattern instead of retrying unchanged.
21
22## Overview
23
24Use this skill to turn raw or minimally processed scRNA-seq data into an analysis-ready object with:
25
26- QC-filtered cells and genes
27- normalized expression values
28- highly variable genes
29- PCA and UMAP embeddings
30- Leiden clusters
31- saved `h5ad` artifact for annotation, DE, integration, or trajectory analysis
32
33## When To Use This Skill
34
35- raw 10x matrices, filtered count matrices, or `h5ad` inputs need standard preprocessing
36- the user wants UMAP, clustering, or marker discovery
37- downstream tasks depend on a stable single-cell object rather than ad hoc plots
38
39## Quick Route
40
41- If the input is already a processed `h5ad`, inspect `adata.raw`, embeddings, cluster columns, and QC columns before rerunning preprocessing.
42- If the input is raw counts, do QC first and only normalize after filtering obvious low-quality cells.
43- If multiple batches are present, preprocess cleanly first, then consider integration instead of hiding batch effects with aggressive filtering.
44
45## Progressive Disclosure
46
47- Read [technical_reference.md](technical_reference.md) for QC decision rules, assay caveats, and integration branching.
48- Read [commands_and_thresholds.md](commands_and_thresholds.md) for concrete Scanpy code, default thresholds, and output conventions.
49
50## Default Rules
51
52- Keep raw counts recoverable. Prefer `adata.raw = adata.copy()` before regression or scaling.
53- Report thresholds explicitly. Do not silently drop cells or genes.
54- Show QC distributions before applying hard filters.
55- Use vector outputs such as `.pdf` or `.svg` for final figures when possible.
56
57## Expected Inputs
58
59- 10x directory, `.h5`, `.h5ad`, or count matrix
60- cell metadata if available
61- species context for mitochondrial or ribosomal gene detection
62
63## Expected Outputs
64
65- `results/processed.h5ad`
66- `qc/cell_qc_metrics.tsv`
67- `qc/gene_qc_metrics.tsv`
68- `figures/qc_violin.pdf`
69- `figures/pca_variance_ratio.pdf`
70- `figures/umap_leiden.pdf`
71
72## Preferred Tools
73
74- `scanpy`
75- `anndata`
76- `pandas`
77- `matplotlib`
78- `seaborn`
79
80## Starter Pattern
81
82```python
83import scanpy as sc
84
85adata = sc.read_10x_mtx("counts/")
86adata.var_names_make_unique()
87adata.var["mt"] = adata.var_names.str.upper().str.startswith("MT-")
88sc.pp.calculate_qc_metrics(adata, qc_vars=["mt"], inplace=True)
89
90adata = adata[
91 (adata.obs["n_genes_by_counts"] >= 200)
92 & (adata.obs["n_genes_by_counts"] <= 6000)
93 & (adata.obs["pct_counts_mt"] < 15),
94 :
95].copy()
96
97sc.pp.filter_genes(adata, min_cells=3)
98sc.pp.normalize_total(adata, target_sum=1e4)
99sc.pp.log1p(adata)
100adata.raw = adata.copy()
101
102sc.pp.highly_variable_genes(adata, n_top_genes=3000, flavor="seurat_v3")
103adata = adata[:, adata.var["highly_variable"]].copy()
104sc.pp.scale(adata, max_value=10)
105sc.tl.pca(adata, svd_solver="arpack")
106sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
107sc.tl.umap(adata)
108sc.tl.leiden(adata, resolution=0.5, key_added="leiden_r05")
109adata.write("results/processed.h5ad")
110```
111
112## Workflow
113
114### 1. Load and validate the object
115
116- confirm orientation is cells by genes
117- make gene names unique
118- record sample IDs and batch labels before merging or filtering
119
120### 2. Compute QC metrics and inspect distributions
121
122- `n_genes_by_counts`
123- `total_counts`
124- `pct_counts_mt`
125- optional ribosomal or hemoglobin fractions
126
127Plot distributions before filtering. Thresholds vary by chemistry, tissue, and nucleus versus whole-cell assay.
128
129### 3. Filter cells and genes
130
131Use dataset-aware thresholds. Good first-pass defaults:
132
133- `min_genes >= 200`
134- `max_genes <= 5000-8000` to remove likely doublets in many droplet datasets
135- `pct_counts_mt < 10-20` depending on tissue stress
136- `min_cells >= 3` for genes
137
138### 4. Normalize, log-transform, and select HVGs
139
140- normalize with `target_sum=1e4`
141- `log1p`
142- select `2000-4000` HVGs
143- save raw counts before heavy transformations
144
145### 5. Reduce dimensions and cluster
146
147- PCA on HVGs
148- neighbor graph using `10-30` PCs and `10-30` neighbors as a starting range
149- UMAP for visualization
150- Leiden across a small resolution grid such as `0.2`, `0.5`, `0.8`, `1.0`
151
152### 6. Export analysis-ready artifacts
153
154Always save:
155
156- processed `h5ad`
157- QC tables
158- cluster assignments
159- publication-ready QC and UMAP figures
160
161## Output Artifacts
162
163- `results/processed.h5ad`: main reusable AnnData object
164- `results/cluster_assignments.tsv`: barcode plus cluster labels
165- `qc/filter_summary.tsv`: counts before and after filtering
166- `figures/umap_leiden.pdf`: main embedding figure
167
168## Quality Review
169
170- Median genes per cell should be plausible for the chemistry and tissue.
171- Mitochondrial fraction should not dominate retained cells.
172- PCA variance should decay smoothly rather than showing obvious technical axes only.
173- UMAP should be reviewed together with QC metrics and batch labels, not alone.
174- Cluster labels should not be finalized before marker inspection.
175
176## Anti-Patterns
177
178- reprocessing an already integrated object as if it were raw counts
179- using a single universal mitochondrial threshold for every tissue
180- interpreting UMAP separation as biology before checking batch and QC covariates
181- discarding raw counts needed later for DE or pseudobulk
182
183## Related Skills
184
185- Cell Annotation
186- Cell Communication
187- Trajectory And Lineage
188- Multiome And scATAC
189
190## Optional Supplements
191
192- `anndata`
193- `scanpy`