nota-america/forgecat-agent-profiles / profiles/anthropics/knowledge-work-plugins/anthropics_knowledge-work-plugins_bio-research/for-claude/.claude/skills/scvi-tools
scvi-tools
VerifiedDeep learning for single-cell analysis using scvi-tools. This skill should be used when users need (1) data integration and batch correction with scVI/scANVI, (2) ATAC-seq analysis with PeakVI, (3) CITE-seq multi-modal analysis with totalVI, (4) multiome RNA+ATAC analysis with MultiVI, (5) spatial transcriptomics deconvolution with DestVI, (6) label transfer and reference mapping with scANVI/scArches, (7) RNA velocity with veloVI, or (8) any deep learning-based single-cell method. Triggers include mentions of scVI, scANVI, totalVI, PeakVI, MultiVI, DestVI, veloVI, sysVI, scArches, variational autoencoder, VAE, batch correction, data integration, multi-modal, CITE-seq, multiome, reference mapping, latent space.
| File | Kind | Size |
|---|---|---|
| LICENSE.txt | markdown | 10.0 KB |
| SKILL.md | skill md | 7.3 KB |
| references/atac_peakvi.md | markdown | 9.3 KB |
| references/batch_correction_sysvi.md | markdown | 10.2 KB |
| references/citeseq_totalvi.md | markdown | 10.1 KB |
| references/data_preparation.md | markdown | 6.2 KB |
| references/environment_setup.md | markdown | 6.3 KB |
| references/label_transfer.md | markdown | 10.2 KB |
| references/multiome_multivi.md | markdown | 8.9 KB |
| references/rna_velocity_velovi.md | markdown | 8.6 KB |
| references/scarches_mapping.md | markdown | 10.8 KB |
| references/scrna_integration.md | markdown | 9.6 KB |
| references/spatial_deconvolution.md | markdown | 11.2 KB |
| references/troubleshooting.md | markdown | 10.8 KB |
| scripts/cluster_embed.pyexecutable | script | 6.3 KB |
| scripts/differential_expression.pyexecutable | script | 6.7 KB |
| scripts/integrate_datasets.pyexecutable | script | 6.9 KB |
| scripts/model_utils.pyexecutable | script | 17.0 KB |
| scripts/prepare_data.pyexecutable | script | 5.1 KB |
| scripts/train_model.pyexecutable | script | 11.3 KB |
| scripts/transfer_labels.pyexecutable | script | 7.2 KB |
| scripts/validate_adata.pyexecutable | script | 11.9 KB |
scripts/transfer_labels.py
View on GitHub#!/usr/bin/env python3
"""
Transfer cell type labels from reference to query using scANVI.
Maps query cells to a pre-trained reference model and predicts cell types.
Usage:
python transfer_labels.py reference_model/ query.h5ad output_dir/
python transfer_labels.py reference_model/ query.h5ad output_dir/ --confidence 0.7
"""
import argparse
import os
import sys
def transfer_labels(
reference_model,
adata_query,
max_epochs=100,
confidence_threshold=0.5
):
"""
Transfer labels from reference to query.
Parameters
----------
reference_model : SCANVI model
Pre-trained scANVI model
adata_query : AnnData
Query data to annotate
max_epochs : int
Fine-tuning epochs
confidence_threshold : float
Minimum confidence for predictions
Returns
-------
AnnData with predictions
"""
import scvi
import numpy as np
# Get reference genes
ref_genes = reference_model.adata.var_names
print(f"Reference genes: {len(ref_genes)}")
# Check gene overlap
query_genes = adata_query.var_names
common = ref_genes.intersection(query_genes)
print(f"Query genes: {len(query_genes)}")
print(f"Common genes: {len(common)} ({len(common)/len(ref_genes)*100:.1f}%)")
if len(common) < len(ref_genes) * 0.5:
print("Warning: Less than 50% gene overlap. Results may be unreliable.")
# Subset query to reference genes
# Missing genes will be filled with zeros
adata_query = adata_query[:, adata_query.var_names.isin(ref_genes)].copy()
# Ensure counts layer
if "counts" not in adata_query.layers:
adata_query.layers["counts"] = adata_query.X.copy()
# Prepare query for mapping
print("Preparing query data...")
scvi.model.SCANVI.prepare_query_anndata(adata_query, reference_model)
# Create query model
print("Creating query model...")
query_model = scvi.model.SCANVI.load_query_data(
adata_query,
reference_model
)
# Fine-tune
print(f"Fine-tuning ({max_epochs} epochs)...")
query_model.train(
max_epochs=max_epochs,
plan_kwargs={"weight_decay": 0.0}
)
# Get predictions
print("Getting predictions...")
predictions = query_model.predict()
soft_predictions = query_model.predict(soft=True)
adata_query.obs["predicted_cell_type"] = predictions
adata_query.obs["prediction_confidence"] = soft_predictions.max(axis=1)
adata_query.obs["confident_prediction"] = adata_query.obs["prediction_confidence"] >= confidence_threshold
# Get latent representation
adata_query.obsm["X_scANVI"] = query_model.get_latent_representation()
# Stats
n_confident = adata_query.obs["confident_prediction"].sum()
print(f"\nPrediction summary:")
print(f" Total cells: {adata_query.n_obs}")
print(f" Confident (>= {confidence_threshold}): {n_confident} ({n_confident/adata_query.n_obs*100:.1f}%)")
print(f" Mean confidence: {adata_query.obs['prediction_confidence'].mean():.3f}")
print("\nPredicted cell types:")
print(adata_query.obs["predicted_cell_type"].value_counts())
return adata_query, query_model
def plot_predictions(adata, output_dir):
"""Plot prediction results."""
import scanpy as sc
import matplotlib.pyplot as plt
# Compute UMAP if needed
if "X_umap" not in adata.obsm:
sc.pp.neighbors(adata, use_rep="X_scANVI")
sc.tl.umap(adata)
# Plot
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
sc.pl.umap(adata, color="predicted_cell_type", ax=axes[0], show=False,
title="Predicted Cell Type")
sc.pl.umap(adata, color="prediction_confidence", ax=axes[1], show=False,
title="Prediction Confidence", cmap="viridis")
sc.pl.umap(adata, color="confident_prediction", ax=axes[2], show=False,
title="Confident Predictions")
plt.tight_layout()
plot_path = os.path.join(output_dir, "predictions.png")
plt.savefig(plot_path, dpi=150, bbox_inches="tight")
plt.close()
print(f"Prediction plot saved to {plot_path}")
def main():
parser = argparse.ArgumentParser(
description="Transfer cell type labels using scANVI",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Basic label transfer
python transfer_labels.py reference_model/ query.h5ad results/
# With confidence threshold
python transfer_labels.py reference_model/ query.h5ad results/ --confidence 0.7
# More fine-tuning
python transfer_labels.py reference_model/ query.h5ad results/ --max-epochs 200
"""
)
parser.add_argument("model_dir", help="Directory containing reference scANVI model")
parser.add_argument("query", help="Query h5ad file to annotate")
parser.add_argument("output_dir", help="Output directory")
parser.add_argument("--reference-adata", help="Reference adata used for training (if not saved with model)")
parser.add_argument("--max-epochs", type=int, default=100,
help="Fine-tuning epochs (default: 100)")
parser.add_argument("--confidence", type=float, default=0.5,
help="Confidence threshold (default: 0.5)")
args = parser.parse_args()
try:
import scvi
import scanpy as sc
except ImportError:
print("Error: scvi-tools and scanpy required")
sys.exit(1)
# Create output directory
os.makedirs(args.output_dir, exist_ok=True)
# Load query data
print(f"Loading query data: {args.query}")
adata_query = sc.read_h5ad(args.query)
print(f"Query: {adata_query.shape}")
# Load reference model
print(f"Loading reference model: {args.model_dir}")
if args.reference_adata:
ref_adata = sc.read_h5ad(args.reference_adata)
reference_model = scvi.model.SCANVI.load(args.model_dir, adata=ref_adata)
else:
# Try loading without adata (works if model was saved with adata)
try:
reference_model = scvi.model.SCANVI.load(args.model_dir)
except ValueError as e:
if "no saved anndata" in str(e).lower():
print("Error: Model was saved without adata. Please provide --reference-adata")
sys.exit(1)
raise
print(f"Reference: {reference_model.adata.shape}")
# Transfer labels
adata_annotated, query_model = transfer_labels(
reference_model,
adata_query,
max_epochs=args.max_epochs,
confidence_threshold=args.confidence
)
# Save results
adata_path = os.path.join(args.output_dir, "query_annotated.h5ad")
adata_annotated.write_h5ad(adata_path)
print(f"\nAnnotated data saved to {adata_path}")
# Save query model
model_path = os.path.join(args.output_dir, "query_model")
query_model.save(model_path)
print(f"Query model saved to {model_path}")
# Save predictions CSV
pred_df = adata_annotated.obs[["predicted_cell_type", "prediction_confidence", "confident_prediction"]]
pred_path = os.path.join(args.output_dir, "predictions.csv")
pred_df.to_csv(pred_path)
print(f"Predictions saved to {pred_path}")
# Plot
plot_predictions(adata_annotated, args.output_dir)
print("\nDone!")
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |