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://mp-staging.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_plotting.py
#!/usr/bin/env python3
"""
Visualization functions for single-cell RNA-seq quality control.
This module provides plotting utilities for QC metrics and filtering thresholds.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import median_abs_deviation
def plot_qc_distributions(adata, output_path, title='Quality Control Metrics'):
"""
Create comprehensive QC distribution plots.
Parameters
----------
adata : AnnData
Annotated data matrix with QC metrics
output_path : str
Path to save the figure
title : str
Figure title (default: 'Quality Control Metrics')
"""
fig, axes = plt.subplots(3, 3, figsize=(15, 12))
fig.suptitle(title, fontsize=16, y=0.995)
# Row 1: Histograms
axes[0, 0].hist(adata.obs['total_counts'], bins=100, color='steelblue', edgecolor='black')
axes[0, 0].set_xlabel('Total counts per cell')
axes[0, 0].set_ylabel('Number of cells')
axes[0, 0].set_title('Distribution of Total Counts')
axes[0, 0].axvline(adata.obs['total_counts'].median(), color='red', linestyle='--', label='Median')
axes[0, 0].legend()
axes[0, 1].hist(adata.obs['n_genes_by_counts'], bins=100, color='forestgreen', edgecolor='black')
axes[0, 1].set_xlabel('Genes per cell')
axes[0, 1].set_ylabel('Number of cells')
axes[0, 1].set_title('Distribution of Detected Genes')
axes[0, 1].axvline(adata.obs['n_genes_by_counts'].median(), color='red', linestyle='--', label='Median')
axes[0, 1].legend()
axes[0, 2].hist(adata.obs['pct_counts_mt'], bins=100, color='coral', edgecolor='black')
axes[0, 2].set_xlabel('Mitochondrial %')
axes[0, 2].set_ylabel('Number of cells')
axes[0, 2].set_title('Distribution of Mitochondrial Content')
axes[0, 2].axvline(adata.obs['pct_counts_mt'].median(), color='red', linestyle='--', label='Median')
axes[0, 2].legend()
# Row 2: Violin plots
axes[1, 0].violinplot([adata.obs['total_counts']], positions=[0], showmeans=True, showmedians=True)
axes[1, 0].set_ylabel('Total counts')
axes[1, 0].set_title('Total Counts per Cell')
axes[1, 0].set_xticks([])
axes[1, 1].violinplot([adata.obs['n_genes_by_counts']], positions=[0], showmeans=True, showmedians=True)
axes[1, 1].set_ylabel('Genes detected')
axes[1, 1].set_title('Genes per Cell')
axes[1, 1].set_xticks([])
axes[1, 2].violinplot([adata.obs['pct_counts_mt']], positions=[0], showmeans=True, showmedians=True)
axes[1, 2].set_ylabel('Mitochondrial %')
axes[1, 2].set_title('Mitochondrial Content')
axes[1, 2].set_xticks([])
# Row 3: Scatter plots
scatter1 = axes[2, 0].scatter(
adata.obs['total_counts'],
adata.obs['n_genes_by_counts'],
c=adata.obs['pct_counts_mt'],
cmap='viridis',
alpha=0.5,
s=10
)
axes[2, 0].set_xlabel('Total counts')
axes[2, 0].set_ylabel('Genes detected')
axes[2, 0].set_title('Counts vs Genes (colored by MT%)')
plt.colorbar(scatter1, ax=axes[2, 0], label='MT %')
axes[2, 1].scatter(
adata.obs['total_counts'],
adata.obs['pct_counts_mt'],
alpha=0.5,
s=10,
color='coral'
)
axes[2, 1].set_xlabel('Total counts')
axes[2, 1].set_ylabel('Mitochondrial %')
axes[2, 1].set_title('Total Counts vs Mitochondrial %')
axes[2, 2].scatter(
adata.obs['n_genes_by_counts'],
adata.obs['pct_counts_mt'],
alpha=0.5,
s=10,
color='forestgreen'
)
axes[2, 2].set_xlabel('Genes detected')
axes[2, 2].set_ylabel('Mitochondrial %')
axes[2, 2].set_title('Genes vs Mitochondrial %')
plt.tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches='tight')
plt.close()
def plot_filtering_thresholds(adata, outlier_masks, thresholds, output_path):
"""
Visualize filtering thresholds overlaid on distributions.
Parameters
----------
adata : AnnData
Annotated data matrix with QC metrics
outlier_masks : dict
Dictionary mapping metric names to boolean outlier masks
Example: {'total_counts': mask1, 'n_genes_by_counts': mask2, 'pct_counts_mt': mask3}
thresholds : dict
Dictionary with threshold information for each metric
Example: {'total_counts': {'n_mads': 5}, 'pct_counts_mt': {'n_mads': 3, 'hard': 8}}
output_path : str
Path to save the figure
"""
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
fig.suptitle('MAD-Based Filtering Thresholds', fontsize=16)
# Helper function to plot with thresholds
def plot_with_threshold(ax, metric, outlier_mask, n_mads, hard_threshold=None):
data = adata.obs[metric]
median = np.median(data)
mad = median_abs_deviation(data)
lower = median - n_mads * mad
upper = median + n_mads * mad
ax.hist(data[~outlier_mask], bins=100, alpha=0.7, label='Pass QC', color='steelblue')
ax.hist(data[outlier_mask], bins=100, alpha=0.7, label='Fail QC', color='coral')
ax.axvline(lower, color='red', linestyle='--', linewidth=2, label=f'Thresholds ({n_mads} MADs)')
ax.axvline(upper, color='red', linestyle='--', linewidth=2)
if hard_threshold is not None:
ax.axvline(hard_threshold, color='darkred', linestyle=':', linewidth=2,
label=f'Hard threshold ({hard_threshold})')
ax.set_xlabel(metric.replace('_', ' ').title())
ax.set_ylabel('Number of cells')
ax.legend()
# Plot each metric
metrics = [
('total_counts', 'Total Counts'),
('n_genes_by_counts', 'Genes Detected'),
('pct_counts_mt', 'Mitochondrial %')
]
for idx, (metric, label) in enumerate(metrics):
if metric in outlier_masks and metric in thresholds:
hard = thresholds[metric].get('hard', None)
plot_with_threshold(axes[idx], metric, outlier_masks[metric],
thresholds[metric]['n_mads'], hard)
plt.tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches='tight')
plt.close()
def plot_qc_after_filtering(adata, output_path):
"""
Create QC plots for filtered data (simplified version without outlier overlay).
Parameters
----------
adata : AnnData
Filtered annotated data matrix with QC metrics
output_path : str
Path to save the figure
"""
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
fig.suptitle('Quality Control Metrics - After Filtering', fontsize=16, y=0.995)
# Row 1: Histograms
axes[0, 0].hist(adata.obs['total_counts'], bins=100, color='steelblue', edgecolor='black')
axes[0, 0].set_xlabel('Total counts per cell')
axes[0, 0].set_ylabel('Number of cells')
axes[0, 0].set_title('Distribution of Total Counts')
axes[0, 1].hist(adata.obs['n_genes_by_counts'], bins=100, color='forestgreen', edgecolor='black')
axes[0, 1].set_xlabel('Genes per cell')
axes[0, 1].set_ylabel('Number of cells')
axes[0, 1].set_title('Distribution of Detected Genes')
axes[0, 2].hist(adata.obs['pct_counts_mt'], bins=100, color='coral', edgecolor='black')
axes[0, 2].set_xlabel('Mitochondrial %')
axes[0, 2].set_ylabel('Number of cells')
axes[0, 2].set_title('Distribution of Mitochondrial Content')
# Row 2: Scatter plots
scatter1 = axes[1, 0].scatter(
adata.obs['total_counts'],
adata.obs['n_genes_by_counts'],
c=adata.obs['pct_counts_mt'],
cmap='viridis',
alpha=0.5,
s=10
)
axes[1, 0].set_xlabel('Total counts')
axes[1, 0].set_ylabel('Genes detected')
axes[1, 0].set_title('Counts vs Genes (colored by MT%)')
plt.colorbar(scatter1, ax=axes[1, 0], label='MT %')
axes[1, 1].scatter(
adata.obs['total_counts'],
adata.obs['pct_counts_mt'],
alpha=0.5,
s=10,
color='coral'
)
axes[1, 1].set_xlabel('Total counts')
axes[1, 1].set_ylabel('Mitochondrial %')
axes[1, 1].set_title('Total Counts vs Mitochondrial %')
axes[1, 2].scatter(
adata.obs['n_genes_by_counts'],
adata.obs['pct_counts_mt'],
alpha=0.5,
s=10,
color='forestgreen'
)
axes[1, 2].set_xlabel('Genes detected')
axes[1, 2].set_ylabel('Mitochondrial %')
axes[1, 2].set_title('Genes vs Mitochondrial %')
plt.tight_layout()
plt.savefig(output_path, dpi=300, bbox_inches='tight')
plt.close()
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download single-cell-rna-qc.zip