Single Cell Rna Qc
AnthropicOfficialPublished by Anthropic
- Skill
- Tool integration
- Science and research
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive toolkit for performing quality control on single-cell RNA-seq data in .h5ad or .h5 formats. It implements scverse and scanpy best practices, utilizing Median Absolute Deviation (MAD)-based filtering to identify outliers while remaining permissive enough to preserve rare cell populations. The skill offers both a ready-to-use command-line pipeline for standard analysis and a modular Python library for researchers requiring custom filtering logic or specific workflow integration.
What it does
- Calculates essential QC metrics including count depth, gene detection, and mitochondrial/ribosomal/hemoglobin content.
- Applies MAD-based outlier detection for robust, data-driven filtering of low-quality cells.
- Generates comprehensive visualizations to assess data quality before and after filtering.
- Supports standard 10X Genomics and AnnData file formats.
- Provides modular utility functions for building custom, non-standard QC workflows.
- Includes guidance on species-specific gene patterns and tissue-specific QC considerations.
When to use it
- When you need to perform standard quality control on single-cell RNA-seq datasets.
- When you want to filter low-quality cells or debris while following established scverse best practices.
- When you need to generate visual reports to justify filtering decisions.
- When you require a flexible, programmatic approach to QC for complex or tissue-specific experiments.
- When you need to assess the impact of different filtering thresholds on your dataset.
Advantages
- Data-driven filtering using MAD reduces reliance on arbitrary, fixed thresholds.
- Permissive defaults help prevent the accidental loss of rare but viable cell populations.
- Automated visualization helps quickly identify technical artifacts or batch effects.
- Modular design allows for seamless integration into larger bioinformatics pipelines.
- Supports both quick, automated processing and highly granular, custom analysis.
Usage examples
- “Run the standard QC pipeline on my 10X Genomics data file named raw_data.h5.”
- The agent executes the qc_analysis.py script, which calculates metrics, applies MAD-based filtering, and generates a folder containing filtered data and QC plots.
- “I need to calculate QC metrics for my AnnData object but I do not want to filter any cells yet.”
- The agent uses the modular qc_core.py functions to compute metrics and generate summary plots without applying the filtering step.
- “How do I apply a stricter mitochondrial threshold for my specific tissue sample?”
- The agent provides instructions on using the --mt-threshold parameter in the command-line tool or demonstrates how to use apply_hard_threshold in a custom script.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/anthropics/single-cell-rna-qc/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip single-cell-rna-qc.zip -d .agents/skills
Documentation by Anthropic
Single-Cell RNA-seq Quality Control
Automated QC workflow for single-cell RNA-seq data following scverse best practices.
When to Use This Skill
Use when users:
Request quality control or QC on single-cell RNA-seq data
Want to filter low-quality cells or assess data quality
Need QC visualizations or metrics
Ask to follow scverse/scanpy best practices
Request MAD-based filtering or outlier detection
Supported input formats:
.h5adfiles (AnnData format from scanpy/Python workflows).h5files (10X Genomics Cell Ranger output)
Default recommendation: Use Approach 1 (complete pipeline) unless the user has specific custom requirements or explicitly requests non-standard filtering logic.
Approach 1: Complete QC Pipeline (Recommended for Standard Workflows)
For standard QC following scverse best practices, use the convenience script scripts/qc_analysis.py:
python3 scripts/qc_analysis.py input.h5ad
# or for 10X Genomics .h5 files:
python3 scripts/qc_analysis.py raw_feature_bc_matrix.h5The script automatically detects the file format and loads it appropriately.
When to use this approach:
Standard QC workflow with adjustable thresholds (all cells filtered the same way)
Batch processing multiple datasets
Quick exploratory analysis
User wants the "just works" solution
Requirements: anndata, scanpy, scipy, matplotlib, seaborn, numpy
Parameters:
Customize filtering thresholds and gene patterns using command-line parameters:
--output-dir- Output directory--mad-counts,--mad-genes,--mad-mt- MAD thresholds for counts/genes/MT%--mt-threshold- Hard mitochondrial % cutoff--min-cells- Gene filtering threshold--mt-pattern,--ribo-pattern,--hb-pattern- Gene name patterns for different species
Use --help to see current default values.
Outputs:
All files are saved to <input_basename>_qc_results/ directory by default (or to the directory specified by --output-dir):
qc_metrics_before_filtering.png- Pre-filtering visualizationsqc_filtering_thresholds.png- MAD-based threshold overlaysqc_metrics_after_filtering.png- Post-filtering quality metrics<input_basename>_filtered.h5ad- Clean, filtered dataset ready for downstream analysis<input_basename>_with_qc.h5ad- Original data with QC annotations preserved
If copying outputs for user access, copy individual files (not the entire directory) so users can preview them directly.
Workflow Steps
The script performs the following steps:
Calculate QC metrics - Count depth, gene detection, mitochondrial/ribosomal/hemoglobin content
Apply MAD-based filtering - Permissive outlier detection using MAD thresholds for counts/genes/MT%
Filter genes - Remove genes detected in few cells
Generate visualizations - Comprehensive before/after plots with threshold overlays
Approach 2: Modular Building Blocks (For Custom Workflows)
For custom analysis workflows or non-standard requirements, use the modular utility functions from scripts/qc_core.py and scripts/qc_plotting.py:
# Run from scripts/ directory, or add scripts/ to sys.path if needed
import anndata as ad
from qc_core import calculate_qc_metrics, detect_outliers_mad, filter_cells
from qc_plotting import plot_qc_distributions # Only if visualization needed
adata = ad.read_h5ad('input.h5ad')
calculate_qc_metrics(adata, inplace=True)
# ... custom analysis logic hereWhen to use this approach:
Different workflow needed (skip steps, change order, apply different thresholds to subsets)
Conditional logic (e.g., filter neurons differently than other cells)
Partial execution (only metrics/visualization, no filtering)
Integration with other analysis steps in a larger pipeline
Custom filtering criteria beyond what command-line params support
Available utility functions:
From qc_core.py (core QC operations):
calculate_qc_metrics(adata, mt_pattern, ribo_pattern, hb_pattern, inplace=True)- Calculate QC metrics and annotate adatadetect_outliers_mad(adata, metric, n_mads, verbose=True)- MAD-based outlier detection, returns boolean maskapply_hard_threshold(adata, metric, threshold, operator='>', verbose=True)- Apply hard cutoffs, returns boolean maskfilter_cells(adata, mask, inplace=False)- Apply boolean mask to filter cellsfilter_genes(adata, min_cells=20, min_counts=None, inplace=True)- Filter genes by detectionprint_qc_summary(adata, label='')- Print summary statistics
From qc_plotting.py (visualization):
plot_qc_distributions(adata, output_path, title)- Generate comprehensive QC plotsplot_filtering_thresholds(adata, outlier_masks, thresholds, output_path)- Visualize filtering thresholdsplot_qc_after_filtering(adata, output_path)- Generate post-filtering plots
Example custom workflows:
Example 1: Only calculate metrics and visualize, don't filter yet
adata = ad.read_h5ad('input.h5ad')
calculate_qc_metrics(adata, inplace=True)
plot_qc_distributions(adata, 'qc_before.png', title='Initial QC')
print_qc_summary(adata, label='Before filtering')Example 2: Apply only MT% filtering, keep other metrics permissive
adata = ad.read_h5ad('input.h5ad')
calculate_qc_metrics(adata, inplace=True)
# Only filter high MT% cells
high_mt = apply_hard_threshold(adata, 'pct_counts_mt', 10, operator='>')
adata_filtered = filter_cells(adata, ~high_mt)
adata_filtered.write('filtered.h5ad')Example 3: Different thresholds for different subsets
adata = ad.read_h5ad('input.h5ad')
calculate_qc_metrics(adata, inplace=True)
# Apply type-specific QC (assumes cell_type metadata exists)
neurons = adata.obs['cell_type'] == 'neuron'
other_cells = ~neurons
# Neurons tolerate higher MT%, other cells use stricter threshold
neuron_qc = apply_hard_threshold(adata[neurons], 'pct_counts_mt', 15, operator='>')
other_qc = apply_hard_threshold(adata[other_cells], 'pct_counts_mt', 8, operator='>')Best Practices
Be permissive with filtering - Default thresholds intentionally retain most cells to avoid losing rare populations
Inspect visualizations - Always review before/after plots to ensure filtering makes biological sense
Consider dataset-specific factors - Some tissues naturally have higher mitochondrial content (e.g., neurons, cardiomyocytes)
Check gene annotations - Mitochondrial gene prefixes vary by species (mt- for mouse, MT- for human)
Iterate if needed - QC parameters may need adjustment based on the specific experiment or tissue type
Reference Materials
For detailed QC methodology, parameter rationale, and troubleshooting guidance, see references/scverse_qc_guidelines.md. This reference provides:
Detailed explanations of each QC metric and why it matters
Rationale for MAD-based thresholds and why they're better than fixed cutoffs
Guidelines for interpreting QC visualizations (histograms, violin plots, scatter plots)
Species-specific considerations for gene annotations
When and how to adjust filtering parameters
Advanced QC considerations (ambient RNA correction, doublet detection)
Load this reference when users need deeper understanding of the methodology or when troubleshooting QC issues.
Next Steps After QC
Typical downstream analysis steps:
Ambient RNA correction (SoupX, CellBender)
Doublet detection (scDblFinder)
Normalization (log-normalize, scran)
Feature selection and dimensionality reduction
Clustering and cell type annotation
Files
- ATTRIBUTION.mdAdded by AutoGineer964 B
- LICENSE.txt10.0 KiB
- SKILL.md7.8 KiB
- references/scverse_qc_guidelines.md7.4 KiB
- scripts/qc_analysis.pyScript9.3 KiB
- scripts/qc_core.pyScript6.5 KiB
- scripts/qc_plotting.pyScript8.3 KiB
scripts/qc_core.py
#!/usr/bin/env python3
"""
Core utility functions for single-cell RNA-seq quality control.
This module provides building blocks for metrics calculation and filtering
while following scverse best practices from:
https://www.sc-best-practices.org/preprocessing_visualization/quality_control.html
"""
import anndata as ad
import scanpy as sc
import numpy as np
from scipy.stats import median_abs_deviation
def calculate_qc_metrics(adata, mt_pattern='mt-,MT-', ribo_pattern='Rpl,Rps,RPL,RPS',
hb_pattern='^Hb[^(p)]|^HB[^(P)]', inplace=True):
"""
Calculate QC metrics for single-cell RNA-seq data.
Parameters
----------
adata : AnnData
Annotated data matrix
mt_pattern : str
Comma-separated mitochondrial gene prefixes (default: 'mt-,MT-')
ribo_pattern : str
Comma-separated ribosomal gene prefixes (default: 'Rpl,Rps,RPL,RPS')
hb_pattern : str
Regex pattern for hemoglobin genes (default: '^Hb[^(p)]|^HB[^(P)]')
inplace : bool
Modify adata in place (default: True)
Returns
-------
AnnData or None
If inplace=False, returns modified AnnData. Otherwise modifies in place.
"""
if not inplace:
adata = adata.copy()
# Identify gene categories
mt_prefixes = tuple(mt_pattern.split(','))
adata.var['mt'] = adata.var_names.str.startswith(mt_prefixes)
ribo_prefixes = tuple(ribo_pattern.split(','))
adata.var['ribo'] = adata.var_names.str.startswith(ribo_prefixes)
adata.var['hb'] = adata.var_names.str.match(hb_pattern)
# Calculate QC metrics
sc.pp.calculate_qc_metrics(
adata,
qc_vars=['mt', 'ribo', 'hb'],
percent_top=None,
log1p=False,
inplace=True
)
if not inplace:
return adata
def detect_outliers_mad(adata, metric, n_mads, verbose=True):
"""
Detect outliers using Median Absolute Deviation (MAD).
Parameters
----------
adata : AnnData
Annotated data matrix with QC metrics
metric : str
Column name in adata.obs to use for outlier detection
n_mads : float
Number of MADs to use as threshold
verbose : bool
Print outlier statistics (default: True)
Returns
-------
np.ndarray
Boolean mask where True indicates outliers
"""
metric_values = adata.obs[metric]
median = np.median(metric_values)
mad = median_abs_deviation(metric_values)
# Calculate bounds
lower = median - n_mads * mad
upper = median + n_mads * mad
# Identify outliers
outlier_mask = (metric_values < lower) | (metric_values > upper)
if verbose:
print(f" {metric}:")
print(f" Median: {median:.2f}, MAD: {mad:.2f}")
print(f" Bounds: [{lower:.2f}, {upper:.2f}] ({n_mads} MADs)")
print(f" Outliers: {outlier_mask.sum()} cells ({outlier_mask.sum()/len(metric_values)*100:.2f}%)")
return outlier_mask
def apply_hard_threshold(adata, metric, threshold, operator='>', verbose=True):
"""
Apply a hard threshold filter.
Parameters
----------
adata : AnnData
Annotated data matrix
metric : str
Column name in adata.obs to filter on
threshold : float
Threshold value
operator : str
Comparison operator: '>', '<', '>=', '<=' (default: '>')
verbose : bool
Print filtering statistics (default: True)
Returns
-------
np.ndarray
Boolean mask where True indicates cells to filter out
"""
metric_values = adata.obs[metric]
if operator == '>':
mask = metric_values > threshold
elif operator == '<':
mask = metric_values < threshold
elif operator == '>=':
mask = metric_values >= threshold
elif operator == '<=':
mask = metric_values <= threshold
else:
raise ValueError(f"Invalid operator: {operator}. Use '>', '<', '>=', or '<='")
if verbose:
print(f" {metric} {operator} {threshold}:")
print(f" Cells filtered: {mask.sum()} ({mask.sum()/len(metric_values)*100:.2f}%)")
return mask
def filter_cells(adata, mask, inplace=False):
"""
Filter cells based on a boolean mask.
Parameters
----------
adata : AnnData
Annotated data matrix
mask : np.ndarray or pd.Series
Boolean mask where True indicates cells to KEEP
inplace : bool
Modify adata in place (default: False)
Returns
-------
AnnData
Filtered AnnData object
"""
if inplace:
# This is actually a bit tricky - AnnData doesn't support true inplace filtering
# Return filtered copy which caller should reassign
return adata[mask].copy()
else:
return adata[mask].copy()
def filter_genes(adata, min_cells=20, min_counts=None, inplace=True):
"""
Filter genes based on detection thresholds.
Parameters
----------
adata : AnnData
Annotated data matrix
min_cells : int
Minimum number of cells a gene must be detected in (default: 20)
min_counts : int, optional
Minimum total counts across all cells
inplace : bool
Modify adata in place (default: True)
Returns
-------
AnnData or None
If inplace=False, returns filtered AnnData
"""
if not inplace:
adata = adata.copy()
if min_cells is not None:
sc.pp.filter_genes(adata, min_cells=min_cells)
if min_counts is not None:
sc.pp.filter_genes(adata, min_counts=min_counts)
if not inplace:
return adata
def print_qc_summary(adata, label=''):
"""
Print summary statistics for QC metrics.
Parameters
----------
adata : AnnData
Annotated data matrix with QC metrics
label : str
Label to prepend to output (e.g., 'Before filtering', 'After filtering')
"""
if label:
print(f"\n{label}:")
print(f" Cells: {adata.n_obs}")
print(f" Genes: {adata.n_vars}")
if 'total_counts' in adata.obs:
print(f" Mean counts per cell: {adata.obs['total_counts'].mean():.0f}")
print(f" Median counts per cell: {adata.obs['total_counts'].median():.0f}")
if 'n_genes_by_counts' in adata.obs:
print(f" Mean genes per cell: {adata.obs['n_genes_by_counts'].mean():.0f}")
print(f" Median genes per cell: {adata.obs['n_genes_by_counts'].median():.0f}")
if 'pct_counts_mt' in adata.obs:
print(f" Mean mitochondrial %: {adata.obs['pct_counts_mt'].mean():.2f}%")
if 'pct_counts_ribo' in adata.obs:
print(f" Mean ribosomal %: {adata.obs['pct_counts_ribo'].mean():.2f}%")
Requirements and compatibility
Written for: Claude Code, Claude apps
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Anthropic
- Publisher
- Anthropic (Official)
- Source
- anthropics/knowledge-work-plugins · bio-research/skills/single-cell-rna-qc · commit e050c2e
- Licence
- Apache License 2.0 (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Anthropic or Anthropic.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download single-cell-rna-qc.zip