Before using code patterns, verify installed versions match. If versions differ:
Python: pip show <package> then help(module.function) to check signatures
R: packageVersion('<pkg>') then ?function_name to verify parameters
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
Automated Cell Type Annotation
CellTypist (Python)
Goal: Automatically annotate cell types using a pre-trained or custom CellTypist model.
Approach: Load a reference model, predict cell types with majority voting for cluster-level consensus, and add predictions to AnnData.
"Automatically label my cell types" → Apply a trained classifier to assign cell type identities based on transcriptomic similarity to a reference atlas.
import celltypist
import scanpy as sc
adata = sc.read_h5ad('adata_processed.h5ad')
# List available models
celltypist.models.models_description()
# Download model
celltypist.models.download_models(model='Immune_All_Low.pkl')
# Load model
model = celltypist.models.Model.load(model='Immune_All_Low.pkl')
# Predict cell types
predictions = celltypist.annotate(adata, model=model, majority_voting=True)
# Add predictions to adata
adata = predictions.to_adata()
# Access predictions
adata.obs['cell_type_celltypist'] = adata.obs['majority_voting']
adata.obs['cell_type_confidence'] = adata.obs['conf_score']
# Visualize
sc.pl.umap(adata, color=['cell_type_celltypist', 'conf_score'])
CellTypist with Custom Model
Goal: Train a custom CellTypist model on a reference dataset for domain-specific annotation.
Approach: Train a logistic regression classifier on labeled reference data with feature selection, then apply to query data.
# Train custom model
new_model = celltypist.train(adata_reference, labels='cell_type', n_jobs=10,
feature_selection=True, use_SGD=True)
# Save model
new_model.write('custom_model.pkl')
# Use custom model
predictions = celltypist.annotate(adata_query, model='custom_model.pkl')
SingleR (R)
Goal: Annotate cell types by correlating expression profiles against curated reference datasets.
Approach: Compare each cell's expression to reference transcriptomes using SingleR's correlation-based assignment, with pruning for low-confidence calls.