How scverse/scanpy works
1. Repository purpose and top-level shape
This is a Python library for single-cell analysis, not an application server. The runtime package lives under src/scanpy, with a small CLI entrypoint (__main__.py, cli.py) and a large surrounding ecosystem for docs, tests, benchmarks, and release automation.
2. Core architectural boundary: AnnData-centric API
Scanpy is built around the anndata.AnnData data structure. Most functions accept an AnnData object, read from standardized slots like X, obs, var, obsm, obsp, and write results back into those same slots. This is the main internal/external boundary of the project.
3. Configuration, logging, and compatibility
Global behavior is controlled by src/scanpy/_settings and src/scanpy/logging.py, with shared constants and compatibility helpers in _keys.py, _compat.py, and _utils. These modules provide cross-cutting concerns such as verbosity, presets, feature flags, and backward-compatibility shims.
4. Data ingestion and persistence
readwrite.py, datasets/, and queries/ cover loading and accessing data from on-disk formats and remote/curated sources. The repo includes bundled example datasets and simulator inputs, plus support for common single-cell formats like h5ad, zarr, and 10x Genomics matrices. This layer is the ingress/egress boundary between files or services and in-memory AnnData.
5. Preprocessing subsystem
src/scanpy/preprocessing contains the data-cleaning and feature-engineering pipeline: QC metrics, filtering, normalization, scaling, highly variable gene selection, combat batch correction, PCA, Scrublet, Harmony integration, and recipe-style pipelines. There are also distributed/Dask-aware paths and deprecated compatibility modules, showing that preprocessing is both a core path and a migration-sensitive area.
6. Neighborhood graph construction
src/scanpy/neighbors builds k-nearest-neighbor graphs and connectivities from embeddings or expression matrices. The resulting graph structures are stored back into AnnData and reused by downstream clustering, manifold learning, and trajectory methods. The presence of a RAPIDS backend indicates an alternate GPU-accelerated execution path.
7. Analysis and “tools” layer
src/scanpy/tools is the main algorithmic analysis layer. It contains clustering (leiden, louvain), trajectory and manifold methods (dpt, diffmap, paga, draw_graph, umap, tsne), gene ranking and scoring (rank_genes_groups, score_genes), ingestion/integration (ingest), and simulation helpers. This layer consumes preprocessed data and neighbor graphs and produces embeddings, clusters, pseudotime, scores, and differential-expression summaries.
8. Visualization subsystem
src/scanpy/plotting turns analysis results into publication-style plots. It is tightly coupled to AnnData annotations and to outputs from preprocessing/tools, with specialized plot types such as dot plots, matrix plots, stacked violins, embedding/scatter plots, PAGA figures, QC plots, and spatial plots. Matplotlib is the main rendering backend, and the module structure reflects a clear separation between plot primitives, embedded plots, and plot-specific utilities.
9. Metrics and derived accessors
src/scanpy/metrics provides graph/spatial statistics like Moran’s I and Geary’s C. src/scanpy/get exposes convenience accessors for aggregated values and kernels. These modules are small but important because they expose reusable derived computations without forcing callers into the higher-level tools pipeline.
10. Experimental and external integration layers
src/scanpy/experimental contains newer preprocessing functionality, while src/scanpy/external wraps or delegates to third-party methods such as BBKNN, MAGIC, MNN correction, Scanorama, PHATE, Palantir, Phenograph, SAM, TriMap, and Wishbone. These folders are explicit integration boundaries: Scanpy provides a unified API while the actual algorithms may live in external packages.
11. Testing architecture
The test suite is extensive and artifact-driven. tests/ includes unit and integration tests, notebook-based regression checks, and many image baselines under tests/_images, indicating that plot stability is part of the contract. src/testing/scanpy contains reusable fixtures/helpers for the test framework.
12. Documentation, tutorials, and release process
docs/ is a first-class subsystem with API docs, tutorials, how-to guides, and custom Sphinx extensions. benchmarks/ uses ASV for performance tracking, and .github/workflows plus ci/ automate linting, test runs, docs, benchmarking, and publishing. This repo is maintained as a mature scientific library with strong emphasis on reproducibility, backward compatibility, and visual regression testing.
13. Typical data flow through the library
A common flow is: load data into AnnData → preprocess and normalize → compute PCA/neighbors → cluster or infer trajectories → rank marker genes / compute metrics → visualize results. Most modules either transform AnnData in place or read from its stored annotations, which makes AnnData the central integration point for the whole architecture.
Main entry points: scanpy/__init__.py AnnData API · preprocessing/__init__.py Preprocess · tools/__init__.py Tools · plotting/__init__.py Plotting
Components 25
Core API
Public package surface centered on AnnData and shared runtime behavior.
- AnnData API · Primary boundary for all read/transform/write operations on scanpy data.
src/scanpy/__init__.py - CLI · Small command-line entrypoint for invoking package functionality.
src/scanpy/cli.py - Settings · Global configuration, presets, and verbosity controls.
src/scanpy/_settings/__init__.py - Logging · Shared logging and message formatting used across the library.
src/scanpy/logging.py - Compat utils · Version shims, shared keys, and low-level utility helpers.
src/scanpy/_compat.py
Data IO
Loading, curated datasets, and remote queries that bridge files/services to AnnData.
- Read/write · Parsing and persisting common single-cell file formats and backed data.
src/scanpy/readwrite.py - Datasets · Packaged example datasets and dataset-loading helpers.
src/scanpy/datasets/__init__.py - Queries · Access helpers for curated or remote data sources.
src/scanpy/queries/__init__.py
Preprocessing
Cleaning, normalization, dimensionality reduction, and batch-correction routines.
- Preprocess · Main preprocessing pipeline for QC, filtering, normalization, and scaling.
src/scanpy/preprocessing/__init__.py - HVG selection · Highly variable gene selection and related filtering logic.
src/scanpy/preprocessing/_highly_variable_genes.py - PCA · Principal-component analysis including dask and compatibility paths.
src/scanpy/preprocessing/_pca/__init__.py - Scrublet · Doublet scoring pipeline and sparse helpers.
src/scanpy/preprocessing/_scrublet/__init__.py
Analysis
Graph construction and higher-level analytical methods built on preprocessed AnnData.
- Neighbors · kNN graph and connectivity construction with CPU and GPU backends.
src/scanpy/neighbors/__init__.py - Tools · Clustering, manifold learning, pseudotime, gene ranking, and simulation.
src/scanpy/tools/__init__.py - PAGA · Graph abstraction and trajectory-aware analysis over neighbor graphs.
src/scanpy/tools/_paga.py - UMAP · Nonlinear embedding generation from neighbor structure.
src/scanpy/tools/_umap.py
Visualization
Plotting and figure generation for analysis results and annotations.
- Plotting · Figure generation from AnnData annotations and analysis outputs.
src/scanpy/plotting/__init__.py - Plot tools · Embedding, scatter, and PAGA-specific plotting primitives.
src/scanpy/plotting/_tools/__init__.py
Extensions
Experimental features and wrappers around external algorithms.
- Experimental · Newer preprocessing functionality under active evolution.
src/scanpy/experimental/__init__.py - External · Wrappers around third-party methods exposed through the Scanpy API.
src/scanpy/external/__init__.py
Support
Metrics, accessors, packaging helpers, and test infrastructure.
Docs & Ops
Documentation, tutorials, benchmarks, CI, and release automation.
- Docs · User guides, API docs, tutorials, and Sphinx extensions.
docs/index.md - Benchmarks · ASV-based performance tracking and benchmark workloads.
benchmarks/asv.conf.json
Connections 29
- AnnData API → Read/write: load/save · Convert between files and in-memory AnnData.
- AnnData API → Datasets: examples · Provide packaged datasets and loaders.
- AnnData API → Queries: fetch · Access curated or remote sources into AnnData-oriented workflows.
- Settings → Logging: controls · Configuration influences verbosity and diagnostics.
- Compat utils → Preprocess: supports · Shared compatibility and helper code used across preprocessing.
- Read/write → AnnData API: returns · Populate standard AnnData slots from input formats.
- Datasets → AnnData API: seed data · Ship example AnnData inputs for tutorials and tests.
- Queries → AnnData API: materialize · Materialize queried data into AnnData-centric workflows.
- Preprocess → HVG selection: includes · Feature selection is a core preprocessing stage.
- Preprocess → PCA: includes · Dimensionality reduction is part of preprocessing.
- Preprocess → Scrublet: includes · Doublet detection is exposed within preprocessing.
- Preprocess → AnnData API: mutates · Read and write standardized slots on AnnData.
- PCA → Neighbors: feeds · Low-dimensional coordinates feed graph construction.
- Neighbors → Tools: feeds · Neighbor graphs are consumed by analysis methods.
- Tools → PAGA: contains · Trajectory and graph abstraction methods live in tools.
- Tools → UMAP: contains · Embedding methods are part of the analysis layer.
- Tools → AnnData API: writes · Store clusters, embeddings, scores, and results back into AnnData.
- Neighbors → AnnData API: stores graph · Persist kNN/connectivity structures in AnnData.
- Tools → Plotting: visualizes · Downstream analysis results are rendered by plotting.
- Plotting → Plot tools: uses · High-level plotting delegates to specialized plot primitives.
- Plotting → AnnData API: reads · Plots are driven by AnnData annotations and embeddings.
- Metrics → AnnData API: derives from · Compute statistics from stored graphs or spatial structure.
- Getters → AnnData API: reads · Convenience accessors extract derived values from AnnData.
- Experimental → Preprocess: extends · Experimental preprocessing adds newer pipeline variants.
- External → Tools: wraps · Expose third-party analysis methods behind Scanpy APIs.
- External → Preprocess: wraps · Some third-party integrations act as preprocessing helpers.
- Testing → Plotting: regresses · Reusable test infrastructure supports image and notebook checks.
- Docs → Plotting: documents · Docs cover plotting APIs and tutorials.
- Benchmarks → Tools: profiles · Performance suite measures core preprocessing and analysis paths.