K-Dense-AI/scientific-agent-skills / skills/scanpy
scanpy
VerifiedPerforms Scanpy single-cell RNA-seq QC, normalization, HVG selection, PCA/UMAP/t-SNE, clustering, exploratory marker ranking, pseudobulk preparation, visualization, and Seurat or SingleCellExperiment RDS conversion to h5ad. Applies to established exploratory scRNA-seq workflows with explicit count and expression provenance; complementary skills cover scvi-tools models and AnnData format details.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 19.8 KB |
| assets/analysis_template.py | script | 10.0 KB |
| assets/celltype_mapping.json | config | 184 B |
| assets/gene_signatures.json | config | 355 B |
| assets/pipeline_config.json | config | 380 B |
| references/analysis_workflow.md | markdown | 7.6 KB |
| references/api_reference.md | markdown | 9.1 KB |
| references/plotting_guide.md | markdown | 10.5 KB |
| references/r_interop.md | markdown | 11.8 KB |
| references/standard_workflow.md | markdown | 7.0 KB |
| references/upstream-review.md | markdown | 8.3 KB |
| scripts/_common.py | script | 10.0 KB |
| scripts/annotate.py | script | 3.7 KB |
| scripts/batch_correct.py | script | 3.1 KB |
| scripts/cluster.py | script | 2.5 KB |
| scripts/convert.py | script | 1.5 KB |
| scripts/find_markers.py | script | 4.3 KB |
| scripts/inspect_data.py | script | 3.1 KB |
| scripts/plot.py | script | 3.6 KB |
| scripts/preprocess.py | script | 3.5 KB |
| scripts/pseudobulk.py | script | 4.6 KB |
| scripts/qc_analysis.pyexecutable | script | 5.1 KB |
| scripts/reduce_dimensions.py | script | 2.8 KB |
| scripts/run_pipeline.py | script | 9.4 KB |
| scripts/score_genes.py | script | 3.9 KB |
| scripts/subset.py | script | 2.6 KB |
references/api_reference.md
View on GitHub# Scanpy API Quick Reference
Reviewed for Scanpy 1.12.4 / AnnData 0.13.4 on 2026-10-01. These snippets are
illustrative and require the named genes, groups and prior results to exist.
Use the tested CLI workflow for a runnable starting point. Counts, normalized
expression and `.raw` have distinct roles; see [upstream-review.md](upstream-review.md).
Quick reference for commonly used scanpy functions organized by module.
## Import Convention
```python
import scanpy as sc
```
## Reading and Writing Data (sc.read_*)
### Reading Functions
```python
sc.read_10x_h5(filename) # Read 10X HDF5 file
sc.read_10x_mtx(path) # Read 10X mtx directory
sc.read_h5ad(filename) # Read h5ad (AnnData) file
sc.read_csv(filename) # Read CSV file
sc.read_excel(filename, sheet=0) # Requires a sheet and Excel reader dependency
sc.read_loom(filename) # Read loom file
sc.read_text(filename) # Read text file
sc.read_visium(path) # Deprecated; use spatialdata-io for new workflows
```
### Writing Functions
```python
adata.write_h5ad(filename) # Write to h5ad format
adata.write_csvs(dirname) # Write to CSV files
adata.write_loom(filename) # Write to loom format
adata.write_zarr(filename) # Write to zarr format
```
## Preprocessing (sc.pp.*)
### Quality Control
```python
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], percent_top=None, inplace=True)
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)
sc.pp.scrublet(adata) # Doublet detection (core since 1.10)
sc.pp.scrublet_simulate_doublets(adata) # Simulate doublets for benchmarking
```
### Normalization and Transformation
```python
sc.pp.normalize_total(adata, target_sum=1e4) # Normalize to target sum
sc.pp.log1p(adata) # Log(x + 1) transformation
sc.pp.sqrt(adata) # Square root transformation
```
### Feature Selection
```python
sc.pp.highly_variable_genes(adata, min_mean=0.0125, max_mean=3, min_disp=0.5)
sc.pp.highly_variable_genes(adata, flavor='seurat_v3', n_top_genes=2000)
# Dask support is experimental; v3 flavors gained support in 1.12.
```
### Scaling and Regression
```python
sc.pp.scale(adata, max_value=10) # Scale to unit variance
sc.pp.regress_out(adata, ['total_counts', 'pct_counts_mt']) # Regress out unwanted variation
```
### Dimensionality Reduction (Preprocessing)
```python
sc.pp.pca(adata, n_comps=50) # Principal component analysis
sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40) # Compute neighborhood graph
sc.pp.neighbors(adata, method='jaccard') # Jaccard connectivities (scanpy 1.12)
```
### Batch Correction
```python
sc.pp.combat(adata, key='batch') # ComBat batch correction
```
## Tools (sc.tl.*)
### Dimensionality Reduction
```python
sc.tl.pca(adata, svd_solver='arpack') # PCA
sc.tl.umap(adata) # UMAP embedding
sc.tl.tsne(adata) # t-SNE embedding
sc.tl.diffmap(adata) # Diffusion map
sc.tl.draw_graph(adata, layout='fa') # Force-directed graph
```
### Clustering
```python
sc.tl.leiden(adata, resolution=0.5) # Leiden clustering (recommended)
# sc.tl.louvain(adata, resolution=0.5) # Deprecated in scanpy 1.12 — use leiden
# K-means is not a scanpy.tl function; use sklearn.cluster.KMeans explicitly.
```
### Marker Genes and Differential Expression
```python
sc.tl.rank_genes_groups(adata, groupby='leiden', method='wilcoxon')
sc.tl.rank_genes_groups(adata, groupby='leiden', method='t-test')
sc.tl.rank_genes_groups(adata, groupby='leiden', method='logreg')
# Get results as dataframe
sc.get.rank_genes_groups_df(adata, group='0')
# Exploratory only — per-cell tests inflate significance (often making p-values too small); pseudobulk for rigorous DE
```
### Aggregation (Pseudobulk)
```python
sc.get.aggregate(adata, by='cell_type', func='sum', layer='counts')
pb = sc.get.aggregate(adata, by=['sample', 'cell_type'], func='sum', layer='counts')
counts = pb.layers['sum'] # cells/groups x genes; pb.X is None
# Keep biological replicate metadata; PyDESeq2 expects sample rows and gene columns.
```
### Trajectory Inference
```python
sc.tl.paga(adata, groups='leiden') # PAGA trajectory
sc.tl.diffmap(adata, n_comps=10) # choose fewer for small datasets
sc.tl.dpt(adata, n_dcs=10) # Diffusion pseudotime
```
### Gene Scoring
```python
sc.tl.score_genes(adata, gene_list, score_name='score')
sc.tl.score_genes_cell_cycle(adata, s_genes=s_genes, g2m_genes=g2m_genes)
```
### Embeddings and Projections
```python
sc.tl.ingest(adata, adata_ref) # Map to reference
sc.tl.embedding_density(adata, basis='umap', groupby='leiden')
```
## Plotting (sc.pl.*)
### Basic Embeddings
```python
sc.pl.umap(adata, color='leiden') # UMAP plot
sc.pl.tsne(adata, color='gene_name') # t-SNE plot
sc.pl.pca(adata, color='leiden') # PCA plot
sc.pl.diffmap(adata, color='leiden') # Diffusion map plot
```
### Heatmaps and Dot Plots
```python
sc.pl.heatmap(adata, var_names=genes, groupby='leiden')
sc.pl.dotplot(adata, var_names=genes, groupby='leiden')
sc.pl.matrixplot(adata, var_names=genes, groupby='leiden')
sc.pl.stacked_violin(adata, var_names=genes, groupby='leiden')
```
### Violin and Scatter Plots
```python
sc.pl.violin(adata, keys=['gene1', 'gene2'], groupby='leiden')
sc.pl.scatter(adata, x='gene1', y='gene2', color='leiden')
```
### Marker Gene Visualization
```python
sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False)
sc.pl.rank_genes_groups_violin(adata, groups='0')
sc.pl.rank_genes_groups_heatmap(adata, n_genes=10)
sc.pl.rank_genes_groups_dotplot(adata, n_genes=5)
```
### Trajectory Visualization
```python
sc.pl.paga(adata, color='leiden') # PAGA graph
# Legacy branch-order plot requires dpt_order_indices/dpt_changepoints,
# which default n_branchings=0 does not create. Prefer the pseudotime UMAP.
# sc.pl.dpt_timeseries(adata) # DPT timeseries
```
### QC Plots
```python
sc.pl.highest_expr_genes(adata, n_top=20)
sc.pl.violin(adata, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'])
sc.pl.scatter(adata, x='total_counts', y='n_genes_by_counts')
```
### Advanced Plots
```python
sc.pl.dendrogram(adata, groupby='leiden')
sc.pl.correlation_matrix(adata, groupby='leiden')
sc.pl.tracksplot(adata, var_names=genes, groupby='leiden')
```
## Common Parameters
### Color Parameters
- `color`: Variable(s) to color by (gene name, obs column)
- `use_raw`: Use `.raw` attribute of adata
- `palette`: Color palette to use
- `vmin`, `vmax`: Color scale limits
### Layout Parameters
- `basis`: Embedding basis ('umap', 'tsne', 'pca', etc.)
- `legend_loc`: Legend location ('on data', 'right margin', etc.)
- `size`: Point size
- `alpha`: Point transparency
### Saving Parameters
- `show`: Whether to show plot
- Prefer `sc.settings.autosave` + `sc.settings.figdir` over deprecated `save=`
## AnnData Structure
```python
adata.X # Expression matrix (cells × genes)
adata.obs # Cell annotations (DataFrame)
adata.var # Gene annotations (DataFrame)
adata.uns # Unstructured annotations (dict)
adata.obsm # Multi-dimensional cell annotations (e.g., PCA, UMAP)
adata.varm # Multi-dimensional gene annotations
adata.layers # Additional data layers
adata.raw # Snapshot of X/var; not necessarily counts
# Access
adata.obs_names # Cell barcodes
adata.var_names # Gene names
adata.shape # (n_cells, n_genes)
# Slicing
adata[cell_indices, gene_indices]
adata[:, adata.var_names.isin(gene_list)]
adata[adata.obs['leiden'] == '0', :]
```
## Settings
```python
sc.settings.verbosity = 3 # 0=error, 1=warning, 2=info, 3=hint
sc.set_figure_params(dpi=80, facecolor='white')
sc.settings.autoshow = False # Don't show plots automatically
sc.settings.autosave = True # Save figures to figdir (preferred over save=)
sc.settings.figdir = './figures/' # Figure directory
sc.settings.file_format_figs = 'pdf' # Output format when autosave is True
sc.settings.cachedir = './cache/' # Cache directory
sc.settings.n_jobs = 8 # Number of parallel jobs
```
Note: the `save=` parameter on individual `sc.pl.*` functions is deprecated in scanpy 1.12. Use `sc.settings.autosave` and `sc.settings.figdir` instead.
## Useful Utilities
```python
sc.logging.print_header() # Print version information
sc.logging.print_memory_usage() # Print memory usage
adata.copy() # Create a copy of AnnData object
import anndata as ad
ad.concat({'sample1': adata1, 'sample2': adata2}, label='sample', join='inner')
# Align gene IDs first; outer joins fill absent sparse features with zero.
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |