agentleFS
nisarthnisarth/claude-skills-store/skills/bio-research/single-cell-rna-qc/SKILL.md

single-cell-rna-qc

Skill1 starsChanged 7 months agoMITView on GitHub

Perform 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 scientists need to filter low-quality cells, detect doublets, assess data quality metrics, or prepare data for downstream analysis. Trigger with "QC my single-cell data", "filter low-quality cells", "single-cell quality control", "check my scRNA-seq data quality", or "doublet detection".

4 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

6 rules. 0 are common, 6 are distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 4 edited versions we read keep these.

  • 6

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use Median Absolute Deviation (MAD) for robust, data-driven thresholds:

    line 89
  2. Distinctive:

    Run Scrublet for computational doublet detection:

    line 127
  3. Distinctive:

    Action: Use 3 MADs instead of 5 for stricter filtering, apply additional gene complexity filter (n_genes > 500), report the trade-off …

    line 240
  4. Distinctive:

    Always inspect the data before applying filters.

    line 244
  5. Distinctive:

    Use MAD-based thresholds rather than fixed cutoffs.

    line 245
  6. Distinctive:

    Run doublet detection per sample, not on the merged dataset.

    line 246

“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Single-Cell RNA-seq Quality Control

Perform comprehensive quality control on single-cell RNA-seq data using the scverse ecosystem (Scanpy, Scrublet). Apply MAD-based adaptive thresholds for filtering, detect doublets, generate diagnostic visualizations, and produce a QC report.

Workflow

Step 1: Load and Inspect the Data

import scanpy as sc
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

sc.settings.verbosity = 2

# Load data
adata = sc.read_h5ad("input.h5ad")
# Or from 10x .h5: adata = sc.read_10x_h5("filtered_feature_bc_matrix.h5")

print(f"Cells: {adata.n_obs}, Genes: {adata.n_vars}")
print(f"Observations: {adata.obs.columns.tolist()}")
print(f"Layers: {list(adata.layers.keys())}")

# Ensure we have raw counts
if adata.X.max() > 100:
    print("Data appears to be raw counts (good)")
else:
    print("WARNING: Data may be normalized. Check for a 'counts' layer.")

Step 2: Compute QC Metrics

Calculate per-cell and per-gene quality metrics:

# Identify mitochondrial genes
# Human: MT- prefix | Mouse: mt- prefix
adata.var["mt"] = adata.var_names.str.startswith("MT-")  # Adjust for species
adata.var["ribo"] = adata.var_names.str.startswith(("RPS", "RPL"))
adata.var["hb"] = adata.var_names.str.match("^HB[^(P)]")  # Hemoglobin genes

# Calculate QC metrics
sc.pp.calculate_qc_metrics(
    adata,
    qc_vars=["mt", "ribo", "hb"],
    inplace=True,
    percent_top=[20],
    log1p=True
)

Key metrics per cell:

  • n_genes_by_counts: Number of genes detected (library complexity).
  • total_counts: Total UMI count (sequencing depth).
  • pct_counts_mt: Percent mitochondrial reads (cell stress/death indicator).
  • pct_counts_ribo: Percent ribosomal reads (cell type indicator).
  • pct_counts_hb: Percent hemoglobin reads (red blood cell contamination).

Step 3: MAD-Based Adaptive Filtering

Use Median Absolute Deviation (MAD) for robust, data-driven thresholds:

def is_outlier(adata, metric, nmads=5):
    """Flag outlier cells using MAD-based thresholds."""
    M = adata.obs[metric]
    median = np.median(M)
    mad = np.median(np.abs(M - median))
    # MAD of zero means use a small epsilon
    if mad == 0:
        mad = 1e-6
    outlier = (M < median - nmads * mad) | (M > median + nmads * mad)
    return outlier

# Apply MAD-based filtering (default: 5 MADs, permissive)
nmads = 5

adata.obs["outlier_n_genes"] = is_outlier(adata, "log1p_n_genes_by_counts", nmads)
adata.obs["outlier_total_counts"] = is_outlier(adata, "log1p_total_counts", nmads)
adata.obs["outlier_mt"] = (
    is_outlier(adata, "pct_counts_mt", nmads) & (adata.obs["pct_counts_mt"] > 8)
)

adata.obs["qc_pass"] = ~(
    adata.obs["outlier_n_genes"]
    | adata.obs["outlier_total_counts"]
    | adata.obs["outlier_mt"]
)

n_before = adata.n_obs
adata_filtered = adata[adata.obs["qc_pass"]].copy()
n_after = adata_filtered.n_obs
print(f"Filtered: {n_before} -> {n_after} cells ({n_before - n_after} removed, "
      f"{(n_before - n_after)/n_before*100:.1f}%)")

Step 4: Doublet Detection

Run Scrublet for computational doublet detection:

import scrublet as scr

