Generated banner for Single Cell Rna Qc
Generated logo for Single Cell Rna Qc

Single Cell Rna Qc

AnthropicOfficialPublished by Anthropic

  • Skill
  • Tool integration
  • Science and research
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Performs quality control on single-cell RNA-seq data (.h5ad or .h5 files) using scverse best practices with MAD-based filtering and comprehensive visualizations. Use when users request QC analysis, filtering low-quality cells, assessing data quality, or following scverse/scanpy best practices for single-cell analysis.
— the description by Anthropic

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/anthropics/single-cell-rna-qc/download
  2. Unzip 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:

  • .h5ad files (AnnData format from scanpy/Python workflows)

  • .h5 files (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.

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.h5

The 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 visualizations

  • qc_filtering_thresholds.png - MAD-based threshold overlays

  • qc_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:

  1. Calculate QC metrics - Count depth, gene detection, mitochondrial/ribosomal/hemoglobin content

  2. Apply MAD-based filtering - Permissive outlier detection using MAD thresholds for counts/genes/MT%

  3. Filter genes - Remove genes detected in few cells

  4. 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 here

When 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 adata

  • detect_outliers_mad(adata, metric, n_mads, verbose=True) - MAD-based outlier detection, returns boolean mask

  • apply_hard_threshold(adata, metric, threshold, operator='>', verbose=True) - Apply hard cutoffs, returns boolean mask

  • filter_cells(adata, mask, inplace=False) - Apply boolean mask to filter cells

  • filter_genes(adata, min_cells=20, min_counts=None, inplace=True) - Filter genes by detection

  • print_qc_summary(adata, label='') - Print summary statistics

From qc_plotting.py (visualization):

  • plot_qc_distributions(adata, output_path, title) - Generate comprehensive QC plots

  • plot_filtering_thresholds(adata, outlier_masks, thresholds, output_path) - Visualize filtering thresholds

  • plot_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

  1. Be permissive with filtering - Default thresholds intentionally retain most cells to avoid losing rare populations

  2. Inspect visualizations - Always review before/after plots to ensure filtering makes biological sense

  3. Consider dataset-specific factors - Some tissues naturally have higher mitochondrial content (e.g., neurons, cardiomyocytes)

  4. Check gene annotations - Mitochondrial gene prefixes vary by species (mt- for mouse, MT- for human)

  5. 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

scripts/qc_analysis.py

#!/usr/bin/env python3
"""
Quality Control Analysis for Single-Cell RNA-seq Data
Following scverse best practices from:
https://www.sc-best-practices.org/preprocessing_visualization/quality_control.html

This is a convenience script that runs a complete QC workflow using the
modular functions from qc_core.py and qc_plotting.py.
"""

import anndata as ad
import scanpy as sc
import sys
import os
import argparse

# Import our modular utilities
from qc_core import (
    calculate_qc_metrics,
    detect_outliers_mad,
    apply_hard_threshold,
    filter_cells,
    filter_genes,
    print_qc_summary
)
from qc_plotting import (
    plot_qc_distributions,
    plot_filtering_thresholds,
    plot_qc_after_filtering
)

print("=" * 80)
print("Single-Cell RNA-seq Quality Control Analysis")
print("=" * 80)

# Default parameters (single source of truth)
DEFAULT_MAD_COUNTS = 5
DEFAULT_MAD_GENES = 5
DEFAULT_MAD_MT = 3
DEFAULT_MT_THRESHOLD = 8
DEFAULT_MIN_CELLS = 20
DEFAULT_MT_PATTERN = 'mt-,MT-'
DEFAULT_RIBO_PATTERN = 'Rpl,Rps,RPL,RPS'
DEFAULT_HB_PATTERN = '^Hb[^(p)]|^HB[^(P)]'

# Parse command-line arguments
parser = argparse.ArgumentParser(
    description='Quality Control Analysis for Single-Cell RNA-seq Data',
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog="""
Examples:
  python3 qc_analysis.py data.h5ad
  python3 qc_analysis.py raw_feature_bc_matrix.h5
  python3 qc_analysis.py data.h5ad --mad-counts 4 --mad-genes 4 --mad-mt 2.5
  python3 qc_analysis.py data.h5ad --mt-threshold 10 --min-cells 10
  python3 qc_analysis.py data.h5ad --mt-pattern "^mt-" --ribo-pattern "^Rpl,^Rps"
    """
)

parser.add_argument('input_file', help='Input .h5ad or .h5 file (10X Genomics format)')
parser.add_argument('--output-dir', type=str, help='Output directory (default: <input_basename>_qc_results)')
parser.add_argument('--mad-counts', type=float, default=DEFAULT_MAD_COUNTS, help=f'MAD threshold for total counts (default: {DEFAULT_MAD_COUNTS})')
parser.add_argument('--mad-genes', type=float, default=DEFAULT_MAD_GENES, help=f'MAD threshold for gene counts (default: {DEFAULT_MAD_GENES})')
parser.add_argument('--mad-mt', type=float, default=DEFAULT_MAD_MT, help=f'MAD threshold for mitochondrial percentage (default: {DEFAULT_MAD_MT})')
parser.add_argument('--mt-threshold', type=float, default=DEFAULT_MT_THRESHOLD, help=f'Hard threshold for mitochondrial percentage (default: {DEFAULT_MT_THRESHOLD})')
parser.add_argument('--min-cells', type=int, default=DEFAULT_MIN_CELLS, help=f'Minimum cells for gene filtering (default: {DEFAULT_MIN_CELLS})')
parser.add_argument('--mt-pattern', type=str, default=DEFAULT_MT_PATTERN, help=f'Comma-separated mitochondrial gene prefixes (default: "{DEFAULT_MT_PATTERN}")')
parser.add_argument('--ribo-pattern', type=str, default=DEFAULT_RIBO_PATTERN, help=f'Comma-separated ribosomal gene prefixes (default: "{DEFAULT_RIBO_PATTERN}")')
parser.add_argument('--hb-pattern', type=str, default=DEFAULT_HB_PATTERN, help=f'Hemoglobin gene regex pattern (default: "{DEFAULT_HB_PATTERN}")')

args = parser.parse_args()

# Verify input file exists
if not os.path.exists(args.input_file):
    print(f"\nError: File '{args.input_file}' not found!")
    sys.exit(1)

input_file = args.input_file
base_name = os.path.splitext(os.path.basename(input_file))[0]

# Set up output directory
if args.output_dir:
    output_dir = args.output_dir
else:
    output_dir = f"{base_name}_qc_results"

os.makedirs(output_dir, exist_ok=True)
print(f"\nOutput directory: {output_dir}")

# Display parameters
print(f"\nParameters:")
print(f"  MAD thresholds: counts={args.mad_counts}, genes={args.mad_genes}, MT%={args.mad_mt}")
print(f"  MT hard threshold: {args.mt_threshold}%")
print(f"  Min cells for gene filtering: {args.min_cells}")
print(f"  Gene patterns: MT={args.mt_pattern}, Ribo={args.ribo_pattern}")

# Load the data
print("\n[1/5] Loading data...")
file_ext = os.path.splitext(input_file)[1].lower()

if file_ext == '.h5ad':
    adata = ad.read_h5ad(input_file)
    print(f"Loaded .h5ad file: {adata.n_obs} cells × {adata.n_vars} genes")
elif file_ext == '.h5':
    adata = sc.read_10x_h5(input_file)
    print(f"Loaded 10X .h5 file: {adata.n_obs} cells × {adata.n_vars} genes")
    # Make variable names unique (10X data sometimes has duplicate gene names)
    adata.var_names_make_unique()
else:
    print(f"\nError: Unsupported file format '{file_ext}'. Expected .h5ad or .h5")
    sys.exit(1)

# Store original counts for comparison
n_cells_original = adata.n_obs
n_genes_original = adata.n_vars

# Calculate QC metrics
print("\n[2/5] Calculating QC metrics...")
calculate_qc_metrics(adata, mt_pattern=args.mt_pattern,
                     ribo_pattern=args.ribo_pattern,
                     hb_pattern=args.hb_pattern,
                     inplace=True)

print(f"  Found {adata.var['mt'].sum()} mitochondrial genes (pattern: {args.mt_pattern})")
print(f"  Found {adata.var['ribo'].sum()} ribosomal genes (pattern: {args.ribo_pattern})")
print(f"  Found {adata.var['hb'].sum()} hemoglobin genes (pattern: {args.hb_pattern})")

print_qc_summary(adata, label='QC Metrics Summary (before filtering)')

# Create before-filtering visualizations
print("\n[3/5] Creating QC visualizations...")
before_plot = os.path.join(output_dir, 'qc_metrics_before_filtering.png')
plot_qc_distributions(adata, before_plot, title='Quality Control Metrics - Before Filtering')
print(f"  Saved: {before_plot}")

# Apply MAD-based filtering
print("\n[4/5] Applying MAD-based filtering thresholds...")

# Detect outliers for each metric
adata.obs['outlier_counts'] = detect_outliers_mad(adata, 'total_counts', args.mad_counts)
adata.obs['outlier_genes'] = detect_outliers_mad(adata, 'n_genes_by_counts', args.mad_genes)
adata.obs['outlier_mt'] = detect_outliers_mad(adata, 'pct_counts_mt', args.mad_mt)

# Apply hard threshold for mitochondrial content
print(f"\n  Applying hard threshold for mitochondrial content (>{args.mt_threshold}%):")
high_mt_mask = apply_hard_threshold(adata, 'pct_counts_mt', args.mt_threshold, operator='>')

# Combine MT filters (MAD + hard threshold)
adata.obs['outlier_mt'] = adata.obs['outlier_mt'] | high_mt_mask

# Overall filtering decision
adata.obs['pass_qc'] = ~(
    adata.obs['outlier_counts'] |
    adata.obs['outlier_genes'] |
    adata.obs['outlier_mt']
)

print(f"\n  Total cells failing QC: {(~adata.obs['pass_qc']).sum()} ({(~adata.obs['pass_qc']).sum()/adata.n_obs*100:.2f}%)")
print(f"  Cells passing QC: {adata.obs['pass_qc'].sum()} ({adata.obs['pass_qc'].sum()/adata.n_obs*100:.2f}%)")

# Visualize filtering thresholds
outlier_masks = {
    'total_counts': adata.obs['outlier_counts'].values,
    'n_genes_by_counts': adata.obs['outlier_genes'].values,
    'pct_counts_mt': adata.obs['outlier_mt'].values
}

thresholds = {
    'total_counts': {'n_mads': args.mad_counts},
    'n_genes_by_counts': {'n_mads': args.mad_genes},
    'pct_counts_mt': {'n_mads': args.mad_mt, 'hard': args.mt_threshold}
}

threshold_plot = os.path.join(output_dir, 'qc_filtering_thresholds.png')
plot_filtering_thresholds(adata, outlier_masks, thresholds, threshold_plot)
print(f"\n  Saved: {threshold_plot}")

# Apply filtering
print("\n[5/5] Applying filters...")
adata_filtered = filter_cells(adata, adata.obs['pass_qc'].values, inplace=False)
print(f"  Cells after filtering: {adata_filtered.n_obs} (removed {n_cells_original - adata_filtered.n_obs})")

# Filter genes
print(f"\n  Filtering genes detected in <{args.min_cells} cells...")
filter_genes(adata_filtered, min_cells=args.min_cells, inplace=True)
print(f"  Genes after filtering: {adata_filtered.n_vars} (removed {n_genes_original - adata_filtered.n_vars})")

# Generate summary statistics
print("\n" + "=" * 80)
print("QC Summary")
print("=" * 80)

print("\nBefore filtering:")
print(f"  Cells: {n_cells_original}")
print(f"  Genes: {n_genes_original}")

print("\nAfter filtering:")
print(f"  Cells: {adata_filtered.n_obs} ({adata_filtered.n_obs/n_cells_original*100:.1f}% retained)")
print(f"  Genes: {adata_filtered.n_vars} ({adata_filtered.n_vars/n_genes_original*100:.1f}% retained)")

print_qc_summary(adata_filtered, label='\nFiltered data QC metrics')

# Create after-filtering visualizations
after_plot = os.path.join(output_dir, 'qc_metrics_after_filtering.png')
plot_qc_after_filtering(adata_filtered, after_plot)
print(f"\n  Saved: {after_plot}")

# Save filtered data
print("\nSaving filtered data...")
output_filtered = os.path.join(output_dir, f'{base_name}_filtered.h5ad')
output_with_qc = os.path.join(output_dir, f'{base_name}_with_qc.h5ad')
adata_filtered.write(output_filtered)
print(f"  Saved: {output_filtered}")

# Also save the unfiltered data with QC annotations
adata.write(output_with_qc)
print(f"  Saved: {output_with_qc} (original data with QC annotations)")

print("\n" + "=" * 80)
print("Quality Control Analysis Complete!")
print("=" * 80)
print(f"\nAll results saved to: {output_dir}/")
print("\nGenerated files:")
print("  1. qc_metrics_before_filtering.png - Initial QC visualizations")
print("  2. qc_filtering_thresholds.png - MAD-based threshold visualization")
print("  3. qc_metrics_after_filtering.png - Post-filtering QC visualizations")
print(f"  4. {base_name}_filtered.h5ad - Filtered dataset")
print(f"  5. {base_name}_with_qc.h5ad - Original dataset with QC annotations")
print("\nNext steps:")
print("  - Consider ambient RNA correction (SoupX)")
print("  - Consider doublet detection (scDblFinder)")
print("  - Proceed with normalization and downstream analysis")

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