# Run Scrublet per sample/batch for best results
for sample in adata_filtered.obs["sample"].unique():
    mask = adata_filtered.obs["sample"] == sample
    sample_data = adata_filtered[mask].X

    scrub = scr.Scrublet(sample_data, expected_doublet_rate=0.06)
    doublet_scores, predicted_doublets = scrub.scrub_doublets(
        min_counts=2, min_cells=3, min_gene_variability_pctl=85
    )

    adata_filtered.obs.loc[mask, "doublet_score"] = doublet_scores
    adata_filtered.obs.loc[mask, "predicted_doublet"] = predicted_doublets

n_doublets = adata_filtered.obs["predicted_doublet"].sum()
print(f"Doublets detected: {n_doublets} ({n_doublets/adata_filtered.n_obs*100:.1f}%)")

# Remove doublets
adata_clean = adata_filtered[~adata_filtered.obs["predicted_doublet"]].copy()

Step 5: Generate QC Visualizations

# Violin plots of QC metrics
sc.pl.violin(
    adata,
    ["n_genes_by_counts", "total_counts", "pct_counts_mt"],
    jitter=0.4, multi_panel=True, save="_qc_violins.png"
)

# Scatter plots: counts vs genes, colored by mito %
sc.pl.scatter(
    adata, x="total_counts", y="n_genes_by_counts",
    color="pct_counts_mt", save="_counts_vs_genes.png"
)

# Highest expressed genes
sc.pl.highest_expr_genes(adata, n_top=20, save="_top_genes.png")

# Before/after filtering comparison
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].hist(adata.obs["pct_counts_mt"], bins=100)
axes[0].set_title(f"Before QC (n={adata.n_obs})")
axes[1].hist(adata_clean.obs["pct_counts_mt"], bins=100)
axes[1].set_title(f"After QC (n={adata_clean.n_obs})")
plt.savefig("qc_mito_comparison.png", dpi=150)

Step 6: Filter Genes and Save

# Remove genes detected in very few cells
sc.pp.filter_genes(adata_clean, min_cells=10)

# Save the QC-filtered dataset
adata_clean.write_h5ad("qc_filtered_output.h5ad")

Output Format

## Single-Cell RNA-seq QC Report

**Input**: <filename> (<n_cells> cells x <n_genes> genes)
**Species**: <human/mouse>
**MAD threshold**: <n> MADs

### Filtering Summary
| Stage               | Cells    | Removed | % Removed |
|----------------------|----------|---------|-----------|
| Input                | <n>      | -       | -         |
| QC outlier removal   | <n>      | <n>     | <pct>     |
| Doublet removal      | <n>      | <n>     | <pct>     |
| **Final**            | **<n>**  | **<n>** | **<pct>** |

### QC Thresholds Applied
| Metric               | Lower Bound | Upper Bound |
|----------------------|-------------|-------------|
| n_genes_by_counts    | <val>       | <val>       |
| total_counts         | <val>       | <val>       |
| pct_counts_mt        | -           | <val>       |

### QC Metric Distributions (post-filter)
| Metric              | Median   | Mean     | Std      |
|---------------------|----------|----------|----------|
| Genes per cell      | <val>    | <val>    | <val>    |
| UMIs per cell       | <val>    | <val>    | <val>    |
| Mito %              | <val>    | <val>    | <val>    |

### Visualizations
- `qc_violins.png` - Distribution of QC metrics
- `counts_vs_genes.png` - Complexity scatter plot
- `top_genes.png` - Highest expressed genes
- `qc_mito_comparison.png` - Before/after mito distribution

### Output
- `qc_filtered_output.h5ad` - QC-filtered AnnData object

Examples

User: "QC my single-cell data, it's a human PBMC dataset" Action: Load .h5ad, compute QC metrics with MT- prefix for human, apply 5-MAD filtering, run Scrublet for doublets, generate violin and scatter plots, save filtered data.

User: "My data has high mitochondrial content, what threshold should I use?" Action: Plot mito% distribution, assess whether there is a bimodal pattern (dead cells vs healthy), adjust MAD threshold or use a fixed cutoff based on the distribution.

User: "Filter strictly, I only want high-quality cells" Action: Use 3 MADs instead of 5 for stricter filtering, apply additional gene complexity filter (n_genes > 500), report the trade-off between stringency and cell count.

Best Practices

  • Always inspect the data before applying filters. Blind application of thresholds can remove biologically meaningful populations (e.g., red blood cells have high hemoglobin and low gene counts).
  • Use MAD-based thresholds rather than fixed cutoffs. Fixed thresholds (e.g., mito% < 20%) do not adapt to dataset-specific distributions.
  • Run doublet detection per sample, not on the merged dataset. Merging inflates artificial doublet rates.
  • A typical filtering loss of 5-15% is normal. If you are removing >30% of cells, investigate whether the cutoffs are appropriate or the experiment had quality issues.
  • Preserve raw counts in adata.layers["counts"] before any normalization for downstream tools (scVI, CellRanger) that require raw data.
  • For multi-sample experiments, check QC metric distributions per sample. One failed sample can skew global MAD thresholds.
  • Expected doublet rates: ~0.8% per 1000 cells captured (10x Chromium). A 10K-cell library should have ~8% doublets.
  • Save the QC report and thresholds alongside the filtered data for reproducibility.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.