Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Enhance documentation for cellxgene-census and deepTools skills. Update cellxgene-census to version 1.1, expanding description, compatibility notes, and data structure details for single-cell and spatial transcriptomics. Revise deepTools to version 1.1, improving installation instructions, normalization methods, and adding new features for effective genome size and scaling. Update quick reference and workflow scripts for better usability and clarity.

Timothy Kassis758bad118556
diff --git a/README.md b/README.md
index 1e493d38..e2a7a3a6 100644
--- a/README.md
+++ b/README.md
@@ -352,7 +352,7 @@ networks, and search GEO for similar patterns.
- **Virtual Screening**: Screen millions of compounds from PubChem/ZINC against protein targets
- **Lead Optimization**: Analyze structure-activity relationships with RDKit, generate analogs with datamol
- **ADMET Prediction**: Predict absorption, distribution, metabolism, excretion, and toxicity with DeepChem
-- **Molecular Docking**: Predict binding poses and affinities with DiffDock
+- **Molecular Docking**: Predict binding poses with DiffDock and rescore poses with affinity-oriented tools
- **Bioactivity Mining**: Query ChEMBL for known inhibitors and analyze SAR patterns
### 🧬 Bioinformatics & Genomics
diff --git a/docs/examples.md b/docs/examples.md
index df49434d..7db2a768 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -96,7 +96,7 @@ Step 6: Predict properties with DeepChem
Step 7: Virtual screening with DiffDock
- Perform molecular docking on top 50 candidates
- Dock into wild-type EGFR and T790M mutant
-- Calculate binding energies and interaction patterns
+- Rank generated poses by DiffDock confidence, then rescore with GNINA/MM-GBSA for affinity-oriented prioritization
- Identify compounds with favorable binding to both forms
Step 8: Search PubChem for commercial availability
@@ -568,7 +568,7 @@ Step 5: Search ZINC15 for fragment library
Step 6: Virtual screening with fragment library
- Use DiffDock to dock fragments into interface pocket
-- Rank by predicted binding affinity
+- Rank by pose confidence, then rescore promising poses with an affinity-oriented method
- Identify fragments binding to hot spot residues
- Select top 50 fragments for elaboration
@@ -582,7 +582,7 @@ Step 7: Fragment elaboration with RDKit
Step 8: Second round of virtual screening
- Dock elaborated molecules with DiffDock
-- Calculate binding energies and interaction patterns
+- Analyze interaction patterns and rescore poses with GNINA/MM-GBSA or another affinity-oriented method
- Prioritize molecules with:
* Strong binding to hot spot residues
* Multiple H-bonds and hydrophobic contacts
diff --git a/docs/open-source-sponsors.md b/docs/open-source-sponsors.md
index 5b99fa28..c298c7c8 100644
--- a/docs/open-source-sponsors.md
+++ b/docs/open-source-sponsors.md
@@ -132,7 +132,7 @@ Scientific Agent Skills is built on the shoulders of giants. The 135 skills in t
| Project | Description | Links |
|---------|-------------|-------|
-| **ESM** | Evolutionary scale modeling | [GitHub](https://github.com/facebookresearch/esm) |
+| **ESM** | Evolutionary scale modeling | [GitHub](https://github.com/Biohub/esm) |
### Data Formats & I/O
diff --git a/docs/skills.md b/docs/skills.md
index 87029a55..7240f6f0 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -42,10 +42,10 @@
- **BioPython** - Comprehensive Python library for computational biology and bioinformatics providing tools for sequence manipulation, database access, and biological data analysis. Key features include: sequence objects (Seq, SeqRecord, SeqIO) for DNA/RNA/protein sequences with biological alphabet validation, file format parsers (FASTA, FASTQ, GenBank, EMBL, Swiss-Prot, PDB, SAM/BAM, VCF, GFF), NCBI database access (Entrez Programming Utilities for PubMed, GenBank, BLAST, taxonomy), BLAST integration (running searches, parsing results), sequence alignment (pairwise and multiple sequence alignment with Bio.Align), phylogenetics (tree construction and manipulation with Bio.Phylo), population genetics (Hardy-Weinberg, F-statistics), protein structure analysis (PDB parsing, structure calculations), and statistical analysis tools. Supports integration with NumPy, pandas, and other scientific Python libraries. Use cases: sequence analysis, database queries, phylogenetic analysis, sequence alignment, file format conversion, and general bioinformatics workflows
- **BioServices** - Python library providing unified programmatic access to 40+ biological web services and databases. Supports major bioinformatics resources including KEGG (pathway and compound data), UniProt (protein sequences and annotations), ChEBI (chemical entities), ChEMBL (bioactive molecules), Reactome (pathways), IntAct (protein interactions), BioModels (biological models), and many others. Features consistent API across different services, automatic result caching, error handling and retry logic, support for both REST and SOAP web services, and conversion of results to Python objects (dictionaries, lists, BioPython objects). Handles authentication, rate limiting, and API versioning. Use cases: automated data retrieval from multiple biological databases, building bioinformatics pipelines, database integration workflows, and programmatic access to biological web resources without manual web browsing
- **Bulk RNA-seq** - End-to-end orchestrator for bulk RNA-seq differential-expression studies, chaining the repo's skills into one defensible pipeline: raw FASTQ -> QC/trimming (FastQC, fastp/Trim Galore) -> alignment and quantification (STAR, Salmon, featureCounts) -> a gene-level counts matrix -> differential expression (PyDESeq2) -> pathway/GSEA enrichment (Pathway Enrichment) -> publication figures (scientific-visualization). Offers two interchangeable upstream paths with a decision guide — nf-core/rnaseq driven through the Nextflow skill, or standalone STAR/Salmon recipes — plus the glue no single tool provides: experimental-design and QC guidance (replication, batch/confounding, strandedness, mapping-rate and PCA gates), a quant->counts bridge script (build_counts_matrix.py: aggregates Salmon quant.sf via pytximport, selects the correct STAR ReadsPerGene strand column, or parses featureCounts into a PyDESeq2-ready counts.csv plus metadata template), and a samplesheet/design validator (validate_samplesheet.py). Emphasizes reproducibility (pinned pipeline/tool/reference versions, containers) and correct statistics (integer counts, gene-ID mapping to symbols, FDR control). Use cases: going from sequencing reads to differentially expressed genes and enriched pathways, running or configuring nf-core/rnaseq, STAR/Salmon quantification, building a counts matrix for DESeq2, and scoping a complete reproducible bulk RNA-seq analysis. For single-cell RNA-seq use Scanpy instead
-- **Cellxgene Census** - Python package for querying and analyzing large-scale single-cell RNA-seq data from the CZ CELLxGENE Discover census. Provides access to 50M+ cells across 1,000+ datasets with standardized annotations and metadata. Key features include: efficient data access using TileDB-SOMA format for scalable queries, integration with AnnData and Scanpy for downstream analysis, cell metadata filtering and querying, gene expression retrieval, and support for both human and mouse data. Enables subsetting datasets by cell type, tissue, disease, or other metadata before downloading, reducing data transfer and memory requirements. Supports local caching and batch operations. Use cases: large-scale single-cell analysis, cell-type discovery, cross-dataset comparisons, reference dataset construction, and exploratory analysis of public single-cell data
+- **Cellxgene Census** - Python package for querying and analyzing versioned public single-cell and spatial transcriptomics data from CZ CELLxGENE Discover. Provides access to the current stable LTS Census release with 217M+ total cells, 125M+ unique cells, and 1,845 datasets, with standardized annotations and metadata across human, mouse, marmoset, rhesus macaque, and chimpanzee. Key features include: efficient TileDB-SOMA access for scalable metadata and expression queries, AnnData and Scanpy integration, source H5AD URI/download helpers, precomputed summary counts, embeddings, spatial Census access, and TileDB-SOMA-ML guidance for PyTorch loaders. Enables subsetting datasets by organism, cell type, tissue, disease, assay, or other metadata before downloading, reducing transfer and memory requirements. Use cases: large-scale single-cell analysis, spatial transcriptomics access, cell-type discovery, cross-dataset comparisons, reference atlas construction, and exploratory analysis of public Census data
- **deepTools** - Comprehensive suite of Python tools for exploring and visualizing next-generation sequencing (NGS) data, particularly ChIP-seq, RNA-seq, and ATAC-seq experiments. Provides command-line tools and Python API for processing BAM and bigWig files. Key features include: quality control metrics (plotFingerprint, plotCorrelation), coverage track generation (bamCoverage for creating bigWig files), matrix generation for heatmaps (computeMatrix, plotHeatmap, plotProfile), comparative analysis (multiBigwigSummary, plotPCA), and efficient handling of large files. Supports normalization methods, binning options, and various visualization outputs. Designed for high-throughput analysis workflows and publication-quality figure generation. Use cases: ChIP-seq peak visualization, RNA-seq coverage analysis, ATAC-seq signal tracks, comparative genomics, and NGS data exploration
- **FlowIO** - Python library for reading and manipulating Flow Cytometry Standard (FCS) files, the standard format for flow cytometry data. Provides efficient parsing of FCS files (versions 2.0, 3.0, 3.1), access to event data (fluorescence intensities, scatter parameters), metadata extraction (keywords, parameters, acquisition settings), and conversion to pandas DataFrames or NumPy arrays. Features include: support for large FCS files, handling of multiple data segments, access to text segments and analysis segments, and integration with flow cytometry analysis workflows. Enables programmatic access to flow cytometry data for downstream analysis, visualization, and machine learning applications. Use cases: flow cytometry data analysis, high-throughput screening, immune cell profiling, and automated processing of FCS files
-- **gget** - Command-line tool and Python package for efficient querying of genomic databases with a simple, unified interface. Provides fast access to Ensembl (gene information, sequences, orthologs, variants), UniProt (protein sequences and annotations), NCBI (BLAST searches, gene information), PDB (protein structures), COSMIC (cancer mutations), and other databases. Features include: single-command queries without complex API setup, automatic result formatting, batch query support, integration with pandas DataFrames, and support for both command-line and Python API usage. Optimized for speed and ease of use, making database queries accessible to users without extensive bioinformatics experience. Use cases: quick gene lookups, sequence retrieval, variant annotation, protein structure access, and rapid database queries in bioinformatics workflows
+- **gget** - Command-line tool and Python package for efficient querying of genomic databases with a simple, unified interface. Provides fast access to Ensembl (gene information and sequences), UniProt, NCBI BLAST/BLAT and viral sequence data, PDB/AlphaFold structures, CELLxGENE Census, OpenTargets, cBioPortal, COSMIC, Enrichr, Bgee, and 8cubeDB mouse specificity/expression metrics. Features include: single-command queries without complex API setup, automatic result formatting, batch query support, integration with pandas DataFrames, and support for both command-line and Python API usage. Optimized for speed and ease of use, making database queries accessible to users without extensive bioinformatics experience. Use cases: quick gene lookups, sequence retrieval, viral dataset downloads, enrichment analysis, disease/drug associations, protein structure access, and rapid database queries in bioinformatics workflows
- **geniml** - Genomic interval machine learning toolkit providing unsupervised methods for building ML models on BED files. Key capabilities include Region2Vec (word2vec-style embeddings of genomic regions and region sets using tokenization and neural language modeling), BEDspace (joint embeddings of regions and metadata labels using StarSpace for cross-modal queries), scEmbed (Region2Vec applied to single-cell ATAC-seq data generating cell-level embeddings for clustering and annotation with scanpy integration), consensus peak building (four statistical methods CC/CCF/ML/HMM for creating reference universes from BED collections), and comprehensive utilities (BBClient for BED caching, BEDshift for genomic randomization preserving context, evaluation metrics for embedding quality, Text2BedNN for neural search backends). Part of BEDbase ecosystem. Supports Python API and CLI workflows, pre-trained models on Hugging Face, and integration with gtars for tokenization. Use cases: region similarity searches, dimension reduction of chromatin accessibility data, scATAC-seq clustering and cell-type annotation, metadata-aware genomic queries, universe construction for standardized references, and any ML task requiring genomic region feature vectors
- **gtars** - High-performance Rust toolkit for genomic interval analysis providing specialized tools for overlap detection using IGD (Integrated Genome Database) indexing, coverage track generation (uniwig module for WIG/BigWig formats), genomic tokenization for machine learning applications (TreeTokenizer for deep learning models), reference sequence management (refget protocol compliance), fragment processing for single-cell genomics (barcode-based splitting and cluster analysis), and fragment scoring against reference datasets. Offers Python bindings with NumPy integration, command-line tools (gtars-cli), and Rust library. Key modules include: tokenizers (convert genomic regions to ML tokens), overlaprs (efficient overlap computation), uniwig (ATAC-seq/ChIP-seq/RNA-seq coverage profiles), refget (GA4GH-compliant sequence digests), bbcache (BEDbase.org integration), scoring (fragment enrichment metrics), and fragsplit (single-cell fragment manipulation). Supports parallel processing, memory-mapped files, streaming for large datasets, and serves as foundation for geniml genomic ML package. Ideal for genomic ML preprocessing, regulatory element analysis, variant annotation, chromatin accessibility profiling, and computational genomics workflows
- **Polars-Bio** - High-performance genomic interval operations and bioinformatics file I/O on Polars DataFrames. Provides overlap, nearest, merge, coverage, complement, and subtract operations for BED/VCF/BAM/GFF intervals. Streaming and cloud-native architecture for large-scale genomic analyses, serving as a faster alternative to bioframe
@@ -67,7 +67,7 @@
### Cheminformatics & Drug Discovery
- **Datamol** - Python library for molecular manipulation and featurization built on RDKit with enhanced workflows and performance optimizations. Provides utilities for molecular I/O (reading/writing SMILES, SDF, MOL files), molecular standardization and sanitization, molecular transformations (tautomer enumeration, stereoisomer generation), molecular featurization (descriptors, fingerprints, graph representations), parallel processing for large datasets, and integration with machine learning pipelines. Features include: optimized RDKit operations, caching for repeated computations, molecular filtering and preprocessing, and seamless integration with pandas DataFrames. Designed for drug discovery and cheminformatics workflows requiring efficient processing of large compound libraries. Use cases: molecular preprocessing for ML models, compound library management, molecular similarity searches, and cheminformatics data pipelines
- **DeepChem** - Molecular machine learning library (PyPI 2.8.0; Python 3.7–3.11) with TensorFlow, PyTorch, and JAX backends. Graph neural networks (GCN, GAT, MPNN, AttentiveFP), 30+ MoleculeNet benchmarks, diverse featurizers (fingerprints, descriptors, graphs), and pretrained models (ChemBERTa, GROVER, MolFormer). Install backend-specific extras (`deepchem[torch]`, `[tensorflow]`, `[jax]`). Use for ADMET/toxicity prediction, materials properties, and transfer learning on small datasets
-- **DiffDock** - State-of-the-art diffusion-based molecular docking method for predicting protein-ligand binding poses and binding affinities. Uses diffusion models to generate diverse, high-quality binding poses without requiring exhaustive search. Key features include: fast inference compared to traditional docking methods, generation of multiple diverse poses, confidence scoring for predictions, and support for flexible ligand docking. Provides pre-trained models and Python API for integration into drug discovery pipelines. Achieves superior performance on standard benchmarks (PDBbind, CASF) compared to traditional docking methods. Use cases: virtual screening, lead optimization, binding pose prediction, structure-based drug design, and initial pose generation for refinement with more expensive methods
+- **DiffDock** - Diffusion-based molecular docking method for predicting protein-ligand binding poses with DiffDock-L confidence scores. Uses diffusion models to generate diverse, high-quality poses without exhaustive search. Key features include: fast GPU inference compared to traditional docking methods, generation of multiple diverse poses, confidence scoring for pose quality, batch CSV input for screening campaigns, and support for protein PDB files or ESMFold sequence inputs with SMILES/SDF/MOL2 ligands. DiffDock does not directly predict binding affinity; combine generated poses with GNINA, MM/GBSA, or free-energy workflows when affinity ranking is required. Use cases: virtual screening, lead optimization, binding pose prediction, structure-based drug design, and initial pose generation for downstream refinement
- **MedChem** - Python library for molecular filtering and prioritization in drug discovery (datamol-io). Apply literature-derived drug-likeness rules (Lipinski, Veber, CNS, lead-like), named structural alert catalogs (PAINS, Brenk, NIBR), complexity thresholds against ZINC-derived percentiles, chemical group detection, and a custom query language for multi-criteria filtering. Returns pandas DataFrames from rule/structural filters and boolean masks from the functional API. Integrates with datamol/RDKit and supports parallel processing. Use cases: compound library triage, hit-to-lead filtering, PAINS deprioritization, screening-deck curation, and lead optimization workflows
- **Molfeat** - Comprehensive Python library providing 100+ molecular featurizers for converting molecules into numerical representations suitable for machine learning. Includes molecular fingerprints (ECFP, MACCS, RDKit, Pharmacophore), molecular descriptors (2D/3D descriptors, constitutional, topological, electronic), graph-based representations (molecular graphs, line graphs), and pre-trained models (MolBERT, ChemBERTa, Uni-Mol embeddings). Features unified API across different featurizer types, caching for performance, parallel processing, and integration with popular ML frameworks (scikit-learn, PyTorch, TensorFlow). Supports both traditional cheminformatics descriptors and modern learned representations. Use cases: molecular property prediction, virtual screening, molecular similarity searches, and preparing molecular data for machine learning models
- **PyTDC** - Python library providing access to Therapeutics Data Commons (TDC), a collection of curated datasets and benchmarks for drug discovery and development. Includes datasets for ADMET prediction (absorption, distribution, metabolism, excretion, toxicity), drug-target interactions, drug-drug interactions, drug response prediction, molecular generation, and retrosynthesis. Features standardized data formats, data loaders with automatic preprocessing, benchmark tasks with evaluation metrics, leaderboards for model comparison, and integration with popular ML frameworks. Provides both single-molecule and drug-pair datasets, covering various stages of drug discovery from target identification to clinical outcomes. Use cases: benchmarking ML models for drug discovery, ADMET prediction model development, drug-target interaction prediction, and drug discovery research
@@ -99,7 +99,7 @@
### Protein Engineering & Design
- **Adaptyv** - Cloud laboratory platform for automated protein testing and validation. Submit protein sequences via API or web interface and receive experimental results in approximately 21 days. Supports multiple assay types including binding assays (biolayer interferometry for protein-target interactions, KD/kon/koff measurements), expression testing (quantify protein expression levels in E. coli, mammalian, yeast, or insect cells), thermostability measurements (DSF and CD for Tm determination and thermal stability profiling), and enzyme activity assays (kinetic parameters, substrate specificity, inhibitor testing). Includes computational optimization tools for pre-screening sequences: NetSolP/SoluProt for solubility prediction, SolubleMPNN for sequence redesign to improve expression, ESM for sequence likelihood scoring, ipTM (AlphaFold-Multimer) for interface stability assessment, and pSAE for aggregation risk quantification. Platform features automated workflows from expression through purification to assay execution with quality control, webhook notifications for experiment completion, batch submission support for high-throughput screening, and comprehensive results with kinetic parameters, confidence metrics, and raw data access. Use cases: antibody affinity maturation, therapeutic protein developability assessment, enzyme engineering and optimization, protein stability improvement, AI-driven protein design validation, library screening for expression and function, lead optimization with experimental feedback, and integration of computational design with wet-lab validation in iterative design-build-test-learn cycles
-- **ESM (Evolutionary Scale Modeling)** - State-of-the-art protein language models from EvolutionaryScale for protein design, structure prediction, and representation learning. Includes ESM3 (1.4B-98B parameter multimodal generative models for simultaneous reasoning across sequence, structure, and function with chain-of-thought generation, inverse folding, and function-conditioned design) and ESM C (300M-6B parameter efficient embedding models 3x faster than ESM2 for similarity analysis, classification, and feature extraction). Supports local inference with open weights, Forge API (`ESM_API_KEY`) for scalable ESM3/ESM C inference, and Biohub-hosted ESMFold2 for all-atom structure prediction. Use cases: novel protein design, structure prediction from sequence, sequence design from structure, protein embeddings, function annotation, variant generation, and directed evolution workflows
+- **ESM (Evolutionary Scale Modeling)** - Protein language models from EvolutionaryScale/Biohub for protein design, structure prediction, and representation learning. Covers current `esm` SDK workflows for local ESM3/ESMC open models, Forge-hosted ESM3 and ESMC inference with `ESM_API_KEY`, Biohub-hosted ESMC embeddings, and ESMFold2 all-atom structure prediction. Use cases: novel protein design, sequence/structure co-design, protein embeddings, function annotation, variant generation, and directed evolution workflows
- **Glycoengineering** - Analyze and engineer protein glycosylation. Scan sequences for N-glycosylation sequons (N-X-S/T), predict O-glycosylation hotspots, and access curated glycoengineering tools (NetOGlyc, GlycoShield, GlycoWorkbench). Use for glycoprotein engineering, therapeutic antibody optimization, and vaccine design
- **Molecular Dynamics** - Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free energy surfaces). Use for structural biology, drug binding studies, and biophysics research
diff --git a/pyproject.toml b/pyproject.toml
index d39ff5c8..07b0c600 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "scientific-agent-skills"
-version = "2.45.0"
+version = "2.46.0"
description = "A set of ready to use Agent Skills for research, science, engineering, analysis, finance and writing."
readme = "README.md"
requires-python = ">=3.13"
diff --git a/skills/cellxgene-census/SKILL.md b/skills/cellxgene-census/SKILL.md
index 6c2a49b2..5a0aebcc 100644
--- a/skills/cellxgene-census/SKILL.md
+++ b/skills/cellxgene-census/SKILL.md
@@ -1,9 +1,11 @@
---
name: cellxgene-census
-description: Query the CELLxGENE Census (61M+ cells) programmatically. Use when you need expression data across tissues, diseases, or cell types from the largest curated single-cell atlas. Best for population-scale queries, reference atlas comparisons. For analyzing your own data use scanpy or scvi-tools.
-license: Unknown
+description: Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.
+allowed-tools: Read Write Edit Bash
+license: MIT
+compatibility: Requires Python >=3.10,<3.13. Examples target cellxgene-census 1.17.x and the 2025-11-08 stable LTS Census; spatial workflows need the spatial extra and TileDB-SOMA >=1.15.5. No authentication is required for public Census data.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,14 +13,16 @@ metadata:
## Overview
-The CZ CELLxGENE Census provides programmatic access to a comprehensive, versioned collection of standardized single-cell genomics data from CZ CELLxGENE Discover. This skill enables efficient querying and analysis of millions of cells across thousands of datasets.
+The CZ CELLxGENE Census provides programmatic access to a comprehensive, versioned collection of standardized single-cell and spatial transcriptomics data from CZ CELLxGENE Discover. This skill enables efficient querying and analysis of public Census releases without downloading whole datasets first.
The Census includes:
-- **61+ million cells** from human and mouse
+- **217+ million total cells** and **125+ million unique cells** in the 2025-11-08 stable LTS release
+- **1,845 datasets** in the 2025-11-08 stable LTS release
+- **Human, mouse, marmoset, rhesus macaque, and chimpanzee** data in the current schema
- **Standardized metadata** (cell types, tissues, diseases, donors)
-- **Raw gene expression** matrices
-- **Pre-calculated embeddings** and statistics
-- **Integration with PyTorch, scanpy, and other analysis tools**
+- **Raw gene expression** matrices and source H5AD lookup/download helpers
+- **Pre-calculated summary counts, embeddings, and spatial data**
+- **Integration with AnnData, Scanpy, TileDB-SOMA, TileDB-SOMA-ML, and other analysis tools**
## When to Use This Skill
@@ -35,12 +39,18 @@ This skill should be used when:
Install the Census API:
```bash
-uv pip install cellxgene-census
+uv pip install "cellxgene-census==1.17.*"
```
-For machine learning workflows, install additional dependencies:
+For spatial workflows:
```bash
-uv pip install cellxgene-census[experimental]
+uv pip install "cellxgene-census[spatial]==1.17.*" "spatialdata[extra]>=0.2.5"
+```
+
+For PyTorch model training, use TileDB-SOMA-ML. The old `cellxgene_census.experimental.ml` loaders are deprecated:
+
+```bash
+uv pip install "cellxgene-census==1.17.*" tiledbsoma-ml
```
## Core Workflow Patterns
@@ -56,15 +66,15 @@ import cellxgene_census
with cellxgene_census.open_soma() as census:
# Work with census data
-# Open specific version for reproducibility
-with cellxgene_census.open_soma(census_version="2023-07-25") as census:
+# Open the current LTS version for reproducibility
+with cellxgene_census.open_soma(census_version="2025-11-08") as census:
# Work with census data
```
**Key points:**
- Use context manager (`with` statement) for automatic cleanup
- Specify `census_version` for reproducible analyses
-- Default opens latest "stable" release
+- `stable` opens the current LTS Census release; `latest` opens the newest weekly release retained for a shorter period
### 2. Exploring Census Information
@@ -72,15 +82,18 @@ Before querying expression data, explore available datasets and metadata.
**Access summary information:**
```python
-# Get summary statistics
+# Get summary statistics as label/value rows
summary = census["census_info"]["summary"].read().concat().to_pandas()
-print(f"Total cells: {summary['total_cell_count'][0]}")
+summary_values = summary.set_index("label")["value"]
+print(f"Total cells: {int(summary_values['total_cell_count']):,}")
+print(f"Unique cells: {int(summary_values['unique_cell_count']):,}")
# Get all datasets
datasets = census["census_info"]["datasets"].read().concat().to_pandas()
-# Filter datasets by criteria
-covid_datasets = datasets[datasets["disease"].str.contains("COVID", na=False)]
+# Get precomputed counts by organism, cell type, tissue, disease, and assay
+summary_counts = census["census_info"]["summary_cell_counts"].read().concat().to_pandas()
+tissue_counts = summary_counts[summary_counts["category"].eq("tissue_general")]
```
**Query cell metadata to understand available data:**
@@ -96,7 +109,13 @@ unique_cell_types = cell_metadata["cell_type"].unique()
print(f"Found {len(unique_cell_types)} cell types in brain")
# Count cells by tissue
-tissue_counts = cell_metadata.groupby("tissue_general").size()
+tissue_metadata = cellxgene_census.get_obs(
+ census,
+ "homo_sapiens",
+ value_filter="is_primary_data == True",
+ column_names=["tissue_general"],
+)
+tissue_counts = tissue_metadata["tissue_general"].value_counts()
```
**Important:** Always filter for `is_primary_data == True` to avoid counting duplicate cells unless specifically analyzing duplicates.
@@ -130,6 +149,7 @@ adata = cellxgene_census.get_anndata(
- Combine conditions with `and`, `or`
- Use `in` for multiple values: `tissue in ['lung', 'liver']`
- Select only needed columns with `obs_column_names`
+- In current LTS releases, `disease` and `disease_ontology_term_id` may contain ` || `-delimited multiple values; inspect available values before relying on exact equality filters for disease cohorts
**Getting metadata separately:**
```python
@@ -156,96 +176,117 @@ For queries exceeding available RAM, use `axis_query()` with iterative processin
import tiledbsoma as soma
# Create axis query
-query = census["census_data"]["homo_sapiens"].axis_query(
+with census["census_data"]["homo_sapiens"].axis_query(
measurement_name="RNA",
obs_query=soma.AxisQuery(
value_filter="tissue_general == 'brain' and is_primary_data == True"
),
var_query=soma.AxisQuery(
value_filter="feature_name in ['FOXP2', 'TBR1', 'SATB2']"
- )
-)
-
-# Iterate through expression matrix in chunks
-iterator = query.X("raw").tables()
-for batch in iterator:
- # batch is a pyarrow.Table with columns:
- # - soma_data: expression value
- # - soma_dim_0: cell (obs) coordinate
- # - soma_dim_1: gene (var) coordinate
- process_batch(batch)
+ ),
+) as query:
+ # Iterate through expression matrix in chunks
+ iterator = query.X("raw").tables()
+ for batch in iterator:
+ # batch is a pyarrow.Table with columns:
+ # - soma_data: expression value
+ # - soma_dim_0: cell (obs) coordinate
+ # - soma_dim_1: gene (var) coordinate
+ process_batch(batch)
```
**Computing incremental statistics:**
```python
+import tiledbsoma as soma
+
# Example: Calculate mean expression
n_observations = 0
sum_values = 0.0
-iterator = query.X("raw").tables()
-for batch in iterator:
- values = batch["soma_data"].to_numpy()
- n_observations += len(values)
- sum_values += values.sum()
+with census["census_data"]["homo_sapiens"].axis_query(
+ measurement_name="RNA",
+ obs_query=soma.AxisQuery(value_filter="tissue_general == 'brain' and is_primary_data == True"),
+ var_query=soma.AxisQuery(value_filter="feature_name in ['FOXP2', 'TBR1', 'SATB2']"),
+) as query:
+ iterator = query.X("raw").tables()
+ for batch in iterator:
+ values = batch["soma_data"].to_numpy()
+ n_observations += len(values)
+ sum_values += values.sum()
mean_expression = sum_values / n_observations
```
### 5. Machine Learning with PyTorch
-For training models, use the experimental PyTorch integration:
+For training models, use TileDB-SOMA-ML. The former `cellxgene_census.experimental.ml` PyTorch loaders are deprecated and scheduled for removal.
```python
-from cellxgene_census.experimental.ml import experiment_dataloader
+import tiledbsoma as soma
+from tiledbsoma_ml import ExperimentDataset, experiment_dataloader
with cellxgene_census.open_soma() as census:
- # Create dataloader
- dataloader = experiment_dataloader(
- census["census_data"]["homo_sapiens"],
+ experiment = census["census_data"]["homo_sapiens"]
+ with experiment.axis_query(
measurement_name="RNA",
- X_name="raw",
- obs_value_filter="tissue_general == 'liver' and is_primary_data == True",
- obs_column_names=["cell_type"],
- batch_size=128,
- shuffle=True,
- )
+ obs_query=soma.AxisQuery(
+ value_filter="tissue_general == 'liver' and is_primary_data == True"
+ ),
+ ) as query:
+ dataset = ExperimentDataset(
+ query=query,
+ layer_name="raw",
+ obs_column_names=["cell_type"],
+ batch_size=128,
+ shuffle=True,
+ )
+ dataloader = experiment_dataloader(dataset)
+
+ # Training loop
+ for epoch in range(num_epochs):
+ dataset.set_epoch(epoch)
+ for X, obs in dataloader:
+ labels = obs["cell_type"]
+
+ # Forward pass
+ outputs = model(X)
+ loss = criterion(outputs, labels)
+
+ # Backward pass
+ optimizer.zero_grad()
+ loss.backward()
+ optimizer.step()
+```
+
+**Train/test splitting:**
+```python
+train_dataset, test_dataset = dataset.random_split(0.8, 0.2, seed=42)
+train_loader = experiment_dataloader(train_dataset, num_workers=2)
+test_loader = experiment_dataloader(test_dataset, num_workers=2)
+```
- # Training loop
- for epoch in range(num_epochs):
- for batch in dataloader:
- X = batch["X"] # Gene expression tensor
- labels = batch["obs"]["cell_type"] # Cell type labels
+Use `batch_size` and `shuffle` on `ExperimentDataset`, not on `torch.utils.data.DataLoader`; `experiment_dataloader()` rejects DataLoader-level `batch_size`, `shuffle`, `sampler`, and `batch_sampler` arguments.
- # Forward pass
- outputs = model(X)
- loss = criterion(outputs, labels)
+### 6. Spatial Census Data
- # Backward pass
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
-```
+Spatial data is available for supported Census releases in a separate `census_spatial_sequencing` collection. Use the spatial extra and a current TileDB-SOMA version when querying Visium or Slide-seq V2 data:
-**Train/test splitting:**
```python
-from cellxgene_census.experimental.ml import ExperimentDataset
-
-# Create dataset from experiment
-dataset = ExperimentDataset(
- experiment_axis_query,
- layer_name="raw",
- obs_column_names=["cell_type"],
- batch_size=128,
-)
+import cellxgene_census
+import tiledbsoma as soma
-# Split into train and test
-train_dataset, test_dataset = dataset.random_split(
- split=[0.8, 0.2],
- seed=42
-)
+with cellxgene_census.open_soma(census_version="2025-11-08") as census:
+ spatial_experiment = census["census_spatial_sequencing"]["homo_sapiens"]
+ with spatial_experiment.axis_query(
+ measurement_name="RNA",
+ obs_query=soma.AxisQuery(
+ value_filter="dataset_id == '4cceac62-9513-42a4-90e5-2878dbb0192c'"
+ ),
+ ) as query:
+ sdata = query.to_spatialdata(X_name="raw")
```
-### 6. Integration with Scanpy
+### 7. Integration with Scanpy
Seamlessly integrate Census data with scanpy workflows:
@@ -273,7 +314,7 @@ sc.tl.umap(adata)
sc.pl.umap(adata, color=["cell_type", "tissue", "disease"])
```
-### 7. Multi-Dataset Integration
+### 8. Multi-Dataset Integration
Query and integrate multiple datasets:
@@ -291,8 +332,9 @@ for tissue in tissues:
adata.obs["tissue"] = tissue
adatas.append(adata)
-# Concatenate
-combined = adatas[0].concatenate(adatas[1:])
+# Concatenate with AnnData's current API
+import anndata as ad
+combined = ad.concat(adatas, label="tissue", keys=tissues)
# Strategy 2: Query multiple datasets directly
adata = cellxgene_census.get_anndata(
@@ -313,7 +355,7 @@ obs_value_filter="cell_type == 'B cell' and is_primary_data == True"
### Specify Census Version for Reproducibility
Always specify the Census version in production analyses:
```python
-census = cellxgene_census.open_soma(census_version="2023-07-25")
+census = cellxgene_census.open_soma(census_version="2025-11-08")
```
### Estimate Query Size Before Loading
@@ -389,10 +431,14 @@ Key fields for filtering:
- `dataset_id`
- `is_primary_data` (Boolean: True = unique cell)
+The current schema includes organism collections beyond human and mouse. Confirm available organisms for the selected release with `list(census["census_data"].keys())`.
+
### Gene Metadata (var)
- `feature_id` (Ensembl gene ID, e.g., "ENSG00000161798")
- `feature_name` (Gene symbol, e.g., "FOXP2")
+- `feature_type`
- `feature_length` (Gene length in base pairs)
+- `nnz`, `n_measured_obs` (availability summaries useful for checking sparsity and coverage)
## Reference Documentation
@@ -414,6 +460,7 @@ Examples and patterns for:
- Small-to-medium queries (AnnData)
- Large queries (out-of-core processing)
- PyTorch integration
+- Spatial Census access patterns
- Scanpy integration workflows
- Multi-dataset integration
- Best practices and common pitfalls
@@ -446,22 +493,26 @@ with cellxgene_census.open_soma() as census:
### Use Case 3: Train Cell Type Classifier
```python
-from cellxgene_census.experimental.ml import experiment_dataloader
+import tiledbsoma as soma
+from tiledbsoma_ml import ExperimentDataset, experiment_dataloader
with cellxgene_census.open_soma() as census:
- dataloader = experiment_dataloader(
- census["census_data"]["homo_sapiens"],
+ experiment = census["census_data"]["homo_sapiens"]
+ with experiment.axis_query(
measurement_name="RNA",
- X_name="raw",
- obs_value_filter="is_primary_data == True",
- obs_column_names=["cell_type"],
- batch_size=128,
- shuffle=True,
- )
-
- # Train model
- for epoch in range(epochs):
- for batch in dataloader:
+ obs_query=soma.AxisQuery(value_filter="is_primary_data == True"),
+ ) as query:
+ dataset = ExperimentDataset(
+ query=query,
+ layer_name="raw",
+ obs_column_names=["cell_type"],
+ batch_size=128,
+ shuffle=True,
+ )
+ dataloader = experiment_dataloader(dataset)
+
+ for X, obs in dataloader:
+ labels = obs["cell_type"]
# Training logic
pass
```
diff --git a/skills/cellxgene-census/references/census_schema.md b/skills/cellxgene-census/references/census_schema.md
index de38701f..6e430f6f 100644
--- a/skills/cellxgene-census/references/census_schema.md
+++ b/skills/cellxgene-census/references/census_schema.md
@@ -2,11 +2,18 @@
## Overview
-The CZ CELLxGENE Census is a versioned collection of single-cell data built on the TileDB-SOMA framework. This reference documents the data structure, available metadata fields, and query syntax.
+The CZ CELLxGENE Census is a versioned collection of single-cell and spatial transcriptomics data built on the TileDB-SOMA framework. This reference documents the data structure, available metadata fields, and query syntax.
+
+Current reference point:
+- Package examples target `cellxgene-census==1.17.*`
+- Current stable LTS Census: `2025-11-08`
+- Census schema version: `2.4.0`
+- CELLxGENE dataset schema version: `7.0.0`
+- Stable LTS package compatibility: `cellxgene-census` 1.17.x
## High-Level Structure
-The Census is organized as a `SOMACollection` with two main components:
+The Census is organized as a `SOMACollection` with these main components:
### 1. census_info
Summary information including:
@@ -18,8 +25,14 @@ Summary information including:
Organism-specific `SOMAExperiment` objects:
- **"homo_sapiens"**: Human single-cell data
- **"mus_musculus"**: Mouse single-cell data
+- **"callithrix_jacchus"**: Common marmoset single-cell data
+- **"macaca_mulatta"**: Rhesus macaque single-cell data
+- **"pan_troglodytes"**: Chimpanzee single-cell data
+
+### 3. census_spatial_sequencing
+Spatial organism-specific `SOMAExperiment` objects for supported releases. Spatial and non-spatial data share core metadata requirements, while spatial observations also include spatial columns such as `array_col`, `array_row`, and `in_tissue`.
-## Data Structure Per Organism
+## Single-Cell Data Structure Per Organism
Each organism experiment contains:
@@ -33,10 +46,23 @@ census["census_data"]["homo_sapiens"].obs
RNA measurement data including:
- **X**: Data matrices with layers:
- `raw`: Raw count data
- - `normalized`: (if available) Normalized counts
- **var**: Gene metadata
- **feature_dataset_presence_matrix**: Sparse boolean array showing which genes were measured in each dataset
+## Spatial Data Structure Per Organism
+
+Spatial data is stored separately from the single-cell Census data:
+```python
+census["census_spatial_sequencing"]["homo_sapiens"]
+```
+
+Each spatial organism experiment contains:
+- `obs`: Spatial observation metadata, including core Census metadata and spatial fields such as `array_col`, `array_row`, and `in_tissue`
+- `ms["RNA"]`: RNA measurement matrices and feature metadata
+- `spatial[scene_id].obsl["loc"]`: point-cloud positions for each scene, with `x`, `y`, and `soma_joinid`
+
+Use `axis_query(...).to_spatialdata(X_name="raw")` when exporting a spatial slice to `spatialdata`.
+
## Cell Metadata Fields (obs)
### Required/Core Fields
@@ -54,6 +80,7 @@ RNA measurement data including:
- `tissue`: Specific tissue name
- `tissue_general`: Broader tissue category (useful for grouping)
- `tissue_ontology_term_id`: Standardized ontology term
+- `tissue_general_ontology_term_id`: Standardized ontology term for the broader tissue category
**Assay:**
- `assay`: Sequencing technology used
@@ -71,7 +98,7 @@ RNA measurement data including:
- `development_stage_ontology_term_id`: Standardized ontology term
**Organism:**
-- `organism`: Scientific name (Homo sapiens, Mus musculus)
+- `organism`: Scientific name (for example, Homo sapiens or Mus musculus)
- `organism_ontology_term_id`: Standardized ontology term
**Technical:**
@@ -88,7 +115,10 @@ census["census_data"]["homo_sapiens"].ms["RNA"].var
- `soma_joinid`: Unique integer identifier for joins
- `feature_id`: Ensembl gene ID (e.g., "ENSG00000161798")
- `feature_name`: Gene symbol (e.g., "FOXP2")
+- `feature_type`: Feature type from the source schema
- `feature_length`: Gene length in base pairs
+- `nnz`: Non-zero count summary
+- `n_measured_obs`: Number of measured observations for the feature
## Value Filter Syntax
@@ -131,6 +161,10 @@ value_filter="(cell_type == 'neuron' or cell_type == 'astrocyte') and disease !=
var_value_filter="feature_name in ['CD4', 'CD8A', 'CD19']"
```
+### Multi-Value Disease Fields
+
+In current LTS releases, `disease` and `disease_ontology_term_id` may contain multiple values delimited by ` || `. Exact equality filters such as `disease == 'COVID-19'` can miss cells whose disease field contains multiple labels. For comprehensive disease queries, first inspect available values with `get_obs()` or `summary_cell_counts`, then choose filters that match the selected release's encoding.
+
## Data Inclusion Criteria
The Census includes all data from CZ CELLxGENE Discover meeting:
@@ -153,12 +187,14 @@ The Census includes:
These may need different normalization approaches.
### Versioning
-Census releases are versioned (e.g., "2023-07-25", "stable"). Always specify version for reproducible analysis:
+Census releases are versioned (e.g., "2025-11-08", "stable", "latest"). Always specify an LTS build date for reproducible analysis:
```python
-census = cellxgene_census.open_soma(census_version="2023-07-25")
+census = cellxgene_census.open_soma(census_version="2025-11-08")
```
-## Dataset Presence Matrix
+`stable` resolves to the current LTS release. `latest` resolves to the newest weekly release, which provides fast access to newly ingested datasets but is retained for a shorter period than LTS releases.
+
+## Feature Dataset Presence Matrix
Access which genes were measured in each dataset:
```python
diff --git a/skills/cellxgene-census/references/common_patterns.md b/skills/cellxgene-census/references/common_patterns.md
index 8ca9ff8a..b96928fb 100644
--- a/skills/cellxgene-census/references/common_patterns.md
+++ b/skills/cellxgene-census/references/common_patterns.md
@@ -101,100 +101,117 @@ Use `axis_query()` for queries that exceed available RAM.
**Pattern: Iterative processing**
```python
-import pyarrow as pa
+import tiledbsoma as soma
# Create query
-query = census["census_data"]["homo_sapiens"].axis_query(
+with census["census_data"]["homo_sapiens"].axis_query(
measurement_name="RNA",
obs_query=soma.AxisQuery(
value_filter="tissue_general == 'brain' and is_primary_data == True"
),
var_query=soma.AxisQuery(
value_filter="feature_name in ['FOXP2', 'TBR1', 'SATB2']"
- )
-)
-
-# Iterate through X matrix in chunks
-iterator = query.X("raw").tables()
-for batch in iterator:
- # Process batch (a pyarrow.Table)
- # batch has columns: soma_data, soma_dim_0, soma_dim_1
- process_batch(batch)
+ ),
+) as query:
+ # Iterate through X matrix in chunks
+ iterator = query.X("raw").tables()
+ for batch in iterator:
+ # Process batch (a pyarrow.Table)
+ # batch has columns: soma_data, soma_dim_0, soma_dim_1
+ process_batch(batch)
```
**Pattern: Incremental statistics (mean/variance)**
```python
+import tiledbsoma as soma
+
# Using Welford's online algorithm
n = 0
mean = 0
M2 = 0
-iterator = query.X("raw").tables()
-for batch in iterator:
- values = batch["soma_data"].to_numpy()
- for x in values:
- n += 1
- delta = x - mean
- mean += delta / n
- delta2 = x - mean
- M2 += delta * delta2
+with census["census_data"]["homo_sapiens"].axis_query(
+ measurement_name="RNA",
+ obs_query=soma.AxisQuery(value_filter="tissue_general == 'brain' and is_primary_data == True"),
+ var_query=soma.AxisQuery(value_filter="feature_name in ['FOXP2', 'TBR1', 'SATB2']"),
+) as query:
+ iterator = query.X("raw").tables()
+ for batch in iterator:
+ values = batch["soma_data"].to_numpy()
+ for x in values:
+ n += 1
+ delta = x - mean
+ mean += delta / n
+ delta2 = x - mean
+ M2 += delta * delta2
variance = M2 / (n - 1) if n > 1 else 0
```
### 4. PyTorch Integration (Machine Learning)
-Use `experiment_dataloader()` for training models.
+Use TileDB-SOMA-ML for training models. The former `cellxgene_census.experimental.ml` loaders are deprecated and scheduled for removal.
**Pattern: Create training dataloader**
```python
-from cellxgene_census.experimental.ml import experiment_dataloader
-import torch
+import tiledbsoma as soma
+from tiledbsoma_ml import ExperimentDataset, experiment_dataloader
with cellxgene_census.open_soma() as census:
- # Create dataloader
- dataloader = experiment_dataloader(
- census["census_data"]["homo_sapiens"],
+ experiment = census["census_data"]["homo_sapiens"]
+ with experiment.axis_query(
measurement_name="RNA",
- X_name="raw",
- obs_value_filter="tissue_general == 'liver' and is_primary_data == True",
- obs_column_names=["cell_type"],
- batch_size=128,
- shuffle=True,
- )
-
- # Training loop
- for epoch in range(num_epochs):
- for batch in dataloader:
- X = batch["X"] # Gene expression
- labels = batch["obs"]["cell_type"] # Cell type labels
- # Train model...
+ obs_query=soma.AxisQuery(
+ value_filter="tissue_general == 'liver' and is_primary_data == True"
+ ),
+ ) as query:
+ dataset = ExperimentDataset(
+ query=query,
+ layer_name="raw",
+ obs_column_names=["cell_type"],
+ batch_size=128,
+ shuffle=True,
+ )
+ dataloader = experiment_dataloader(dataset)
+
+ for epoch in range(num_epochs):
+ dataset.set_epoch(epoch)
+ for X, obs in dataloader:
+ labels = obs["cell_type"]
+ # Train model...
```
**Pattern: Train/test split**
```python
-from cellxgene_census.experimental.ml import ExperimentDataset
-
-# Create dataset from query
-dataset = ExperimentDataset(
- experiment_axis_query,
- layer_name="raw",
- obs_column_names=["cell_type"],
- batch_size=128,
-)
-
# Split data
-train_dataset, test_dataset = dataset.random_split(
- split=[0.8, 0.2],
- seed=42
-)
+train_dataset, test_dataset = dataset.random_split(0.8, 0.2, seed=42)
# Create loaders
-train_loader = experiment_dataloader(train_dataset)
-test_loader = experiment_dataloader(test_dataset)
+train_loader = experiment_dataloader(train_dataset, num_workers=2)
+test_loader = experiment_dataloader(test_dataset, num_workers=2)
+```
+
+Set `batch_size` and `shuffle` on `ExperimentDataset`, not on the PyTorch `DataLoader`.
+
+### 5. Spatial Census Data
+
+Use the `cellxgene-census[spatial]` extra and query the `census_spatial_sequencing` collection for Visium or Slide-seq V2 data.
+
+```python
+import tiledbsoma as soma
+
+with cellxgene_census.open_soma(census_version="2025-11-08") as census:
+ spatial_experiment = census["census_spatial_sequencing"]["homo_sapiens"]
+ with spatial_experiment.axis_query(
+ measurement_name="RNA",
+ obs_query=soma.AxisQuery(
+ value_filter="dataset_id == '4cceac62-9513-42a4-90e5-2878dbb0192c'"
+ ),
+ ) as query:
+ sdata = query.to_spatialdata(X_name="raw")
```
-### 5. Integration Workflows
+### 6. Integration Workflows
**Pattern: Scanpy integration**
```python
@@ -247,7 +264,7 @@ obs_value_filter="cell_type == 'B cell' and is_primary_data == True"
### 2. Specify Census Version
For reproducible analysis, always specify the Census version:
```python
-census = cellxgene_census.open_soma(census_version="2023-07-25")
+census = cellxgene_census.open_soma(census_version="2025-11-08")
```
### 3. Use Context Manager
diff --git a/skills/deeptools/SKILL.md b/skills/deeptools/SKILL.md
index 77dd7baa..cb751129 100644
--- a/skills/deeptools/SKILL.md
+++ b/skills/deeptools/SKILL.md
@@ -2,8 +2,14 @@
name: deeptools
description: NGS analysis toolkit. BAM to bigWig conversion, QC (correlation, PCA, fingerprints), heatmaps/profiles (TSS, peaks), for ChIP-seq, RNA-seq, ATAC-seq visualization.
license: BSD license
+allowed-tools:
+ - Read
+ - Write
+ - Edit
+ - Bash
+compatibility: Requires Python >3.8 and deepTools 3.5.6-compatible dependencies. The upstream project recommends conda/bioconda for full dependency resolution; repo examples use uv with pinned PyPI installs for reproducible command-line workflows.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -70,9 +76,17 @@ See `assets/quick_reference.md` for frequently used commands and parameters.
## Installation
```bash
-uv pip install deeptools
+uv pip install deepTools==3.5.6
```
+Upstream recommends conda/bioconda for full dependency resolution, especially on shared HPC systems:
+
+```bash
+conda install -c conda-forge -c bioconda deeptools
+```
+
+On Apple Silicon, upstream documents either the PyPI route above or an `osx-64` conda environment when native conda packages are unavailable.
+
## Core Workflows
deepTools workflows typically follow this pattern: **QC → Normalization → Comparison/Visualization**
@@ -118,6 +132,8 @@ Use bamCoverage with `--filterRNAstrand` to separate forward and reverse strands
**Important:** NEVER use `--extendReads` for RNA-seq (would extend over splice junctions).
+**Strand note:** `--filterRNAstrand` assumes common dUTP/NSR/NNSR reverse-stranded library preparation. For libraries where read 1 follows the RNA strand, forward/reverse output is inverted; use SAM flag filters when library chemistry differs.
+
Use normalization: CPM for fixed bins, RPKM for gene-level analysis.
Template available: `scripts/workflow_generator.py rnaseq_coverage`
@@ -215,8 +231,8 @@ Choosing the correct normalization is critical for valid comparisons. Consult `r
**Normalization methods:**
- **RPGC**: 1× genome coverage (requires --effectiveGenomeSize)
- **CPM**: Counts per million mapped reads
-- **RPKM**: Reads per kb per million (accounts for region length)
-- **BPM**: Bins per million
+- **RPKM**: Reads per kb per million (per-bin length and library-size scaling)
+- **BPM**: Bins per million, analogous to TPM-style scaling over binned signal
- **None**: Raw counts (not recommended for comparisons)
Full explanation: `references/normalization_methods.md`
@@ -228,6 +244,8 @@ RPGC normalization requires effective genome size. Common values:
| Organism | Assembly | Size | Usage |
|----------|----------|------|-------|
| Human | GRCh38/hg38 | 2,913,022,398 | `--effectiveGenomeSize 2913022398` |
+| Human | T2T/CHM13CAT_v2 | 3,117,292,070 | `--effectiveGenomeSize 3117292070` |
+| Mouse | GRCm39/mm39 | 2,654,621,783 | `--effectiveGenomeSize 2654621783` |
| Mouse | GRCm38/mm10 | 2,652,783,500 | `--effectiveGenomeSize 2652783500` |
| Zebrafish | GRCz11 | 1,368,780,147 | `--effectiveGenomeSize 1368780147` |
| *Drosophila* | dm6 | 142,573,017 | `--effectiveGenomeSize 142573017` |
@@ -241,6 +259,7 @@ Many deepTools commands share these options:
**Performance:**
- `--numberOfProcessors, -p`: Enable parallel processing (always use available cores)
+- `max` / `max/2`: Supported values for `--numberOfProcessors`; useful under schedulers because recent deepTools releases detect CPU affinity more carefully
- `--region`: Process specific regions for testing (e.g., `chr1:1-1000000`)
**Read Filtering:**
@@ -280,12 +299,13 @@ Many deepTools commands share these options:
### RNA-seq Specific
- **Never extend reads** for RNA-seq (would span splice junctions)
-- **Strand-specific**: Use `--filterRNAstrand forward/reverse` for stranded libraries
+- **Strand-specific**: Use `--filterRNAstrand forward/reverse` for common dUTP-style stranded libraries; confirm library orientation before interpreting strand labels
- **Normalization**: CPM for bins, RPKM for genes
### ATAC-seq Specific
- **Apply Tn5 correction**: Use alignmentSieve with `--ATACshift`
+- **Use only proper pairs for shifting**: `--ATACshift` is equivalent to `--shift 4 -5 5 -4` and filters to properly paired fragments
- **Fragment filtering**: Set appropriate min/max fragment lengths
- **Check nucleosome pattern**: Fragment size plot should show ladder pattern
@@ -336,7 +356,7 @@ Complete documentation of all deepTools commands organized by category:
- BAM and bigWig processing tools (9 tools)
- Quality control tools (6 tools)
- Visualization tools (3 tools)
-- Miscellaneous tools (2 tools)
+- Miscellaneous tools (3 tools, including `bigwigAverage`)
Each tool includes:
- Purpose and overview
@@ -476,18 +496,6 @@ When users need detailed information:
- **Normalization**: Consult `references/normalization_methods.md` for method selection
- **Genome sizes**: Reference `references/effective_genome_sizes.md`
-Search references using grep patterns:
-```bash
-# Find tool documentation
-grep -A 20 "^### toolname" references/tools_reference.md
-
-# Find workflow
-grep -A 50 "^## Workflow Name" references/workflows.md
-
-# Find normalization method
-grep -A 15 "^### Method Name" references/normalization_methods.md
-```
-
## Example Interactions
**User: "I need to analyze my ChIP-seq data"**
diff --git a/skills/deeptools/assets/quick_reference.md b/skills/deeptools/assets/quick_reference.md
index 31ce31dc..0a3ad2a9 100644
--- a/skills/deeptools/assets/quick_reference.md
+++ b/skills/deeptools/assets/quick_reference.md
@@ -41,6 +41,8 @@ plotFingerprint -b input.bam chip.bam -o fingerprint.png \
| Organism | Assembly | Size |
|----------|----------|------|
| Human | hg38 | 2913022398 |
+| Human | T2T/CHM13CAT_v2 | 3117292070 |
+| Mouse | mm39 | 2654621783 |
| Mouse | mm10 | 2652783500 |
| Fly | dm6 | 142573017 |
@@ -50,6 +52,11 @@ plotFingerprint -b input.bam chip.bam -o fingerprint.png \
- **CPM**: Counts per million (for fixed bins)
- **RPKM**: Reads per kb per million (for genes)
+## Notes
+
+- `--filterRNAstrand` assumes common dUTP-style reverse-stranded RNA-seq libraries.
+- `--ATACshift` uses only properly paired fragments and is equivalent to `--shift 4 -5 5 -4`.
+
## Typical Workflow
1. **QC**: plotFingerprint, plotCorrelation
diff --git a/skills/deeptools/references/effective_genome_sizes.md b/skills/deeptools/references/effective_genome_sizes.md
index b4c70315..361732de 100644
--- a/skills/deeptools/references/effective_genome_sizes.md
+++ b/skills/deeptools/references/effective_genome_sizes.md
@@ -23,12 +23,14 @@ Effective genome size refers to the length of the "mappable" genome - regions th
|----------|----------|----------------|--------------|
| Human | GRCh38/hg38 | 2,913,022,398 | `--effectiveGenomeSize 2913022398` |
| Human | GRCh37/hg19 | 2,864,785,220 | `--effectiveGenomeSize 2864785220` |
-| Mouse | GRCm39/mm39 | 2,654,621,837 | `--effectiveGenomeSize 2654621837` |
+| Human | T2T/CHM13CAT_v2 | 3,117,292,070 | `--effectiveGenomeSize 3117292070` |
+| Mouse | GRCm39/mm39 | 2,654,621,783 | `--effectiveGenomeSize 2654621783` |
| Mouse | GRCm38/mm10 | 2,652,783,500 | `--effectiveGenomeSize 2652783500` |
| Zebrafish | GRCz11 | 1,368,780,147 | `--effectiveGenomeSize 1368780147` |
| *Drosophila* | dm6 | 142,573,017 | `--effectiveGenomeSize 142573017` |
| *C. elegans* | WBcel235/ce11 | 100,286,401 | `--effectiveGenomeSize 100286401` |
| *C. elegans* | ce10 | 100,258,171 | `--effectiveGenomeSize 100258171` |
+| *Arabidopsis thaliana* | TAIR10 | 119,482,012 | `--effectiveGenomeSize 119482012` |
### Human (GRCh38) by Read Length
@@ -80,9 +82,9 @@ computeGCBias --bamfile input.bam \
## Choosing the Right Value
-**For most analyses:** Use the non-N bases method value for your reference genome
+**For most analyses with multimapping reads retained:** Use the non-N bases method value for your reference genome
-**For filtered data:** If you apply strict quality filters or remove multimapping reads, consider using the read-length-specific values
+**For filtered data:** If you apply MAPQ filters or remove multimapping reads, consider read-length-specific mappability values
**When unsure:** Use the conservative non-N bases value - it's more widely applicable
diff --git a/skills/deeptools/references/normalization_methods.md b/skills/deeptools/references/normalization_methods.md
index dd84096f..5b214e21 100644
--- a/skills/deeptools/references/normalization_methods.md
+++ b/skills/deeptools/references/normalization_methods.md
@@ -81,7 +81,7 @@ bamCoverage --bam input.bam --outFileName output.bw \
**Formula:** `(Number of reads in bin) / (Sum of all reads in bins in millions)`
-**Key difference from CPM:** Only considers reads that fall within the analyzed bins, not all mapped reads.
+**Key difference from CPM:** deepTools scales by the sum of reads across all bins, analogous to TPM-style scaling for RNA-seq signal tracks.
**When to use:**
- Similar to CPM, but when you want to exclude reads outside analyzed regions
@@ -108,9 +108,9 @@ bamCoverage --bam input.bam --outFileName output.bw \
### 4. RPGC (Reads Per Genomic Content)
-**Formula:** `(Number of reads × Scaling factor) / Effective genome size`
+**Formula:** `(Number of reads per bin) / scaling factor for 1× average genomic coverage`
-**Scaling factor:** Calculated to achieve 1× genomic coverage (1 read per base)
+**Scaling factor:** deepTools estimates sequencing depth as `(total mapped reads × fragment length) / effective genome size`, then applies the inverse to match 1× average coverage.
**When to use:**
- Want comparable coverage values across samples
@@ -138,6 +138,7 @@ bamCoverage --bam input.bam --outFileName output.bw \
**Cons:**
- Requires knowing effective genome size
+- Effective genome size should change if blacklists, MAPQ filters, or multimapper removal substantially change the mappable space
- Assumes uniform coverage (not true for ChIP-seq with peaks)
---
@@ -346,6 +347,19 @@ bamCoverage --bam input.bam --outFileName output.bw \
**When to use:** Sex chromosomes in mixed-sex samples, mitochondrial DNA, or chromosomes with unusual coverage.
+### Exact Scaling
+
+By default, deepTools can sample reads to estimate scaling factors after filtering. Use `--exactScaling` when rare filtered regions are expected to make sampling inaccurate.
+
+```bash
+bamCoverage --bam input.bam --outFileName output.bw \
+ --normalizeUsing RPGC \
+ --effectiveGenomeSize 2913022398 \
+ --exactScaling
+```
+
+**Tradeoff:** More accurate scaling for unusual filtering patterns, but slower because all reads are processed for scaling.
+
---
## Common Pitfalls
diff --git a/skills/deeptools/references/tools_reference.md b/skills/deeptools/references/tools_reference.md
index 6b39614c..e9ca80ab 100644
--- a/skills/deeptools/references/tools_reference.md
+++ b/skills/deeptools/references/tools_reference.md
@@ -75,10 +75,12 @@ Converts BAM alignment files into normalized coverage tracks in bigWig or bedGra
- `--Offset`: Position-specific offsets (useful for RiboSeq, GROseq)
- `--filterRNAstrand`: Separate forward/reverse strand reads
- `--ignoreForNormalization`: Exclude chromosomes from normalization (e.g., sex chromosomes)
+- `--exactScaling`: Process all reads when sampling-based scaling may be inaccurate
- `--numberOfProcessors, -p`: Parallel processing
**Important Notes:**
- For RNA-seq: Do NOT use --extendReads (would extend over splice junctions)
+- `--filterRNAstrand` assumes common dUTP/NSR/NNSR reverse-stranded libraries; verify library orientation before interpreting forward/reverse tracks
- For ChIP-seq: Use --extendReads with smaller bin sizes
- Never apply --ignoreDuplicates after GC bias correction
@@ -181,7 +183,13 @@ Filters BAM files by various quality metrics on-the-fly. Useful for creating fil
- `--minFragmentLength / --maxFragmentLength`: Fragment length filters
- `--samFlagInclude / --samFlagExclude`: SAM flag filtering
- `--shift`: Shift reads (e.g., for ATACseq Tn5 correction)
-- `--ATACshift`: Automatically shift for ATAC-seq data
+- `--ATACshift`: Automatically shift for ATAC-seq data; equivalent to `--shift 4 -5 5 -4`
+- `--BED`: Write BEDPE output instead of BAM/CRAM
+- `--filterMetrics`: Save counts before/after filtering
+
+**Important Notes:**
+- `--shift` and `--ATACshift` use only properly paired reads.
+- Adjust effective genome size if blacklisted regions are excluded before RPGC normalization.
---
@@ -203,8 +211,9 @@ Calculates scores per genomic region and prepares matrices for plotHeatmap and p
- `-bs, --binSize`: Bin size for averaging scores
- `--skipZeros`: Skip regions with all zeros
- `--minThreshold / --maxThreshold`: Filter by signal intensity
-- `--sortRegions`: ascending, descending, keep, no
+- `--sortRegions`: ascend, descend, keep, no
- `--sortUsing`: mean, median, max, min, sum, region_length
+- `--sortUsingSamples`: Limit sorting to selected sample columns
- `-p, --numberOfProcessors`: Parallel processing
- `--averageTypeBins`: Statistical method (mean, median, min, max, sum, std)
@@ -212,6 +221,10 @@ Calculates scores per genomic region and prepares matrices for plotHeatmap and p
- `--outFileNameMatrix`: Export tab-delimited data
- `--outFileSortedRegions`: Save filtered/sorted BED file
+**Important Notes:**
+- Use `--sortRegions keep` if output order must match the input BED/GTF order.
+- Matrices from deepTools 3.x include labels and are not backward compatible with pre-3.0 plotting tools.
+
**Common Usage:**
```bash
# TSS analysis
@@ -472,6 +485,29 @@ plotEnrichment -b Input.bam H3K4me3.bam \
## Miscellaneous Tools
+### bigwigAverage
+
+Averages multiple bigWig tracks by partitioning the genome into equal-sized bins, optionally applying scale factors before averaging.
+
+**Key Parameters:**
+- `--bigwigs, -b`: Input bigWig files
+- `--outFileName, -o`: Output file name
+- `--outFileFormat, -of`: bigwig or bedgraph
+- `--scaleFactors`: Colon-separated scale factors, such as `0.7:1`
+- `--skipNonCoveredRegions, --skipNAs`: Skip missing regions instead of treating them as zero
+- `--binSize, -bs`: Bin size for averaging
+- `--region, -r`: Limit processing to a test region
+- `--blackListFileName, -bl`: Exclude blacklisted regions
+- `--numberOfProcessors, -p`: Parallel processing
+
+**Common Usage:**
+```bash
+bigwigAverage -b rep1.bw rep2.bw -o average.bw \
+ --scaleFactors 1:0.9 --binSize 50
+```
+
+---
+
### computeMatrixOperations
Advanced matrix manipulation tool for combining or subsetting matrices from computeMatrix. Enables complex multi-sample, multi-region analyses.
diff --git a/skills/deeptools/references/workflows.md b/skills/deeptools/references/workflows.md
index 2bcc6ff4..47e807d4 100644
--- a/skills/deeptools/references/workflows.md
+++ b/skills/deeptools/references/workflows.md
@@ -267,7 +267,7 @@ bamCoverage \
--numberOfProcessors 8
```
-**Important:** Do NOT use `--extendReads` for RNA-seq (would extend over splice junctions).
+**Important:** Do NOT use `--extendReads` for RNA-seq (would extend over splice junctions). `--filterRNAstrand` assumes common dUTP/NSR/NNSR reverse-stranded library prep; for other chemistries, confirm orientation or use SAM flag filters.
---
@@ -361,6 +361,8 @@ alignmentSieve \
--ignoreDuplicates
```
+**Note:** `--ATACshift` is equivalent to `--shift 4 -5 5 -4` and uses only properly paired fragments.
+
---
### Step 2: Generate Coverage Track
diff --git a/skills/deeptools/scripts/workflow_generator.py b/skills/deeptools/scripts/workflow_generator.py
index 03e15127..884eddab 100644
--- a/skills/deeptools/scripts/workflow_generator.py
+++ b/skills/deeptools/scripts/workflow_generator.py
@@ -6,9 +6,14 @@ Generates bash script templates for common deepTools workflows.
"""
import argparse
+import re
+import shlex
import sys
+SAFE_PATH_PATTERN = re.compile(r"^[A-Za-z0-9._/-]+$")
+
+
WORKFLOWS = {
'chipseq_qc': {
'name': 'ChIP-seq Quality Control',
@@ -29,70 +34,120 @@ WORKFLOWS = {
}
+def sanitize_path(value, default, label):
+ """Return a shell-safe path-like value for generated workflow scripts."""
+ value = default if value in (None, "") else str(value)
+ if not SAFE_PATH_PATTERN.fullmatch(value):
+ raise ValueError(
+ f"{label} contains unsupported characters. Use letters, numbers, '/', '.', '_' or '-'."
+ )
+ if any(part == ".." for part in value.split("/")):
+ raise ValueError(f"{label} must not contain '..' path segments.")
+ return value
+
+
+def sanitize_path_list(value, default, label):
+ """Parse and validate a space-separated list of path-like values."""
+ raw_values = default if value in (None, "") else shlex.split(str(value))
+ if not raw_values:
+ raise ValueError(f"{label} must contain at least one file path.")
+ return [sanitize_path(item, item, label) for item in raw_values]
+
+
+def sanitize_positive_int(value, label):
+ """Validate numeric workflow settings before script interpolation."""
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(f"{label} must be an integer.") from exc
+ if parsed < 1:
+ raise ValueError(f"{label} must be >= 1.")
+ return parsed
+
+
+def shell_literal(value):
+ """Quote a sanitized value for use in a generated bash assignment."""
+ return shlex.quote(str(value))
+
+
+def shell_array(values):
+ """Render sanitized values as a bash array literal."""
+ return " ".join(shell_literal(value) for value in values)
+
+
+def runnable_script_path(output_file):
+ """Return a quoted path suitable for the generated run hint."""
+ if output_file.startswith("/"):
+ return shell_literal(output_file)
+ return f"./{shell_literal(output_file)}"
+
+
def generate_chipseq_qc_workflow(output_file, params):
"""Generate ChIP-seq QC workflow script."""
script = f"""#!/bin/bash
+set -euo pipefail
+
# deepTools ChIP-seq Quality Control Workflow
# Generated by deepTools workflow generator
# Configuration
-INPUT_BAM="{params.get('input_bam', 'Input.bam')}"
-CHIP_BAM=("{params.get('chip_bams', 'ChIP1.bam ChIP2.bam')}")
+INPUT_BAM={shell_literal(params['input_bam'])}
+CHIP_BAM=({shell_array(params['chip_bams'])})
GENOME_SIZE={params.get('genome_size', '2913022398')}
THREADS={params.get('threads', '8')}
-OUTPUT_DIR="{params.get('output_dir', 'deeptools_qc')}"
+OUTPUT_DIR={shell_literal(params['output_dir'])}
# Create output directory
-mkdir -p $OUTPUT_DIR
+mkdir -p "$OUTPUT_DIR"
echo "=== Starting ChIP-seq QC workflow ==="
# Step 1: Correlation analysis
echo "Step 1: Computing correlation matrix..."
multiBamSummary bins \\
- --bamfiles $INPUT_BAM ${{CHIP_BAM[@]}} \\
- -o $OUTPUT_DIR/readCounts.npz \\
- --numberOfProcessors $THREADS
+ --bamfiles "$INPUT_BAM" "${{CHIP_BAM[@]}}" \\
+ -o "$OUTPUT_DIR/readCounts.npz" \\
+ --numberOfProcessors "$THREADS"
echo "Step 2: Generating correlation heatmap..."
plotCorrelation \\
- -in $OUTPUT_DIR/readCounts.npz \\
+ -in "$OUTPUT_DIR/readCounts.npz" \\
--corMethod pearson \\
--whatToShow heatmap \\
- --plotFile $OUTPUT_DIR/correlation_heatmap.png \\
+ --plotFile "$OUTPUT_DIR/correlation_heatmap.png" \\
--plotNumbers
echo "Step 3: Generating PCA plot..."
plotPCA \\
- -in $OUTPUT_DIR/readCounts.npz \\
- -o $OUTPUT_DIR/PCA_plot.png \\
+ -in "$OUTPUT_DIR/readCounts.npz" \\
+ -o "$OUTPUT_DIR/PCA_plot.png" \\
-T "PCA of ChIP-seq samples"
# Step 2: Coverage assessment
echo "Step 4: Assessing coverage..."
plotCoverage \\
- --bamfiles $INPUT_BAM ${{CHIP_BAM[@]}} \\
- --plotFile $OUTPUT_DIR/coverage.png \\
+ --bamfiles "$INPUT_BAM" "${{CHIP_BAM[@]}}" \\
+ --plotFile "$OUTPUT_DIR/coverage.png" \\
--ignoreDuplicates \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
# Step 3: Fragment size (for paired-end data)
echo "Step 5: Analyzing fragment sizes..."
bamPEFragmentSize \\
- --bamfiles $INPUT_BAM ${{CHIP_BAM[@]}} \\
- --histogram $OUTPUT_DIR/fragmentSizes.png \\
+ --bamfiles "$INPUT_BAM" "${{CHIP_BAM[@]}}" \\
+ --histogram "$OUTPUT_DIR/fragmentSizes.png" \\
--plotTitle "Fragment Size Distribution"
# Step 4: ChIP signal strength
echo "Step 6: Evaluating ChIP enrichment..."
plotFingerprint \\
- --bamfiles $INPUT_BAM ${{CHIP_BAM[@]}} \\
- --plotFile $OUTPUT_DIR/fingerprint.png \\
+ --bamfiles "$INPUT_BAM" "${{CHIP_BAM[@]}}" \\
+ --plotFile "$OUTPUT_DIR/fingerprint.png" \\
--extendReads 200 \\
--ignoreDuplicates \\
- --numberOfProcessors $THREADS \\
- --outQualityMetrics $OUTPUT_DIR/fingerprint_metrics.txt
+ --numberOfProcessors "$THREADS" \\
+ --outQualityMetrics "$OUTPUT_DIR/fingerprint_metrics.txt"
echo "=== ChIP-seq QC workflow complete ==="
echo "Results are in: $OUTPUT_DIR"
@@ -108,20 +163,22 @@ def generate_chipseq_analysis_workflow(output_file, params):
"""Generate complete ChIP-seq analysis workflow script."""
script = f"""#!/bin/bash
+set -euo pipefail
+
# deepTools ChIP-seq Complete Analysis Workflow
# Generated by deepTools workflow generator
# Configuration
-INPUT_BAM="{params.get('input_bam', 'Input.bam')}"
-CHIP_BAM="{params.get('chip_bam', 'ChIP.bam')}"
-GENES_BED="{params.get('genes_bed', 'genes.bed')}"
-PEAKS_BED="{params.get('peaks_bed', 'peaks.bed')}"
+INPUT_BAM={shell_literal(params['input_bam'])}
+CHIP_BAM={shell_literal(params['chip_bam'])}
+GENES_BED={shell_literal(params['genes_bed'])}
+PEAKS_BED={shell_literal(params['peaks_bed'])}
GENOME_SIZE={params.get('genome_size', '2913022398')}
THREADS={params.get('threads', '8')}
-OUTPUT_DIR="{params.get('output_dir', 'chipseq_analysis')}"
+OUTPUT_DIR={shell_literal(params['output_dir'])}
# Create output directory
-mkdir -p $OUTPUT_DIR
+mkdir -p "$OUTPUT_DIR"
echo "=== Starting ChIP-seq analysis workflow ==="
@@ -129,57 +186,57 @@ echo "=== Starting ChIP-seq analysis workflow ==="
echo "Step 1: Generating coverage tracks..."
bamCoverage \\
- --bam $INPUT_BAM \\
- --outFileName $OUTPUT_DIR/Input_coverage.bw \\
+ --bam "$INPUT_BAM" \\
+ --outFileName "$OUTPUT_DIR/Input_coverage.bw" \\
--normalizeUsing RPGC \\
- --effectiveGenomeSize $GENOME_SIZE \\
+ --effectiveGenomeSize "$GENOME_SIZE" \\
--binSize 10 \\
--extendReads 200 \\
--ignoreDuplicates \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
bamCoverage \\
- --bam $CHIP_BAM \\
- --outFileName $OUTPUT_DIR/ChIP_coverage.bw \\
+ --bam "$CHIP_BAM" \\
+ --outFileName "$OUTPUT_DIR/ChIP_coverage.bw" \\
--normalizeUsing RPGC \\
- --effectiveGenomeSize $GENOME_SIZE \\
+ --effectiveGenomeSize "$GENOME_SIZE" \\
--binSize 10 \\
--extendReads 200 \\
--ignoreDuplicates \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
# Step 2: Create log2 ratio track
echo "Step 2: Creating log2 ratio track..."
bamCompare \\
- --bamfile1 $CHIP_BAM \\
- --bamfile2 $INPUT_BAM \\
- --outFileName $OUTPUT_DIR/ChIP_vs_Input_log2ratio.bw \\
+ --bamfile1 "$CHIP_BAM" \\
+ --bamfile2 "$INPUT_BAM" \\
+ --outFileName "$OUTPUT_DIR/ChIP_vs_Input_log2ratio.bw" \\
--operation log2 \\
--scaleFactorsMethod readCount \\
--binSize 10 \\
--extendReads 200 \\
--ignoreDuplicates \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
# Step 3: Compute matrix around TSS
echo "Step 3: Computing matrix around TSS..."
computeMatrix reference-point \\
--referencePoint TSS \\
- --scoreFileName $OUTPUT_DIR/ChIP_coverage.bw \\
- --regionsFileName $GENES_BED \\
+ --scoreFileName "$OUTPUT_DIR/ChIP_coverage.bw" \\
+ --regionsFileName "$GENES_BED" \\
--beforeRegionStartLength 3000 \\
--afterRegionStartLength 3000 \\
--binSize 10 \\
--sortRegions descend \\
--sortUsing mean \\
- --outFileName $OUTPUT_DIR/matrix_TSS.gz \\
- --numberOfProcessors $THREADS
+ --outFileName "$OUTPUT_DIR/matrix_TSS.gz" \\
+ --numberOfProcessors "$THREADS"
# Step 4: Generate heatmap
echo "Step 4: Generating heatmap..."
plotHeatmap \\
- --matrixFile $OUTPUT_DIR/matrix_TSS.gz \\
- --outFileName $OUTPUT_DIR/heatmap_TSS.png \\
+ --matrixFile "$OUTPUT_DIR/matrix_TSS.gz" \\
+ --outFileName "$OUTPUT_DIR/heatmap_TSS.png" \\
--colorMap RdBu \\
--whatToShow 'plot, heatmap and colorbar' \\
--yAxisLabel "Genes" \\
@@ -191,8 +248,8 @@ plotHeatmap \\
# Step 5: Generate profile plot
echo "Step 5: Generating profile plot..."
plotProfile \\
- --matrixFile $OUTPUT_DIR/matrix_TSS.gz \\
- --outFileName $OUTPUT_DIR/profile_TSS.png \\
+ --matrixFile "$OUTPUT_DIR/matrix_TSS.gz" \\
+ --outFileName "$OUTPUT_DIR/profile_TSS.png" \\
--plotType lines \\
--perGroup \\
--colors blue \\
@@ -204,11 +261,11 @@ plotProfile \\
if [ -f "$PEAKS_BED" ]; then
echo "Step 6: Calculating enrichment at peaks..."
plotEnrichment \\
- --bamfiles $INPUT_BAM $CHIP_BAM \\
- --BED $PEAKS_BED \\
+ --bamfiles "$INPUT_BAM" "$CHIP_BAM" \\
+ --BED "$PEAKS_BED" \\
--labels Input ChIP \\
- --plotFile $OUTPUT_DIR/enrichment.png \\
- --outRawCounts $OUTPUT_DIR/enrichment_counts.tab \\
+ --plotFile "$OUTPUT_DIR/enrichment.png" \\
+ --outRawCounts "$OUTPUT_DIR/enrichment_counts.tab" \\
--extendReads 200 \\
--ignoreDuplicates
fi
@@ -227,37 +284,39 @@ def generate_rnaseq_coverage_workflow(output_file, params):
"""Generate RNA-seq coverage workflow script."""
script = f"""#!/bin/bash
+set -euo pipefail
+
# deepTools RNA-seq Coverage Workflow
# Generated by deepTools workflow generator
# Configuration
-RNASEQ_BAM="{params.get('rnaseq_bam', 'rnaseq.bam')}"
+RNASEQ_BAM={shell_literal(params['rnaseq_bam'])}
THREADS={params.get('threads', '8')}
-OUTPUT_DIR="{params.get('output_dir', 'rnaseq_coverage')}"
+OUTPUT_DIR={shell_literal(params['output_dir'])}
# Create output directory
-mkdir -p $OUTPUT_DIR
+mkdir -p "$OUTPUT_DIR"
echo "=== Starting RNA-seq coverage workflow ==="
# Generate strand-specific coverage tracks
echo "Step 1: Generating forward strand coverage..."
bamCoverage \\
- --bam $RNASEQ_BAM \\
- --outFileName $OUTPUT_DIR/forward_coverage.bw \\
+ --bam "$RNASEQ_BAM" \\
+ --outFileName "$OUTPUT_DIR/forward_coverage.bw" \\
--filterRNAstrand forward \\
--normalizeUsing CPM \\
--binSize 1 \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
echo "Step 2: Generating reverse strand coverage..."
bamCoverage \\
- --bam $RNASEQ_BAM \\
- --outFileName $OUTPUT_DIR/reverse_coverage.bw \\
+ --bam "$RNASEQ_BAM" \\
+ --outFileName "$OUTPUT_DIR/reverse_coverage.bw" \\
--filterRNAstrand reverse \\
--normalizeUsing CPM \\
--binSize 1 \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
echo "=== RNA-seq coverage workflow complete ==="
echo "Results are in: $OUTPUT_DIR"
@@ -276,49 +335,51 @@ def generate_atacseq_workflow(output_file, params):
"""Generate ATAC-seq workflow script."""
script = f"""#!/bin/bash
+set -euo pipefail
+
# deepTools ATAC-seq Analysis Workflow
# Generated by deepTools workflow generator
# Configuration
-ATAC_BAM="{params.get('atac_bam', 'atacseq.bam')}"
-PEAKS_BED="{params.get('peaks_bed', 'peaks.bed')}"
+ATAC_BAM={shell_literal(params['atac_bam'])}
+PEAKS_BED={shell_literal(params['peaks_bed'])}
GENOME_SIZE={params.get('genome_size', '2913022398')}
THREADS={params.get('threads', '8')}
-OUTPUT_DIR="{params.get('output_dir', 'atacseq_analysis')}"
+OUTPUT_DIR={shell_literal(params['output_dir'])}
# Create output directory
-mkdir -p $OUTPUT_DIR
+mkdir -p "$OUTPUT_DIR"
echo "=== Starting ATAC-seq analysis workflow ==="
# Step 1: Shift reads for Tn5 correction
echo "Step 1: Applying Tn5 offset correction..."
alignmentSieve \\
- --bam $ATAC_BAM \\
- --outFile $OUTPUT_DIR/atacseq_shifted.bam \\
+ --bam "$ATAC_BAM" \\
+ --outFile "$OUTPUT_DIR/atacseq_shifted.bam" \\
--ATACshift \\
--minFragmentLength 38 \\
--maxFragmentLength 2000 \\
--ignoreDuplicates
# Index the shifted BAM
-samtools index $OUTPUT_DIR/atacseq_shifted.bam
+samtools index "$OUTPUT_DIR/atacseq_shifted.bam"
# Step 2: Generate coverage track
echo "Step 2: Generating coverage track..."
bamCoverage \\
- --bam $OUTPUT_DIR/atacseq_shifted.bam \\
- --outFileName $OUTPUT_DIR/atacseq_coverage.bw \\
+ --bam "$OUTPUT_DIR/atacseq_shifted.bam" \\
+ --outFileName "$OUTPUT_DIR/atacseq_coverage.bw" \\
--normalizeUsing RPGC \\
- --effectiveGenomeSize $GENOME_SIZE \\
+ --effectiveGenomeSize "$GENOME_SIZE" \\
--binSize 1 \\
- --numberOfProcessors $THREADS
+ --numberOfProcessors "$THREADS"
# Step 3: Fragment size analysis
echo "Step 3: Analyzing fragment sizes..."
bamPEFragmentSize \\
- --bamfiles $ATAC_BAM \\
- --histogram $OUTPUT_DIR/fragmentSizes.png \\
+ --bamfiles "$ATAC_BAM" \\
+ --histogram "$OUTPUT_DIR/fragmentSizes.png" \\
--maxFragmentLength 1000
# Step 4: Compute matrix at peaks (if peaks provided)
@@ -326,18 +387,18 @@ if [ -f "$PEAKS_BED" ]; then
echo "Step 4: Computing matrix at peaks..."
computeMatrix reference-point \\
--referencePoint center \\
- --scoreFileName $OUTPUT_DIR/atacseq_coverage.bw \\
- --regionsFileName $PEAKS_BED \\
+ --scoreFileName "$OUTPUT_DIR/atacseq_coverage.bw" \\
+ --regionsFileName "$PEAKS_BED" \\
--beforeRegionStartLength 2000 \\
--afterRegionStartLength 2000 \\
--binSize 10 \\
- --outFileName $OUTPUT_DIR/matrix_peaks.gz \\
- --numberOfProcessors $THREADS
+ --outFileName "$OUTPUT_DIR/matrix_peaks.gz" \\
+ --numberOfProcessors "$THREADS"
echo "Step 5: Generating heatmap..."
plotHeatmap \\
- --matrixFile $OUTPUT_DIR/matrix_peaks.gz \\
- --outFileName $OUTPUT_DIR/heatmap_peaks.png \\
+ --matrixFile "$OUTPUT_DIR/matrix_peaks.gz" \\
+ --outFileName "$OUTPUT_DIR/heatmap_peaks.png" \\
--colorMap YlOrRd \\
--refPointLabel "Peak Center" \\
--heatmapHeight 15
@@ -419,34 +480,39 @@ Examples:
parser.print_help()
sys.exit(1)
- # Prepare parameters
- params = {
- 'threads': args.threads,
- 'genome_size': args.genome_size,
- 'output_dir': args.output_dir or f"{args.workflow}_output",
- 'input_bam': args.input_bam,
- 'chip_bam': args.chip_bam,
- 'chip_bams': args.chip_bams,
- 'rnaseq_bam': args.rnaseq_bam,
- 'atac_bam': args.atac_bam,
- 'genes_bed': args.genes_bed,
- 'peaks_bed': args.peaks_bed,
- }
+ # Prepare parameters. Values are validated before they are interpolated
+ # into generated bash so filenames cannot smuggle shell metacharacters.
+ try:
+ output_file = sanitize_path(args.output, 'deeptools_workflow.sh', 'output script')
+ params = {
+ 'threads': sanitize_positive_int(args.threads, 'threads'),
+ 'genome_size': sanitize_positive_int(args.genome_size, 'genome size'),
+ 'output_dir': sanitize_path(args.output_dir, f"{args.workflow}_output", 'output directory'),
+ 'input_bam': sanitize_path(args.input_bam, 'Input.bam', 'input BAM'),
+ 'chip_bam': sanitize_path(args.chip_bam, 'ChIP.bam', 'ChIP BAM'),
+ 'chip_bams': sanitize_path_list(args.chip_bams, ['ChIP1.bam', 'ChIP2.bam'], 'ChIP BAMs'),
+ 'rnaseq_bam': sanitize_path(args.rnaseq_bam, 'rnaseq.bam', 'RNA-seq BAM'),
+ 'atac_bam': sanitize_path(args.atac_bam, 'atacseq.bam', 'ATAC-seq BAM'),
+ 'genes_bed': sanitize_path(args.genes_bed, 'genes.bed', 'genes BED'),
+ 'peaks_bed': sanitize_path(args.peaks_bed, 'peaks.bed', 'peaks BED'),
+ }
+ except ValueError as exc:
+ parser.error(str(exc))
# Generate workflow
if args.workflow == 'chipseq_qc':
- message = generate_chipseq_qc_workflow(args.output, params)
+ message = generate_chipseq_qc_workflow(output_file, params)
elif args.workflow == 'chipseq_analysis':
- message = generate_chipseq_analysis_workflow(args.output, params)
+ message = generate_chipseq_analysis_workflow(output_file, params)
elif args.workflow == 'rnaseq_coverage':
- message = generate_rnaseq_coverage_workflow(args.output, params)
+ message = generate_rnaseq_coverage_workflow(output_file, params)
elif args.workflow == 'atacseq':
- message = generate_atacseq_workflow(args.output, params)
+ message = generate_atacseq_workflow(output_file, params)
print(message)
print(f"\nTo run the workflow:")
- print(f" chmod +x {args.output}")
- print(f" ./{args.output}")
+ print(f" chmod +x {shell_literal(output_file)}")
+ print(f" {runnable_script_path(output_file)}")
print(f"\nNote: Edit the script to customize file paths and parameters.")
diff --git a/skills/diffdock/SKILL.md b/skills/diffdock/SKILL.md
index 2477a009..2be6b0c2 100644
--- a/skills/diffdock/SKILL.md
+++ b/skills/diffdock/SKILL.md
@@ -1,9 +1,17 @@
---
name: diffdock
-description: Diffusion-based molecular docking. Predict protein-ligand binding poses from PDB/SMILES, confidence scores, virtual screening, for structure-based drug design. Not for affinity prediction.
+description: DiffDock and DiffDock-L molecular docking. Use for protein-small-molecule pose prediction from PDB or sequence plus SMILES/SDF/MOL2, batch docking, virtual screening, and pose-confidence interpretation. Not for binding affinity prediction.
+allowed-tools:
+ - Read
+ - Write
+ - Edit
+ - Bash
+ - Glob
+ - Grep
+compatibility: Requires the DiffDock repository, Python 3.9 environment from upstream environment.yml or the official Docker image, RDKit, PyTorch/PyG, and optional CUDA GPU acceleration. Current guidance targets DiffDock v1.1.3 / DiffDock-L.
license: MIT license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -68,6 +76,7 @@ micromamba activate diffdock
- GPU strongly recommended (10-100x speedup vs CPU)
- First run pre-computes SO(2)/SO(3) lookup tables (~2-5 minutes)
- Model checkpoints (~500MB) download automatically if not present
+- Current upstream release is DiffDock v1.1.3; DiffDock-L is the default model line in `default_inference_args.yaml`
## Core Workflows
@@ -84,7 +93,7 @@ micromamba activate diffdock
python -m inference \
--config default_inference_args.yaml \
--protein_path protein.pdb \
- --ligand "CC(=O)Oc1ccccc1C(=O)O" \
+ --ligand_description "CC(=O)Oc1ccccc1C(=O)O" \
--out_dir results/single_docking/
```
@@ -93,20 +102,23 @@ python -m inference \
python -m inference \
--config default_inference_args.yaml \
--protein_sequence "MSKGEELFTGVVPILVELDGDVNGHKF..." \
- --ligand ligand.sdf \
+ --ligand_description ligand.sdf \
--out_dir results/sequence_docking/
```
**Output Structure:**
```
results/single_docking/
-├── rank_1.sdf # Top-ranked pose
-├── rank_2.sdf # Second-ranked pose
-├── ...
-├── rank_10.sdf # 10th pose (default: 10 samples)
-└── confidence_scores.txt
+└── complex_0/
+ ├── rank1.sdf # Convenience copy of top-ranked pose
+ ├── rank1_confidence0.87.sdf # Top-ranked pose with confidence in filename
+ ├── rank2_confidence0.42.sdf # Second-ranked pose
+ ├── ...
+ └── rank10_confidence-1.23.sdf # 10th pose (default: 10 samples)
```
+Current `inference.py` registers `--ligand_description` for single-complex runs. Some upstream README text still says `--ligand`; use `--ligand_description` unless your local checkout explicitly supports a `--ligand` alias.
+
### Workflow 2: Batch Processing Multiple Complexes
**Use Case:** Dock multiple ligands to proteins, virtual screening campaigns
@@ -291,7 +303,7 @@ DiffDock generates poses; combine with other tools for affinity:
**GNINA (Fast neural network scoring):**
```bash
-for pose in results/*.sdf; do
+for pose in results/single_docking/complex_0/*confidence*.sdf; do
gnina -r protein.pdb -l "$pose" --score_only
done
```
@@ -463,8 +475,8 @@ When using DiffDock, cite the appropriate papers:
**DiffDock-L (current default model):**
```
-Stärk et al. (2024) "DiffDock-L: Improving Molecular Docking with Diffusion Models"
-arXiv:2402.18396
+Corso et al. (2024) "Deep Confident Steps to New Pockets: Strategies for Docking Generalization"
+ICLR 2024, arXiv:2402.18396
```
**Original DiffDock:**
diff --git a/skills/diffdock/assets/custom_inference_config.yaml b/skills/diffdock/assets/custom_inference_config.yaml
index de5f0a9e..bb9d1f7c 100644
--- a/skills/diffdock/assets/custom_inference_config.yaml
+++ b/skills/diffdock/assets/custom_inference_config.yaml
@@ -19,6 +19,8 @@ no_final_step_noise: true
# Sampling parameters
samples_per_complex: 10 # Increase for difficult cases (e.g., 20-40)
sigma_schedule: expbeta
+inf_sched_alpha: 1
+inf_sched_beta: 1
initial_noise_std_proportion: 1.46
# Temperature controls - Adjust these to balance exploration vs accuracy
@@ -42,6 +44,8 @@ temp_sigma_data_tor: 0.69
# Feature flags
no_model: false
no_random: false
+no_random_pocket: false
+resample_rdkit: false
ode: false # Set to true to use ODE solver instead of SDE
different_schedules: false
limit_failures: 5
diff --git a/skills/diffdock/references/confidence_and_limitations.md b/skills/diffdock/references/confidence_and_limitations.md
index 5610c58d..1c46b243 100644
--- a/skills/diffdock/references/confidence_and_limitations.md
+++ b/skills/diffdock/references/confidence_and_limitations.md
@@ -174,8 +174,8 @@ For methodology details and benchmarking results, see:
- Corso et al., arXiv:2210.01776
2. **DiffDock-L Paper** (2024):
- - Enhanced model with improved generalization
- - Stärk et al., arXiv:2402.18396
+ - "Deep Confident Steps to New Pockets: Strategies for Docking Generalization"
+ - Corso et al., ICLR 2024, arXiv:2402.18396
3. **PoseBusters Benchmark**:
- Rigorous docking evaluation framework
diff --git a/skills/diffdock/references/parameters_reference.md b/skills/diffdock/references/parameters_reference.md
index 86f822c1..b127fb6d 100644
--- a/skills/diffdock/references/parameters_reference.md
+++ b/skills/diffdock/references/parameters_reference.md
@@ -36,9 +36,10 @@ This document provides comprehensive details on all DiffDock configuration param
- Automatically generates protein structure from sequence
- Alternative to `--protein_path`
-- **`--ligand`**: Ligand specification (SMILES string or file path)
- - SMILES string: `--ligand "COc(cc1)ccc1C#N"`
- - File path: `--ligand ligand.sdf` or `.mol2`
+- **`--ligand_description`**: Ligand specification (SMILES string or file path) for single-complex inference
+ - SMILES string: `--ligand_description "COc(cc1)ccc1C#N"`
+ - File path: `--ligand_description ligand.sdf` or `.mol2`
+ - Note: some upstream README text still mentions `--ligand`, but current `inference.py` registers `--ligand_description`
- **`--protein_ligand_csv`**: CSV file for batch processing
- Required columns: `complex_name`, `protein_path`, `ligand_description`, `protein_sequence`
@@ -64,6 +65,9 @@ This document provides comprehensive details on all DiffDock configuration param
- **`--no_final_step_noise`**: Omit noise at the final diffusion step
- Default: `true`
+- **`--resample_rdkit`**: Resample the RDKit ligand conformer before inference
+ - Default: `false`
+
### Sampling Settings
- **`--samples_per_complex`**: Number of samples to generate per complex
- Default: `10`
@@ -72,6 +76,9 @@ This document provides comprehensive details on all DiffDock configuration param
- **`--sigma_schedule`**: Noise schedule type
- Default: `expbeta` (exponential-beta)
+- **`--inf_sched_alpha` / `--inf_sched_beta`**: Inference schedule shape parameters
+ - Default: `1` / `1`
+
- **`--initial_noise_std_proportion`**: Initial noise standard deviation scaling
- Default: `1.46`
@@ -140,6 +147,9 @@ This document provides comprehensive details on all DiffDock configuration param
- Default: `false`
- Useful for reproducibility testing
+- **`--no_random_pocket`**: Disable random pocket randomization
+ - Default: `false`
+
### Alternative Sampling
- **`--ode`**: Use ODE solver instead of SDE
- Default: `false`
diff --git a/skills/diffdock/references/workflows_examples.md b/skills/diffdock/references/workflows_examples.md
index abedd68c..037f8083 100644
--- a/skills/diffdock/references/workflows_examples.md
+++ b/skills/diffdock/references/workflows_examples.md
@@ -40,27 +40,30 @@ The first execution pre-computes SO(2) and SO(3) lookup tables, taking a few min
python -m inference \
--config default_inference_args.yaml \
--protein_path examples/protein.pdb \
- --ligand "COc1ccc(C(=O)Nc2ccccc2)cc1" \
+ --ligand_description "COc1ccc(C(=O)Nc2ccccc2)cc1" \
--out_dir results/single_docking/
```
**Output Structure**:
```
results/single_docking/
-├── index_0_rank_1.sdf # Top-ranked prediction
-├── index_0_rank_2.sdf # Second-ranked prediction
-├── ...
-├── index_0_rank_10.sdf # 10th prediction (if samples_per_complex=10)
-└── confidence_scores.txt # Scores for all predictions
+└── complex_0/
+ ├── rank1.sdf # Convenience copy of top-ranked prediction
+ ├── rank1_confidence0.87.sdf # Top-ranked prediction with confidence
+ ├── rank2_confidence0.42.sdf # Second-ranked prediction
+ ├── ...
+ └── rank10_confidence-1.23.sdf # 10th prediction (if samples_per_complex=10)
```
+Current upstream `inference.py` uses `--ligand_description`; avoid the older `--ligand` spelling unless your local checkout has added an alias.
+
### Using Ligand Structure File
```bash
python -m inference \
--config default_inference_args.yaml \
--protein_path protein.pdb \
- --ligand ligand.sdf \
+ --ligand_description ligand.sdf \
--out_dir results/ligand_file/
```
@@ -74,7 +77,7 @@ python -m inference \
python -m inference \
--config default_inference_args.yaml \
--protein_sequence "MSKGEELFTGVVPILVELDGDVNGHKFSVSGEGEGDATYGKLTLKFICTTGKLPVPWPTLVTTFSYGVQCFSRYPDHMKQHDFFKSAMPEGYVQERTIFFKDDGNYKTRAEVKFEGDTLVNRIELKGIDFKEDGNILGHKLEYNYNSHNVYIMADKQKNGIKVNFKIRHNIEDGSVQLADHYQQNTPIGDGPVLLPDNHYLSTQSALSKDPNEKRDHMVLLEFVTAAGITHGMDELYK" \
- --ligand "CC(C)Cc1ccc(cc1)C(C)C(=O)O" \
+ --ligand_description "CC(C)Cc1ccc(cc1)C(C)C(=O)O" \
--out_dir results/sequence_docking/
```
@@ -118,11 +121,12 @@ python -m inference \
```
results/batch_predictions/
├── complex1/
-│ ├── rank_1.sdf
-│ ├── rank_2.sdf
+│ ├── rank1.sdf
+│ ├── rank1_confidence0.87.sdf
+│ ├── rank2_confidence0.42.sdf
│ └── ...
├── complex2/
-│ ├── rank_1.sdf
+│ ├── rank1.sdf
│ └── ...
└── complex3/
└── ...
@@ -172,19 +176,25 @@ python -m inference \
```python
# analyze_screening_results.py
-import os
import pandas as pd
+import re
+from pathlib import Path
results = []
-results_dir = "results/virtual_screening/"
+results_dir = Path("results/virtual_screening/")
+
+for complex_dir in results_dir.iterdir():
+ if not complex_dir.is_dir():
+ continue
+
+ scores = []
+ for sdf_file in complex_dir.glob("rank*_confidence*.sdf"):
+ match = re.search(r"confidence(-?\d+(?:\.\d+)?)", sdf_file.name)
+ if match:
+ scores.append(float(match.group(1)))
-for complex_dir in os.listdir(results_dir):
- confidence_file = os.path.join(results_dir, complex_dir, "confidence_scores.txt")
- if os.path.exists(confidence_file):
- with open(confidence_file) as f:
- scores = [float(line.strip()) for line in f]
- top_score = max(scores)
- results.append({"complex": complex_dir, "top_confidence": top_score})
+ if scores:
+ results.append({"complex": complex_dir.name, "top_confidence": max(scores)})
# Sort by confidence
df = pd.DataFrame(results)
@@ -244,12 +254,12 @@ python -m inference \
python -m inference \
--config default_inference_args.yaml \
--protein_path protein.pdb \
- --ligand "CC(=O)OC1=CC=CC=C1C(=O)O" \
+ --ligand_description "CC(=O)OC1=CC=CC=C1C(=O)O" \
--out_dir results/diffdock_poses/ \
--save_visualisation
# 2. Rescore with GNINA
-for pose in results/diffdock_poses/*.sdf; do
+for pose in results/diffdock_poses/complex_0/*confidence*.sdf; do
gnina -r protein.pdb -l "$pose" --score_only -o "${pose%.sdf}_gnina.sdf"
done
```
@@ -261,33 +271,32 @@ done
from openmm import app, LangevinIntegrator, Platform
from openmm.app import ForceField, Modeller, PDBFile
from rdkit import Chem
-import os
+from pathlib import Path
# Load protein
protein = PDBFile('protein.pdb')
forcefield = ForceField('amber14-all.xml', 'amber14/tip3pfb.xml')
# Process each DiffDock pose
-pose_dir = 'results/diffdock_poses/'
-for pose_file in os.listdir(pose_dir):
- if pose_file.endswith('.sdf'):
- # Load ligand
- mol = Chem.SDMolSupplier(os.path.join(pose_dir, pose_file))[0]
-
- # Combine protein + ligand
- modeller = Modeller(protein.topology, protein.positions)
- # ... add ligand to modeller ...
-
- # Create system and minimize
- system = forcefield.createSystem(modeller.topology)
- integrator = LangevinIntegrator(300, 1.0, 0.002)
- simulation = app.Simulation(modeller.topology, system, integrator)
- simulation.minimizeEnergy(maxIterations=1000)
-
- # Save minimized structure
- positions = simulation.context.getState(getPositions=True).getPositions()
- PDBFile.writeFile(simulation.topology, positions,
- open(f"minimized_{pose_file}.pdb", 'w'))
+pose_dir = Path('results/diffdock_poses/complex_0')
+for pose_path in pose_dir.glob('*confidence*.sdf'):
+ # Load ligand
+ mol = Chem.SDMolSupplier(str(pose_path))[0]
+
+ # Combine protein + ligand
+ modeller = Modeller(protein.topology, protein.positions)
+ # ... add ligand to modeller ...
+
+ # Create system and minimize
+ system = forcefield.createSystem(modeller.topology)
+ integrator = LangevinIntegrator(300, 1.0, 0.002)
+ simulation = app.Simulation(modeller.topology, system, integrator)
+ simulation.minimizeEnergy(maxIterations=1000)
+
+ # Save minimized structure
+ positions = simulation.context.getState(getPositions=True).getPositions()
+ PDBFile.writeFile(simulation.topology, positions,
+ open(f"minimized_{pose_path.stem}.pdb", 'w'))
```
## Workflow 7: Using the Graphical Interface
@@ -343,7 +352,7 @@ Use custom configuration:
python -m inference \
--config custom_inference.yaml \
--protein_path protein.pdb \
- --ligand "CC(=O)OC1=CC=CC=C1C(=O)O" \
+ --ligand_description "CC(=O)OC1=CC=CC=C1C(=O)O" \
--out_dir results/custom_config/
```
diff --git a/skills/diffdock/scripts/analyze_results.py b/skills/diffdock/scripts/analyze_results.py
index 4eec2dd9..b294cfec 100755
--- a/skills/diffdock/scripts/analyze_results.py
+++ b/skills/diffdock/scripts/analyze_results.py
@@ -52,28 +52,37 @@ def parse_confidence_scores(results_dir):
def parse_single_complex(complex_dir):
"""Parse results for a single complex."""
- predictions = []
+ predictions_by_rank = {}
# Look for SDF files with rank information
for sdf_file in complex_dir.glob("*.sdf"):
filename = sdf_file.name
- # Extract rank from filename (e.g., "rank_1.sdf" or "index_0_rank_1.sdf")
- rank_match = re.search(r'rank_(\d+)', filename)
+ # Current DiffDock writes rank1_confidence0.87.sdf; older runs may use rank_1.sdf.
+ rank_match = re.search(r'rank_?(\d+)', filename)
if rank_match:
rank = int(rank_match.group(1))
# Try to extract confidence score from filename or separate file
confidence = extract_confidence_score(sdf_file, complex_dir)
- predictions.append({
+ prediction = {
'rank': rank,
'file': sdf_file.name,
'path': str(sdf_file),
'confidence': confidence
- })
+ }
+
+ existing = predictions_by_rank.get(rank)
+ if (
+ existing is None
+ or (existing['confidence'] is None and confidence is not None)
+ or ('confidence' in filename and 'confidence' not in existing['file'])
+ ):
+ predictions_by_rank[rank] = prediction
# Sort by rank
+ predictions = list(predictions_by_rank.values())
predictions.sort(key=lambda x: x['rank'])
return {'predictions': predictions} if predictions else None
@@ -84,18 +93,23 @@ def extract_confidence_score(sdf_file, complex_dir):
Extract confidence score for a prediction.
Tries multiple methods:
- 1. Read from confidence_scores.txt file
- 2. Parse from SDF file properties
- 3. Extract from filename if present
+ 1. Extract from current filename format, e.g. rank1_confidence0.87.sdf
+ 2. Read from legacy confidence_scores.txt file
+ 3. Parse from SDF file properties
"""
- # Method 1: confidence_scores.txt
+ # Method 1: Filename
+ conf_match = re.search(r'(?:confidence|conf)_?(-?\d+(?:\.\d+)?)', sdf_file.name)
+ if conf_match:
+ return float(conf_match.group(1))
+
+ # Method 2: legacy confidence_scores.txt
confidence_file = complex_dir / "confidence_scores.txt"
if confidence_file.exists():
try:
with open(confidence_file) as f:
lines = f.readlines()
# Extract rank from filename
- rank_match = re.search(r'rank_(\d+)', sdf_file.name)
+ rank_match = re.search(r'rank_?(\d+)', sdf_file.name)
if rank_match:
rank = int(rank_match.group(1))
if rank <= len(lines):
@@ -103,7 +117,7 @@ def extract_confidence_score(sdf_file, complex_dir):
except Exception:
pass
- # Method 2: Parse from SDF file
+ # Method 3: Parse from SDF file
try:
with open(sdf_file) as f:
content = f.read()
@@ -114,11 +128,6 @@ def extract_confidence_score(sdf_file, complex_dir):
except Exception:
pass
- # Method 3: Filename (e.g., "rank_1_conf_0.95.sdf")
- conf_match = re.search(r'conf_(-?\d+\.?\d*)', sdf_file.name)
- if conf_match:
- return float(conf_match.group(1))
-
return None
diff --git a/skills/diffdock/scripts/setup_check.py b/skills/diffdock/scripts/setup_check.py
index 950c36a1..664a0645 100755
--- a/skills/diffdock/scripts/setup_check.py
+++ b/skills/diffdock/scripts/setup_check.py
@@ -22,12 +22,12 @@ def check_python_version():
version = sys.version_info
print("Checking Python version...")
- if version.major == 3 and version.minor >= 8:
+ if version.major == 3 and version.minor >= 9:
print(f" ✓ Python {version.major}.{version.minor}.{version.micro}")
return True
else:
print(f" ✗ Python {version.major}.{version.minor}.{version.micro} "
- f"(requires Python 3.8 or higher)")
+ f"(requires Python 3.9 or higher; upstream environment.yml uses Python 3.9.18)")
return False
@@ -38,7 +38,12 @@ def check_package(package_name, import_name=None, version_attr='__version__'):
try:
module = __import__(import_name)
- version = getattr(module, version_attr, 'unknown')
+ version = module
+ for attr in version_attr.split('.'):
+ version = getattr(version, attr, None)
+ if version is None:
+ version = 'unknown'
+ break
print(f" ✓ {package_name:20s} (version: {version})")
return True
except ImportError:
@@ -120,7 +125,7 @@ def check_esm():
return True
except ImportError:
print(f" ⚠ ESM not installed (needed for protein sequence folding)")
- print(f" Install with: pip install fair-esm")
+ print(f" Install with: uv pip install fair-esm")
return False
diff --git a/skills/esm/SKILL.md b/skills/esm/SKILL.md
index a070401a..42744b28 100644
--- a/skills/esm/SKILL.md
+++ b/skills/esm/SKILL.md
@@ -1,9 +1,9 @@
---
name: esm
-description: Comprehensive toolkit for EvolutionaryScale protein language models including ESM3 (generative multimodal design across sequence, structure, and function) and ESM C (efficient embeddings). Use for protein sequence/structure/function tasks, inverse folding, embeddings, variant design, and ESMFold2 structure prediction via Biohub. Supports local open weights (Python 3.12, esm on PyPI) and cloud Forge/Biohub APIs with ESM_API_KEY authentication.
+description: Use when working directly with the `esm` Python SDK, ESM3 or ESMC model IDs, Forge/Biohub inference clients, or ESMFold2 folding workflows.
license: MIT license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +11,7 @@ metadata:
## Overview
-ESM provides state-of-the-art protein language models for understanding, generating, and designing proteins. This skill enables working with two model families: ESM3 for generative protein design across sequence, structure, and function, and ESM C for efficient protein representation learning and embeddings.
+ESM provides protein language models for understanding, generating, and designing proteins. Use this skill for current EvolutionaryScale/Biohub workflows: ESM3 for generative design, ESMC for representation learning and embeddings, hosted Forge/Biohub inference, and ESMFold2 all-atom structure prediction.
## Core Capabilities
@@ -31,8 +31,8 @@ Generate novel protein sequences with desired properties using multimodal genera
from esm.models.esm3 import ESM3
from esm.sdk.api import ESM3InferenceClient, ESMProtein, GenerationConfig
-# Load model locally
-model: ESM3InferenceClient = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
+# Load local open weights after accepting the license on Hugging Face.
+model: ESM3InferenceClient = ESM3.from_pretrained("esm3-open").to("cuda")
# Create protein prompt
protein = ESMProtein(sequence="MPRT___KEND") # '_' represents masked positions
@@ -49,7 +49,7 @@ import os
import esm
from esm.sdk.api import ESMProtein, GenerationConfig
-# Same interface as local ESM3 — token from ESM_API_KEY (see Authentication)
+# Same interface as local ESM3; token from ESM_API_KEY (see Authentication)
model = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])
# Generate
@@ -107,17 +107,19 @@ Generate high-quality embeddings for downstream tasks like function prediction,
```python
from esm.models.esmc import ESMC
-from esm.sdk.api import ESMProtein
+from esm.sdk.api import ESMProtein, LogitsConfig
# Load ESM C model
-model = ESMC.from_pretrained("esmc-300m").to("cuda")
+model = ESMC.from_pretrained("esmc_300m").to("cuda")
# Get embeddings
protein = ESMProtein(sequence="MPRTKEINDAGLIVHSP...")
protein_tensor = model.encode(protein)
-
-# Generate embeddings
-embeddings = model.forward(protein_tensor)
+logits_output = model.logits(
+ protein_tensor,
+ LogitsConfig(sequence=True, return_embeddings=True),
+)
+embeddings = logits_output.embeddings
```
**Batch processing:**
@@ -130,7 +132,13 @@ proteins = [
ESMProtein(sequence="KTEFLNDGR...")
]
-embeddings_list = [model.logits(model.forward(model.encode(p))) for p in proteins]
+embeddings_list = [
+ model.logits(
+ model.encode(p),
+ LogitsConfig(sequence=True, return_embeddings=True),
+ ).embeddings
+ for p in proteins
+]
```
See `references/esm-c-api.md` for ESM C model details, efficiency comparisons, and advanced embedding strategies.
@@ -184,12 +192,13 @@ protein = model.generate(protein, config)
### 6. Batch Processing with Forge API
-Process multiple proteins efficiently using Forge's async executor.
+Process multiple proteins efficiently using Forge's async methods.
```python
import os
import asyncio
import esm
+from esm.sdk.api import ESMProtein, GenerationConfig
client = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])
@@ -211,25 +220,27 @@ See `references/forge-api.md` for detailed Forge API documentation, authenticati
## Model Selection Guide
**ESM3 Models (Generative):**
-- `esm3-sm-open-v1` (1.4B) - Open weights, local usage, good for experimentation
+- `esm3-open` (1.4B) - Open weights, local usage after accepting the Hugging Face license
- `esm3-medium-2024-08` (7B) - Best balance of quality and speed (Forge only)
- `esm3-large-2024-03` (98B) - Highest quality, slower (Forge only)
**ESM C Models (Embeddings):**
-- `esmc-300m` (30 layers) - Lightweight, fast inference (open weights, local)
-- `esmc-600m` (36 layers) - Balanced performance (open weights, local)
+- `esmc_300m` / `esmc-300m-2024-12` (30 layers) - Lightweight, fast inference (open weights, local)
+- `esmc_600m` / `esmc-600m-2024-12` (36 layers) - Balanced performance (open weights, local)
- `esmc-6b-2024-12` (80 layers) - Maximum quality (Forge API; local 6B weights require Forge or SageMaker)
+Local `ESMC.from_pretrained()` examples use underscore aliases (`esmc_300m`, `esmc_600m`). Hosted API clients use dated model IDs such as `esmc-600m-2024-12`.
+
**Selection criteria:**
-- **Local development/testing:** Use `esm3-sm-open-v1` or `esmc-300m`
+- **Local development/testing:** Use `esm3-open` or `esmc_300m`
- **Production quality:** Use `esm3-medium-2024-08` via Forge
- **Maximum accuracy:** Use `esm3-large-2024-03` or `esmc-6b-2024-12` via Forge
-- **High throughput:** Use Forge API with batch executor
+- **High throughput:** Use Forge or Biohub APIs with explicit async concurrency limits
- **Cost optimization:** Use smaller models, implement caching strategies
## Installation
-Install from PyPI ([`esm` on PyPI](https://pypi.org/project/esm/) by EvolutionaryScale). Requires **Python 3.12** (`>=3.12,<3.13` for current releases).
+Install from PyPI ([`esm` on PyPI](https://pypi.org/project/esm/) by EvolutionaryScale). Current PyPI release: **3.2.3** (Oct 14, 2025). Requires **Python >=3.12,<3.13**.
**Basic installation:**
@@ -244,7 +255,7 @@ uv pip install "esm==3.2.3"
uv pip install flash-attn --no-build-isolation
```
-The Forge client ships with the `esm` package — no extra install for cloud inference.
+The Forge client ships with the `esm` package - no extra install for ESM3 or ESMC Forge inference.
## Authentication
@@ -252,7 +263,7 @@ Forge API access requires an API key. Never hardcode tokens in scripts or commit
1. Check whether `ESM_API_KEY` is already set in the environment.
2. If not, check a local `.env` for `ESM_API_KEY` only (do not load unrelated secrets).
-3. If still missing, create a key at [Forge](https://forge.evolutionaryscale.ai) (or [Biohub developer console](https://biohub.ai/developer-console/api-keys) for newer ESMFold2 endpoints).
+3. If still missing, create a key in the [Biohub developer console](https://biohub.ai/developer-console/api-keys) for Biohub APIs or [Forge](https://forge.evolutionaryscale.ai) for legacy Forge-hosted ESM3/ESMC access.
```python
import os
@@ -260,9 +271,9 @@ import os
token = os.environ["ESM_API_KEY"] # raises KeyError if unset
```
-`esm.sdk.client()` reads `ESM_API_KEY` automatically when `token` is omitted.
+`esm.sdk.client()` reads `ESM_API_KEY` automatically when `token` is omitted. Keep endpoint URLs fixed to trusted hosts such as `https://forge.evolutionaryscale.ai` or `https://biohub.ai`; do not take API hosts from untrusted user input.
-**Biohub platform:** EvolutionaryScale is migrating some services (including ESMFold2 structure prediction) to [biohub.ai](https://biohub.ai). SDK class names may still reference "Forge". See `references/biohub-platform.md` for ESMFold2 and Biohub-specific setup.
+**Biohub platform:** EvolutionaryScale and Forge now surface current hosted models through [biohub.ai](https://biohub.ai). SDK class names may still reference "Forge". See `references/biohub-platform.md` for ESMFold2 and Biohub-specific setup.
## Common Workflows
@@ -288,7 +299,7 @@ These references contain detailed API specifications, parameter descriptions, an
## Best Practices
**For generation tasks:**
-- Start with smaller models for prototyping (`esm3-sm-open-v1`)
+- Start with smaller models for prototyping (`esm3-open`)
- Use temperature parameter to control diversity (0.0 = deterministic, 1.0 = diverse)
- Implement iterative refinement with chain-of-thought for complex designs
- Validate generated sequences with structure prediction or wet-lab experiments
@@ -307,7 +318,7 @@ These references contain detailed API specifications, parameter descriptions, an
## Resources and Documentation
-- **GitHub Repository:** https://github.com/evolutionaryscale/esm (releases through v3.2.x; see also [Biohub/esm](https://github.com/Biohub/esm) for ESMFold2)
+- **GitHub Repository:** https://github.com/Biohub/esm (current ESMC/ESMFold2/Biohub docs; ESM3 docs remain linked from the repository)
- **Forge Platform:** https://forge.evolutionaryscale.ai
- **Biohub Platform:** https://biohub.ai
- **Scientific Paper:** Hayes et al., Science (2025) - https://www.science.org/doi/10.1126/science.ads0018
@@ -315,9 +326,9 @@ These references contain detailed API specifications, parameter descriptions, an
- ESM3 Release: https://www.evolutionaryscale.ai/blog/esm3-release
- ESM C Launch: https://www.evolutionaryscale.ai/blog/esm-cambrian
- **Community:** Slack community at https://bit.ly/3FKwcWd
-- **Model Weights:** HuggingFace EvolutionaryScale organization
+- **Model Weights:** Hugging Face EvolutionaryScale and Biohub organizations
## Responsible Use
-ESM is designed for beneficial applications in protein engineering, drug discovery, and scientific research. Follow the Responsible Biodesign Framework (https://responsiblebiodesign.ai/) when designing novel proteins. Consider biosafety and ethical implications of protein designs before experimental validation.
+ESM is designed for beneficial applications in protein engineering, drug discovery, and scientific research. Follow the Responsible Biodesign Framework (https://responsiblebiodesign.ai/) and Biohub Acceptable Use Policy (https://biohub.org/acceptable-use-policy/) when designing novel proteins. Consider biosafety and ethical implications of protein designs before experimental validation.
diff --git a/skills/esm/references/biohub-platform.md b/skills/esm/references/biohub-platform.md
index 986b524c..17247b36 100644
--- a/skills/esm/references/biohub-platform.md
+++ b/skills/esm/references/biohub-platform.md
@@ -2,7 +2,7 @@
## Overview
-EvolutionaryScale is migrating hosted inference from [Forge](https://forge.evolutionaryscale.ai) to the [Biohub platform](https://biohub.ai). The Python SDK still uses `esm.sdk.forge` client classes and "Forge" naming in many places, but newer structure-prediction APIs (ESMFold2) run on Biohub endpoints.
+EvolutionaryScale and Forge now surface current hosted ESM workflows through the [Biohub platform](https://biohub.ai). The Python SDK still uses `esm.sdk.forge` client classes and "Forge" naming in some places, but current Biohub APIs use `https://biohub.ai` endpoints.
Use this reference when you need **all-atom structure prediction** (ESMFold2) or when upstream docs point to `biohub.ai` instead of `forge.evolutionaryscale.ai`.
@@ -20,17 +20,19 @@ Never commit API keys or paste them into notebooks checked into git.
## Installation
-For ESMFold2 and latest Biohub SDK features, upstream may recommend installing from the Biohub GitHub repo (pin a specific commit for reproducibility):
+For ESM3/ESMC workflows on PyPI, `uv pip install "esm==3.2.3"` remains the standard reproducible path.
+
+For ESMFold2 and the newest Biohub SDK features, upstream may recommend installing from the Biohub GitHub repo. Avoid floating branch installs in automated or production instructions. Pin a trusted release or a full 40-character commit SHA from the official Biohub repository, and review the verified GitHub release/commit before installing:
```bash
-uv pip install "esm@git+https://github.com/Biohub/esm.git@c94ed8d"
+uv pip install "esm@git+https://github.com/Biohub/esm.git@<full-40-character-commit-sha>"
```
-For ESM3/ESM C workflows on PyPI, `uv pip install "esm==3.2.3"` remains the standard path. Confirm which install source your task requires before mixing both in one environment.
+Confirm which install source your task requires before mixing PyPI and GitHub builds in one environment.
## ESMFold2 Structure Prediction
-ESMFold2 is a structure prediction model built on ESMC 6B, available through `SequenceStructureForgeInferenceClient` with Biohub as the API host.
+ESMFold2 is a structure prediction model built on ESMC 6B, available through `SequenceStructureForgeInferenceClient` with Biohub as the API host. Biohub lists ESMFold2 as a 2026-04/2026-05 model family and documents `esmfold2-fast-2026-05` for hosted inference.
```python
import os
@@ -57,6 +59,30 @@ with open("result.cif", "w") as f:
f.write(result.complex.to_mmcif())
```
+## Hosted ESMC Embeddings
+
+Biohub also documents hosted ESMC inference with `esmc_client()` and dated ESMC model IDs:
+
+```python
+import os
+from esm.sdk import esmc_client
+from esm.sdk.api import ESMProtein, LogitsConfig
+
+model = esmc_client(
+ model="esmc-600m-2024-12",
+ url="https://biohub.ai",
+ token=os.environ["ESM_API_KEY"],
+)
+
+protein = ESMProtein(sequence="MPRTKEINDAGLIVHSPQWFYK")
+protein_tensor = model.encode(protein)
+logits_output = model.logits(
+ protein_tensor,
+ LogitsConfig(sequence=True, return_embeddings=True),
+)
+embeddings = logits_output.embeddings
+```
+
### Model IDs
| Model ID | Use case |
@@ -64,12 +90,15 @@ with open("result.cif", "w") as f:
| `esmfold2-fast-2026-05` | Fast single-sequence folding |
| Check Biohub docs for additional variants | MSA-augmented or higher-accuracy modes |
+ESMFold2 predicts static all-atom structures. Treat outputs as hypotheses that require experimental validation, especially for therapeutic, clinical, or safety-sensitive uses.
+
## Relationship to Forge (ESM3 / ESM C)
| Capability | Typical endpoint | Client |
|------------|------------------|--------|
| ESM3 generation | `https://forge.evolutionaryscale.ai` | `esm.sdk.client()` or `ESM3ForgeInferenceClient` |
| ESM C 6B embeddings (hosted) | Forge | `ESM3ForgeInferenceClient` with `esmc-6b-2024-12` |
+| ESMC hosted embeddings | `https://biohub.ai` | `esmc_client()` with dated ESMC model IDs |
| ESMFold2 structure prediction | `https://biohub.ai` | `SequenceStructureForgeInferenceClient` |
For ESM3 and ESM C cloud usage patterns, see `forge-api.md`. For local open-weight models, see `esm3-api.md` and `esm-c-api.md`.
diff --git a/skills/esm/references/esm-c-api.md b/skills/esm/references/esm-c-api.md
index d717f029..c025cafa 100644
--- a/skills/esm/references/esm-c-api.md
+++ b/skills/esm/references/esm-c-api.md
@@ -10,8 +10,8 @@ ESM C (Cambrian) is a family of protein language models optimized for representa
| Model ID | Parameters | Layers | Best For |
|----------|-----------|--------|----------|
-| `esmc-300m` | 300M | 30 | Fast inference, lightweight applications |
-| `esmc-600m` | 600M | 36 | Balanced performance and quality |
+| `esmc_300m` / `esmc-300m-2024-12` | 300M | 30 | Fast inference, lightweight applications |
+| `esmc_600m` / `esmc-600m-2024-12` | 600M | 36 | Balanced performance and quality |
| `esmc-6b-2024-12` | 6B | 80 | Maximum quality (Forge API; not open weights) |
**Key Features:**
@@ -37,23 +37,23 @@ Main interface for ESM C models.
```python
from esm.models.esmc import ESMC
-from esm.sdk.api import ESMProtein
+from esm.sdk.api import ESMProtein, LogitsConfig
# Load model with automatic device placement
-model = ESMC.from_pretrained("esmc-300m").to("cuda")
+model = ESMC.from_pretrained("esmc_300m").to("cuda")
# Or specify device explicitly
-model = ESMC.from_pretrained("esmc-600m").to("cpu")
+model = ESMC.from_pretrained("esmc_600m").to("cpu")
-# For maximum quality (local open weights: esmc-300m or esmc-600m)
+# For maximum local quality (open weights: esmc_300m or esmc_600m)
# For 6B hosted inference, use Forge with esmc-6b-2024-12 (see forge-api.md)
-model = ESMC.from_pretrained("esmc-600m").to("cuda")
+model = ESMC.from_pretrained("esmc_600m").to("cuda")
```
**Model Selection Criteria:**
-- **esmc-300m**: Development, real-time applications, batch processing of many sequences
-- **esmc-600m**: Production deployments, good quality/speed balance
+- **esmc_300m**: Development, real-time applications, batch processing of many sequences
+- **esmc_600m**: Production deployments, good quality/speed balance
- **esmc-6b-2024-12** (Forge): Research, maximum accuracy when 6B open weights are unavailable locally
### Basic Embedding Generation
@@ -62,10 +62,10 @@ model = ESMC.from_pretrained("esmc-600m").to("cuda")
```python
from esm.models.esmc import ESMC
-from esm.sdk.api import ESMProtein
+from esm.sdk.api import ESMProtein, LogitsConfig
# Load model
-model = ESMC.from_pretrained("esmc-600m").to("cuda")
+model = ESMC.from_pretrained("esmc_600m").to("cuda")
# Create protein
protein = ESMProtein(sequence="MPRTKEINDAGLIVHSPQWFYK")
@@ -73,11 +73,13 @@ protein = ESMProtein(sequence="MPRTKEINDAGLIVHSPQWFYK")
# Encode to tensor
protein_tensor = model.encode(protein)
-# Generate embeddings
-embeddings = model.forward(protein_tensor)
-
-# Get logits (per-position predictions)
-logits = model.logits(embeddings)
+# Generate logits and embeddings
+logits_output = model.logits(
+ protein_tensor,
+ LogitsConfig(sequence=True, return_embeddings=True),
+)
+embeddings = logits_output.embeddings
+logits = logits_output.logits
print(f"Embedding shape: {embeddings.shape}")
print(f"Logits shape: {logits.shape}")
@@ -87,8 +89,8 @@ print(f"Logits shape: {logits.shape}")
For a sequence of length L:
- `embeddings.shape`: `(1, L, hidden_dim)` where hidden_dim depends on model
- - esmc-300m: hidden_dim = 960
- - esmc-600m: hidden_dim = 1152
+ - esmc_300m: hidden_dim = 960
+ - esmc_600m: hidden_dim = 1152
- esmc-6b: hidden_dim = 2560
- `logits.shape`: `(1, L, 64)` - per-position amino acid predictions
@@ -335,12 +337,12 @@ class ProteinPropertyPredictor(nn.Module):
return x
# Use ESM C as frozen feature extractor
-esm_model = ESMC.from_pretrained("esmc-600m").to("cuda")
+esm_model = ESMC.from_pretrained("esmc_600m").to("cuda")
esm_model.train(False) # Inference mode (disables dropout; not Python eval)
# Create task-specific model
predictor = ProteinPropertyPredictor(
- embedding_dim=1152, # esmc-600m dimension
+ embedding_dim=1152, # esmc_600m dimension
hidden_dim=512,
output_dim=1 # e.g., stability score
).to("cuda")
@@ -394,7 +396,7 @@ print(f"Residue similarity: {similarity.item():.4f}")
import torch
# Use half precision for memory efficiency
-model = ESMC.from_pretrained("esmc-600m").to("cuda").half()
+model = ESMC.from_pretrained("esmc_600m").to("cuda").half()
# Process with mixed precision
with torch.cuda.amp.autocast():
@@ -495,7 +497,7 @@ cache.save()
**Migration from ESM2:**
-ESM C is designed as a drop-in replacement:
+ESM C is designed as a modern replacement for many ESM2 embedding workflows:
```python
# Old ESM2 code
@@ -504,7 +506,7 @@ model, alphabet = pretrained.esm2_t33_650M_UR50D()
# New ESM C code (similar API)
from esm.models.esmc import ESMC
-model = ESMC.from_pretrained("esmc-600m")
+model = ESMC.from_pretrained("esmc_600m")
```
Key differences:
@@ -546,7 +548,7 @@ ESM C can be fine-tuned for specific tasks:
import torch.optim as optim
# Load model
-model = ESMC.from_pretrained("esmc-300m").to("cuda")
+model = ESMC.from_pretrained("esmc_300m").to("cuda")
# Unfreeze for fine-tuning
for param in model.parameters():
diff --git a/skills/esm/references/esm3-api.md b/skills/esm/references/esm3-api.md
index 16aff41c..355d5bae 100644
--- a/skills/esm/references/esm3-api.md
+++ b/skills/esm/references/esm3-api.md
@@ -10,7 +10,7 @@ ESM3 is a frontier multimodal generative language model that reasons over the se
| Model ID | Parameters | Availability | Best For |
|----------|-----------|--------------|----------|
-| `esm3-sm-open-v1` | 1.4B | Open weights (local) | Development, testing, learning |
+| `esm3-open` | 1.4B | Open weights (local, Hugging Face license acceptance required) | Development, testing, learning |
| `esm3-medium-2024-08` | 7B | Forge API only | Production, balanced quality/speed |
| `esm3-large-2024-03` | 98B | Forge API only | Maximum quality, research |
| `esm3-medium-multimer-2024-09` | 7B | Forge API only | Protein complexes (experimental) |
@@ -129,10 +129,10 @@ The unified interface for both local and remote inference.
from esm.models.esm3 import ESM3
# Load with automatic device placement
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
+model = ESM3.from_pretrained("esm3-open").to("cuda")
# Or explicitly specify device
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cpu")
+model = ESM3.from_pretrained("esm3-open").to("cpu")
```
**Forge API (same interface as local):**
@@ -141,7 +141,7 @@ model = ESM3.from_pretrained("esm3-sm-open-v1").to("cpu")
import os
import esm
-# Drop-in replacement for ESM3.from_pretrained() — reads ESM_API_KEY by default
+# Drop-in replacement for ESM3.from_pretrained(); reads ESM_API_KEY by default
model = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])
```
@@ -390,7 +390,7 @@ import torch
torch.cuda.empty_cache()
# Use half precision for memory efficiency
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda").half()
+model = ESM3.from_pretrained("esm3-open").to("cuda").half()
# Process in chunks for very long sequences
def chunk_generate(model, long_sequence, chunk_size=500):
@@ -434,7 +434,7 @@ except torch.cuda.OutOfMemoryError:
## Model-Specific Considerations
-**esm3-sm-open-v1:**
+**esm3-open:**
- Suitable for development and testing
- Lower quality than larger models
- Fast inference on consumer GPUs
diff --git a/skills/esm/references/forge-api.md b/skills/esm/references/forge-api.md
index 9fa7973e..e3756503 100644
--- a/skills/esm/references/forge-api.md
+++ b/skills/esm/references/forge-api.md
@@ -1,8 +1,8 @@
-# Forge API Reference
+# Forge and Hosted API Reference
## Overview
-Forge is EvolutionaryScale's cloud platform for scalable protein design and inference. It provides API access to the full ESM3 model family, including large models not available for local execution.
+Forge is EvolutionaryScale's hosted platform for scalable ESM3 and ESMC inference. Biohub is the current platform surface for newer hosted workflows such as ESMFold2; SDK classes may still use `forge` names even when the endpoint is `https://biohub.ai`.
**Key Benefits:**
- Access to all ESM3 models including 98B parameter version
@@ -16,7 +16,7 @@ Forge is EvolutionaryScale's cloud platform for scalable protein design and infe
### 1. Obtain API Token
-Sign up and get your API token at: https://forge.evolutionaryscale.ai
+Create a token in the [Biohub developer console](https://biohub.ai/developer-console/api-keys) for Biohub APIs. For legacy Forge-hosted ESM3/ESMC access, use https://forge.evolutionaryscale.ai.
### 2. Install ESM SDK
@@ -28,13 +28,14 @@ Requires Python 3.12. The Forge client is included in the standard PyPI package.
### 3. Set API Key
-Export your Forge API key (never hardcode in source files):
+Export your API key (never hardcode in source files):
```bash
-export ESM_API_KEY="your-key-from-forge-console"
+export ESM_API_KEY="your-key-from-console"
```
`esm.sdk.client()` reads `ESM_API_KEY` by default when `token` is omitted.
+Keep API hosts fixed to trusted endpoints such as `https://forge.evolutionaryscale.ai` and `https://biohub.ai`; do not accept an arbitrary endpoint URL from untrusted input.
### 4. Basic Connection
@@ -156,31 +157,27 @@ results = asyncio.run(generate_many(client, proteins))
print(f"Generated {len(results)} proteins")
```
-### Batch Processing with BatchExecutor
+### Batch Processing with Async Concurrency
-For large-scale processing with automatic concurrency management:
+For large-scale processing, combine the SDK's async methods with an explicit concurrency limit:
```python
-from esm.sdk.forge import BatchExecutor
+import asyncio
from esm.sdk.api import ESMProtein, GenerationConfig
-# Create batch executor
-executor = BatchExecutor(
- client=client,
- max_concurrent=10 # Process 10 requests concurrently
-)
+async def generate_many_limited(client, proteins, config, max_concurrent=10):
+ semaphore = asyncio.Semaphore(max_concurrent)
+
+ async def run_one(protein):
+ async with semaphore:
+ return await client.async_generate(protein, config)
+
+ return await asyncio.gather(*(run_one(protein) for protein in proteins))
# Prepare batch of proteins
proteins = [ESMProtein(sequence=f"MPRT{'_' * 50}KEND") for _ in range(100)]
config = GenerationConfig(track="sequence", num_steps=25)
-
-# Submit batch
-batch_results = executor.submit_batch(
- proteins=proteins,
- config=config,
- progress_callback=lambda i, total: print(f"Processed {i}/{total}")
-)
-
+batch_results = asyncio.run(generate_many_limited(client, proteins, config))
print(f"Completed {len(batch_results)} generations")
```
@@ -188,15 +185,12 @@ print(f"Completed {len(batch_results)} generations")
### Understanding Limits
-Forge implements rate limiting based on:
+Hosted APIs may rate limit based on:
- Requests per minute (RPM)
- Tokens per minute (TPM)
- Concurrent requests
-**Typical Limits (subject to change):**
-- Free tier: 60 RPM, 5 concurrent
-- Pro tier: 300 RPM, 20 concurrent
-- Enterprise: Custom limits
+Check the Forge or Biohub console for your current credits, model access, and rate limits; do not bake assumed limits into production code.
### Handling Rate Limits
@@ -268,25 +262,25 @@ Process results as they complete:
```python
import asyncio
-from concurrent.futures import ThreadPoolExecutor
async def stream_generate(client, proteins, config):
"""Stream results as they complete."""
- pending = {
+ task_to_index = {
asyncio.create_task(client.async_generate(p, config)): i
for i, p in enumerate(proteins)
}
+ pending_tasks = set(task_to_index)
results = [None] * len(proteins)
- while pending:
- done, pending = await asyncio.wait(
- pending.keys(),
+ while pending_tasks:
+ done, pending_tasks = await asyncio.wait(
+ pending_tasks,
return_when=asyncio.FIRST_COMPLETED
)
for task in done:
- idx = pending.pop(task)
+ idx = task_to_index[task]
result = await task
results[idx] = result
yield idx, result
@@ -624,7 +618,7 @@ For dedicated infrastructure and enterprise use:
## Best Practices Summary
-1. **Authentication**: Use `ESM_API_KEY` environment variable or a secrets manager — never hardcode tokens
+1. **Authentication**: Use `ESM_API_KEY` environment variable or a secrets manager; never hardcode tokens
2. **Rate Limiting**: Implement exponential backoff and respect limits
3. **Error Handling**: Always handle network errors and retries
4. **Caching**: Cache results for repeated queries
diff --git a/skills/esm/references/workflows.md b/skills/esm/references/workflows.md
index 8c3716ef..120460ea 100644
--- a/skills/esm/references/workflows.md
+++ b/skills/esm/references/workflows.md
@@ -20,7 +20,7 @@ from esm.sdk.api import ESMProtein, GenerationConfig, FunctionAnnotation
import matplotlib.pyplot as plt
# Setup
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
+model = ESM3.from_pretrained("esm3-open").to("cuda")
# Step 1: Define target properties
print("Step 1: Defining target GFP properties...")
@@ -147,7 +147,7 @@ import numpy as np
from sklearn.cluster import KMeans
# Setup
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
+model = ESM3.from_pretrained("esm3-open").to("cuda")
# Parent protein
parent_sequence = "MPRTKEINDAGLIVHSPQWFYKARNDTESLGKIVHEFPM"
@@ -227,7 +227,7 @@ print("\nGenerating embeddings for clustering...")
from esm.models.esmc import ESMC
-embedding_model = ESMC.from_pretrained("esmc-300m").to("cuda")
+embedding_model = ESMC.from_pretrained("esmc_300m").to("cuda")
def get_embedding(sequence):
"""Get mean-pooled embedding for sequence."""
@@ -304,7 +304,7 @@ from esm.sdk.api import ESMProtein, GenerationConfig
import numpy as np
# Setup
-model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
+model = ESM3.from_pretrained("esm3-open").to("cuda")
# Load target structure (e.g., from PDB)
target_protein = ESMProtein.from_pdb("target_structure.pdb")
@@ -466,8 +466,8 @@ from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
# Setup models
-esm3_model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")
-esmc_model = ESMC.from_pretrained("esmc-600m").to("cuda")
+esm3_model = ESM3.from_pretrained("esm3-open").to("cuda")
+esmc_model = ESMC.from_pretrained("esmc_600m").to("cuda")
# Example: Predict if protein is an enzyme
# (In practice, you'd have a labeled training set)
@@ -544,7 +544,7 @@ from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
# Setup
-model = ESMC.from_pretrained("esmc-600m").to("cuda")
+model = ESMC.from_pretrained("esmc_600m").to("cuda")
# Load protein dataset (example)
sequences = [
diff --git a/skills/gget/SKILL.md b/skills/gget/SKILL.md
index 33772fa4..ef2d1256 100644
--- a/skills/gget/SKILL.md
+++ b/skills/gget/SKILL.md
@@ -1,9 +1,15 @@
---
name: gget
-description: "Fast CLI/Python queries to 20+ bioinformatics databases. Use for quick lookups: gene info, BLAST searches, AlphaFold structures, enrichment analysis. Best for interactive exploration, simple queries. For batch processing or advanced BLAST use biopython; for multi-database Python workflows use bioservices."
+description: "Fast CLI/Python queries to 20+ bioinformatics databases. Use for quick lookups: gene info, BLAST/BLAT, viral sequence downloads, AlphaFold structures, enrichment analysis, OpenTargets, COSMIC, CELLxGENE, and 8cube mouse specificity/expression data. Best for interactive exploration and simple queries. For batch processing or advanced BLAST use biopython; for multi-database Python workflows use bioservices."
license: BSD-2-Clause license
+allowed-tools:
+ - Read
+ - Write
+ - Edit
+ - Bash
+compatibility: Requires Python >=3.8 and gget 0.30.5-compatible APIs. Optional setup modules may install scientific dependencies that lag the newest Python releases; use Python 3.9 or 3.10 if `gget setup cellxgene` or `gget setup alphafold` fails.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,20 +17,19 @@ metadata:
## Overview
-gget is a command-line bioinformatics tool and Python package providing unified access to 20+ genomic databases and analysis methods. Query gene information, sequence analysis, protein structures, expression data, and disease associations through a consistent interface. All gget modules work both as command-line tools and as Python functions.
+gget is a command-line bioinformatics tool and Python package providing unified access to 20+ genomic databases and analysis methods. Query gene information, sequence analysis, protein structures, viral sequences, expression data, disease associations, and mouse tissue/cell specificity metrics through a consistent interface. Most gget modules work both as command-line tools and as Python functions.
-**Important**: The databases queried by gget are continuously updated, which sometimes changes their structure. gget modules are tested automatically on a biweekly basis and updated to match new database structures when necessary.
+**Important**: The databases queried by gget are continuously updated, which sometimes changes their structure. Guidance here targets gget 0.30.5 (PyPI current as of 2026-06-07). For reproducible work, pin `gget==0.30.5`; for broken upstream database adapters, update gget after checking release notes.
## Installation
Install gget in a clean virtual environment to avoid conflicts:
```bash
-# Using uv (recommended)
-uv uv pip install gget
-
-# Or using pip
-uv pip install --upgrade gget
+# Reproducible install targeting this skill
+uv venv .venv
+source .venv/bin/activate
+uv pip install "gget==0.30.5"
# In Python/Jupyter
import gget
@@ -51,6 +56,8 @@ Common flags across modules:
- `-q/--quiet`: Suppress progress information
- `-csv`: Return CSV format (command-line only)
+Python argument names generally match long CLI options without leading dashes. For example, `--census_version` becomes `census_version=...`. Use `gget <module> --help` for the exact current signature.
+
## Module Categories
### 1. Reference & Gene Information
@@ -61,8 +68,9 @@ Retrieve download links and metadata for Ensembl reference genomes.
**Parameters**:
- `species`: Genus_species format (e.g., 'homo_sapiens', 'mus_musculus'). Shortcuts: 'human', 'mouse'
-- `-w/--which`: Specify return types (gtf, cdna, dna, cds, cdrna, pep). Default: all
+- `-w/--which`: Specify return types as comma-separated CLI values or Python list (gtf, cdna, dna, cds, cdrna, pep). Default: all
- `-r/--release`: Ensembl release number (default: latest)
+- `-od/--out_dir`: Directory for downloaded files
- `-l/--list_species`: List available vertebrate species
- `-liv/--list_iv_species`: List available invertebrate species
- `-ftp`: Return only FTP links
@@ -76,19 +84,19 @@ gget ref --list_species
# Get all reference files for human
gget ref homo_sapiens
-# Download only GTF annotation for mouse
-gget ref -w gtf -d mouse
+# Download GTF and cDNA files for mouse
+gget ref -w gtf,cdna -d mouse
```
```python
# Python
gget.ref("homo_sapiens")
-gget.ref("mus_musculus", which="gtf", download=True)
+gget.ref("mus_musculus", which=["gtf", "cdna"], download=True)
```
#### gget search - Gene Search
-Locate genes by name or description across species.
+Locate genes by name, description, and Ensembl synonyms across species.
**Parameters**:
- `searchwords`: One or more search terms (case-insensitive)
@@ -97,6 +105,7 @@ Locate genes by name or description across species.
- `-t/--id_type`: Return 'gene' (default) or 'transcript'
- `-ao/--andor`: 'or' (default) finds ANY searchword; 'and' requires ALL
- `-l/--limit`: Maximum results to return
+- `wrap_text`: Python-only display helper for wide DataFrames
**Returns**: ensembl_id, gene_name, ensembl_description, ext_ref_description, biotype, URL
@@ -247,30 +256,31 @@ gget.muscle("sequences.fasta", save=True)
#### gget diamond - Local Sequence Alignment
-Perform fast local protein or translated DNA alignment using DIAMOND.
+Perform fast local protein alignment or translated nucleotide-to-protein alignment using DIAMOND.
**Parameters**:
- Query: Sequences (string/list) or FASTA file path
-- `--reference`: Reference sequences (string/list) or FASTA file path (required)
-- `--sensitivity`: fast, mid-sensitive, sensitive, more-sensitive, very-sensitive (default), ultra-sensitive
-- `--threads`: CPU threads (default: 1)
-- `--diamond_db`: Save database for reuse
-- `--translated`: Enable nucleotide-to-amino acid alignment
+- `-ref/--reference`: Reference sequences (string/list) or FASTA file path (required)
+- `-s/--sensitivity`: fast, mid-sensitive, sensitive, more-sensitive, very-sensitive (default), ultra-sensitive
+- `-t/--threads`: CPU threads (default: 1)
+- `-db/--diamond_db`: Save database for reuse
+- `-x/--translated`: Enable nucleotide query to amino acid reference alignment
**Returns**: Identity percentage, sequence lengths, match positions, gap openings, E-values, bit scores
**Examples**:
```bash
# Align against reference
-gget diamond GGETISAWESQME -ref reference.fasta --threads 4
+gget diamond GGETISAWESQME -ref reference.fasta -t 4
-# Save database for reuse
-gget diamond query.fasta -ref ref.fasta --diamond_db my_db.dmnd
+# Translate nucleotide query against amino acid reference
+gget diamond query_nt.fasta -ref proteins.fasta --translated
```
```python
# Python
gget.diamond("GGETISAWESQME", reference="reference.fasta", threads=4)
+gget.diamond("ATGGGC...", reference="proteins.fasta", translated=True)
```
### 3. Structural & Protein Analysis
@@ -306,10 +316,7 @@ Predict 3D protein structures using simplified AlphaFold2.
**Setup Required**:
```bash
-# Install OpenMM first
-uv pip install openmm
-
-# Then setup AlphaFold
+# Installs modified third-party dependencies and downloads model parameters
gget setup alphafold
```
@@ -509,11 +516,12 @@ Retrieve disease and drug associations from OpenTargets.
- Ensembl gene ID (required)
- `-r/--resource`: diseases (default), drugs, tractability, pharmacogenetics, expression, depmap, interactions
- `-l/--limit`: Cap results count
-- Filter arguments (vary by resource):
- - drugs: `--filter_disease`
- - pharmacogenetics: `--filter_drug`
- - expression/depmap: `--filter_tissue`, `--filter_anat_sys`, `--filter_organ`
- - interactions: `--filter_protein_a`, `--filter_protein_b`, `--filter_gene_b`
+- `--filters`: Exact-match filters using returned OpenTargets column names; repeat on the CLI or pass a Python dict
+- `-or/--or`: CLI-only; combine filters with OR logic instead of the default AND logic
+
+**Current notes**:
+- gget 0.30.5 rewrote this module for the newer OpenTargets API; some output column names differ from older releases.
+- The older `--filter_mode` argument was removed upstream.
**Examples**:
```bash
@@ -523,13 +531,18 @@ gget opentargets ENSG00000169194 -r diseases -l 5
# Get associated drugs
gget opentargets ENSG00000169194 -r drugs -l 10
-# Get tissue expression
-gget opentargets ENSG00000169194 -r expression --filter_tissue brain
+# Filter interactions by returned column names
+gget opentargets ENSG00000169194 -r interactions --filters protein_a_id=P35225 --filters gene_b_id=ENSG00000077238
```
```python
# Python
gget.opentargets("ENSG00000169194", resource="diseases", limit=5)
+gget.opentargets(
+ "ENSG00000169194",
+ resource="interactions",
+ filters={"protein_a_id": "P35225", "gene_b_id": "ENSG00000077238"},
+)
```
#### gget cbio - cBioPortal Cancer Genomics
@@ -577,6 +590,7 @@ gget.cbio_plot(["msk_impact_2017"], ["AKT1", "ALK"], stratification="tissue")
Search COSMIC (Catalogue Of Somatic Mutations In Cancer) database.
**Important**: License fees apply for commercial use. Requires COSMIC account credentials.
+Avoid passing COSMIC credentials directly as CLI arguments on shared systems because command-line arguments can be exposed in shell history, process listings, and logs. Prefer the interactive prompt (`gget cosmic --download_cosmic ...`) or named environment variables read inside Python.
**Parameters**:
- `searchterm`: Gene name, Ensembl ID, mutation notation, or sample ID
@@ -586,38 +600,117 @@ Search COSMIC (Catalogue Of Somatic Mutations In Cancer) database.
**Database download flags**:
- `-d/--download_cosmic`: Activate download mode
- `-gm/--gget_mutate`: Create version for gget mutate
-- `-cp/--cosmic_project`: Database type (cancer, census, cell_line, resistance, genome_screen, targeted_screen)
+- `-cp/--cosmic_project`: Database type (cancer, cancer_example, census, cell_line, resistance, genome_screen, targeted_screen)
- `-cv/--cosmic_version`: COSMIC version
- `-gv/--grch_version`: Human reference genome (37 or 38)
-- `--email`, `--password`: COSMIC credentials
+- `--email`, `--password`: COSMIC credentials for non-interactive downloads; prefer prompt or Python env vars
**Examples**:
```bash
-# First download database
-gget cosmic -d --email [email protected] --password xxx -cp cancer
+# First download database; gget prompts for COSMIC email/password
+gget cosmic --download_cosmic --cosmic_project cancer
# Then query
-gget cosmic EGFR -ctp cosmic_data.tsv -l 10
+gget cosmic EGFR --cosmic_tsv_path "CancerMutationCensus_AllData_Tsv_v101_GRCh37/CancerMutationCensus_AllData_v101_GRCh37.tsv" -l 10
```
```python
# Python
+import os
+
+gget.cosmic(
+ searchterm=None,
+ download_cosmic=True,
+ cosmic_project="cancer",
+ email=os.environ["COSMIC_EMAIL"],
+ password=os.environ["COSMIC_PASSWORD"],
+)
gget.cosmic("EGFR", cosmic_tsv_path="cosmic_data.tsv", limit=10)
```
-### 5. Additional Tools
+### 5. Viral & Mouse Specificity Data
+
+#### gget virus - Viral Sequence Downloads
+
+Download viral nucleotide sequences plus linked metadata from INSDC sources via NCBI Virus, with optional GenBank metadata enrichment. Results are saved to an output folder as FASTA, CSV, JSONL, and a command summary file.
+
+**Parameters**:
+- `virus`: Virus taxon name, taxon ID, accession, space-separated accessions, or path to a text file of accessions
+- `-a/--is_accession`: Treat `virus` as accession input
+- `--is_sars_cov2`, `--is_alphainfluenza`: Use optimized cached NCBI datasets paths for SARS-CoV-2 or Influenza A
+- `--host`: Host organism name or NCBI taxonomy ID
+- `--nuc_completeness`: complete or partial
+- `--min_seq_length`, `--max_seq_length`: Sequence length filters
+- `-g/--genbank_metadata`: Fetch detailed GenBank metadata; auto-enabled by some annotation filters
+- `--segment`, `--vaccine_strain`, `--annotated`, `--lab_passaged`, `--source_database`: Common viral metadata filters
+- `--download_all_accessions`: Apply filters across all viral accessions
+- `--baseline`, `--merge-results`: Resume or merge with prior metadata from partial/previous runs
+
+**Important**: Do not use `--download_all_accessions` without restrictive filters; it can attempt to download the entire Viruses taxonomy and consume substantial time, bandwidth, and disk.
+
+**Examples**:
+```bash
+# Complete Zika genomes from human hosts
+gget virus "Zika virus" --nuc_completeness complete --host human --out zika_data
+
+# SARS-CoV-2 reference genome by accession
+gget virus NC_045512.2 --is_accession --is_sars_cov2
+```
+
+```python
+# Python
+gget.virus(
+ "SARS-CoV-2",
+ host="human",
+ nuc_completeness="complete",
+ min_seq_length=29000,
+ genbank_metadata=True,
+ is_sars_cov2=True,
+ outfolder="covid_data",
+)
+```
+
+#### gget 8cube - Mouse Specificity & Expression
+
+Query 8cubeDB for snRNA-seq gene specificity metrics and normalized expression values across mouse strains, tissues, sexes, and individuals.
+
+**Subcommands**:
+- `gget 8cube specificity <genes...>`: Return gene-level psi/zeta specificity statistics
+- `gget 8cube psi_block <genes...> --analysis_level <level> --analysis_type <type>`: Return block-level specificity
+- `gget 8cube expression <genes...> --analysis_level <level> --analysis_type <type>`: Return mean/variance normalized expression
+
+**Examples**:
+```bash
+gget 8cube specificity Acsm2 ENSMUSG00000046623.9
+gget 8cube psi_block Acsm2 --analysis_level Kidney --analysis_type "Sex:Celltype"
+gget 8cube expression Gjb4 --analysis_level Across_tissues --analysis_type Strain
+```
+
+```python
+# Python
+from gget import specificity, psi_block, gene_expression
+
+specificity(["Acsm2", "ENSMUSG00000046623.9"])
+psi_block(["Acsm2"], analysis_level="Kidney", analysis_type="Sex:Celltype")
+gene_expression(["Gjb4"], analysis_level="Across_tissues", analysis_type="Strain")
+```
+
+### 6. Additional Tools
#### gget mutate - Generate Mutated Sequences
Generate mutated nucleotide sequences from mutation annotations.
+**Current scope**: gget 0.29.1 simplified `mutate` to focus on applying standard mutation annotations to supplied nucleotide sequences and returning/saving mutated FASTA records. The broader variant-screening workflow moved upstream to the `kvar` project.
+
**Parameters**:
-- `sequences`: FASTA file path or direct sequence input (string/list)
-- `-m/--mutations`: CSV/TSV file or DataFrame with mutation data (required)
+- `sequences`: FASTA file path or direct nucleotide sequence input (string/list)
+- `-m/--mutations`: Mutation string/list, CSV/TSV path, or DataFrame with mutation data (required)
- `-mc/--mut_column`: Mutation column name (default: 'mutation')
- `-sic/--seq_id_column`: Sequence ID column (default: 'seq_ID')
-- `-mic/--mut_id_column`: Mutation ID column
+- `-mic/--mut_id_column`: Mutation ID column (default: same as mut_column)
- `-k/--k`: Length of flanking sequences (default: 30 nucleotides)
+- `-o/--out`: Output FASTA path; without it Python returns a list of mutated sequences
**Returns**: Mutated sequences in FASTA format
@@ -626,15 +719,14 @@ Generate mutated nucleotide sequences from mutation annotations.
# Single mutation
gget mutate ATCGCTAAGCT -m "c.4G>T"
-# Multiple sequences with mutations from file
-gget mutate sequences.fasta -m mutations.csv -o mutated.fasta
+# Multiple sequences with one mutation per sequence
+gget mutate ATCGCTAAGCT TAGCTA -m "c.4G>T" "c.1_3inv" -o mutated.fasta
```
```python
# Python
-import pandas as pd
-mutations_df = pd.DataFrame({"seq_ID": ["seq1"], "mutation": ["c.4G>T"]})
-gget.mutate(["ATCGCTAAGCT"], mutations=mutations_df)
+gget.mutate("ATCGCTAAGCT", "c.4G>T")
+gget.mutate(["ATCGCTAAGCT", "TAGCTA"], ["c.4G>T", "c.1_3inv"], out="mutated.fasta")
```
#### gget gpt - OpenAI Text Generation
@@ -646,37 +738,39 @@ Generate natural language text using OpenAI's API.
gget setup gpt
```
-**Important**: Free tier limited to 3 months after account creation. Set monthly billing limits.
+**Important**: Requires an OpenAI API key. Do not hard-code the key in notebooks, scripts, shell history, or committed files. Prefer a named environment variable such as `OPENAI_API_KEY`, and set monthly billing limits before use.
**Parameters**:
- `prompt`: Text input for generation (required)
-- `api_key`: OpenAI authentication (required)
-- Model configuration: temperature, top_p, max_tokens, frequency_penalty, presence_penalty
-- Default model: gpt-3.5-turbo (configurable)
+- `api_key`: OpenAI authentication (required by the upstream API)
+- Model configuration: model, temperature, top_p, stop, max_tokens, frequency_penalty, presence_penalty, logit_bias
+- Default model: gpt-3.5-turbo (upstream default; verify available models in your OpenAI account)
**Examples**:
-```bash
-gget gpt "Explain CRISPR" --api_key your_key_here
-```
+For CLI usage, `gget gpt` expects the API key as an argument. Avoid this on shared systems because process arguments can be visible to other users.
```python
# Python
-gget.gpt("Explain CRISPR", api_key="your_key_here")
+import os
+
+gget.gpt("Explain CRISPR", api_key=os.environ["OPENAI_API_KEY"])
```
#### gget setup - Install Dependencies
Install/download third-party dependencies for specific modules.
+As of gget 0.29.2, `gget setup` tries `uv pip install` first for Python dependencies and falls back to `pip install` if uv is unavailable or fails.
+
**Parameters**:
- `module`: Module name requiring dependency installation
- `-o/--out`: Output folder path (elm module only)
**Modules requiring setup**:
- `alphafold` - Downloads ~4GB of model parameters
-- `cellxgene` - Installs cellxgene-census (may not support latest Python)
+- `cellxgene` - Installs cellxgene-census (may require Python 3.9/3.10 if the latest Python is unsupported)
- `elm` - Downloads local ELM database
-- `gpt` - Configures OpenAI integration
+- `gpt` - Installs/configures OpenAI integration dependencies
**Examples**:
```bash
@@ -826,6 +920,7 @@ gget ref -w dna -d homo_sapiens
- Run `gget setup` before first use of alphafold, cellxgene, elm, gpt
- For enrichment analysis, use database shortcuts for convenience
- Cache cBioPortal data with `-dd` to avoid repeated downloads
+- For OpenTargets, inspect returned column names before writing filters; gget 0.30.5 follows the newer OpenTargets API schema
### Structure Prediction
- AlphaFold multimer predictions: use `-mr 20` for higher accuracy
@@ -833,11 +928,18 @@ gget ref -w dna -d homo_sapiens
- Visualize results in Python with `plot=True`
- Check PDB database first before running AlphaFold predictions
+### Viral Data
+- Use restrictive filters with `gget virus` before requesting broad viral datasets
+- Keep `command_summary.txt` with downstream results for reproducibility and recovery after partial downloads
+- Use `--baseline` and `--merge-results` to resume interrupted viral metadata/sequence downloads
+
### Error Handling
-- Database structures change; update gget regularly: `uv pip install --upgrade gget`
+- Database structures change; when an adapter breaks, check upstream release notes and pin the newer fixed version explicitly
+- Pin the known-good version for reproducible environments: `uv pip install "gget==0.30.5"`
- Process max ~1000 Ensembl IDs at once with gget info
- For large-scale analyses, implement rate limiting for API queries
- Use virtual environments to avoid dependency conflicts
+- Keep COSMIC and OpenAI credentials in named environment variables or interactive prompts; do not write real credentials into examples, notebooks, or logs
## Output Formats
@@ -847,12 +949,14 @@ gget ref -w dna -d homo_sapiens
- FASTA: gget seq, gget mutate
- PDB: gget pdb, gget alphafold
- PNG: gget cbio plot
+- FASTA/CSV/JSONL folder: gget virus
### Python
- Default: DataFrame or dictionary
- JSON: Add `json=True` parameter
- Save to file: Add `save=True` or specify `out="filename"`
- AnnData: gget cellxgene
+- DataFrame/JSON: gget 8cube specificity, psi_block, expression
## Resources
diff --git a/skills/gget/references/database_info.md b/skills/gget/references/database_info.md
index 54bc48af..0957e424 100644
--- a/skills/gget/references/database_info.md
+++ b/skills/gget/references/database_info.md
@@ -4,10 +4,10 @@ Overview of databases queried by gget modules, including update frequencies and
## Important Note
-The databases queried by gget are continuously being updated, which sometimes changes their structure. gget modules are tested automatically on a biweekly basis and updated to match new database structures when necessary. Always keep gget updated:
+The databases queried by gget are continuously being updated, which sometimes changes their structure. gget modules are tested automatically on a biweekly basis and updated to match new database structures when necessary. For reproducible environments matching this skill, pin the current verified version:
```bash
-pip install --upgrade gget
+uv pip install "gget==0.30.5"
```
## Database Directory
@@ -193,8 +193,35 @@ pip install --upgrade gget
- Free for academic use
- License fees apply for commercial use
- Requires COSMIC account credentials
+ - Prefer the interactive prompt or named environment variables over credentials in CLI arguments
- Must download database before querying
+#### NCBI Virus / INSDC
+- **Used by:** gget virus
+- **Description:** Viral nucleotide sequences and metadata from International Nucleotide Sequence Database Collaboration sources, accessed via NCBI Virus and optionally enriched with GenBank metadata
+- **Update frequency:** Continuous additions and corrections
+- **Access:** NCBI Virus / NCBI datasets APIs and bundled NCBI datasets CLI for optimized SARS-CoV-2 and Alphainfluenza paths
+- **Website:** https://www.ncbi.nlm.nih.gov/labs/virus/
+- **Data:**
+ - Viral nucleotide FASTA sequences
+ - Metadata CSV/JSONL
+ - Optional GenBank XML/CSV metadata and protein/gene annotations
+- **Notes:**
+ - Use restrictive host/completeness/date/length filters for broad taxa
+ - Keep command summaries for reproducibility and recovery
+ - Avoid unfiltered `--download_all_accessions`
+
+#### 8cubeDB
+- **Used by:** gget 8cube
+- **Description:** snRNA-seq-derived gene specificity and normalized expression metrics across mouse strains, tissues, sexes, and individuals
+- **Update frequency:** Project/version dependent
+- **Access:** 8cubeDB web API
+- **Website:** https://eightcubedb.onrender.com/
+- **Data:**
+ - Gene-level specificity metrics
+ - Block-level specificity metrics
+ - Mean and variance of normalized expression
+
### AI & Prediction Services
#### AlphaFold2 (DeepMind)
@@ -217,7 +244,7 @@ pip install --upgrade gget
- **Website:** https://openai.com/
- **Notes:**
- Default model: gpt-3.5-turbo
- - Free tier limited to 3 months after account creation
+ - Requires an API key; prefer `OPENAI_API_KEY` in Python workflows and avoid hard-coded keys
- Set billing limits to control costs
## Data Consistency & Reproducibility
@@ -240,6 +267,8 @@ To ensure reproducibility in analyses:
print(gget.__version__)
```
+ Current verified version for this skill: `0.30.5` (requires Python >=3.8).
+
3. **Save raw data:**
```python
# Always save results for reproducibility
@@ -262,6 +291,7 @@ To ensure reproducibility in analyses:
- Implement delays for large-scale queries
- Use local databases (DIAMOND, COSMIC) when possible
- Cache results to avoid repeated queries
+ - For `gget virus`, use restrictive filters and resume partial downloads with baseline/merge options
## Database-Specific Best Practices
@@ -289,6 +319,12 @@ To ensure reproducibility in analyses:
- cBioPortal: cache data locally for repeated analyses
- COSMIC: download appropriate database subset for your needs
- Respect license agreements for commercial use
+- Keep COSMIC credentials out of shell history, notebooks, and committed files
+
+### Viral Databases
+- Prefer taxon/accession-specific `gget virus` queries over all-accession downloads
+- Check `command_summary.txt` after each run for errors, software versions, and output paths
+- Use GenBank metadata only when needed because it increases runtime and output size
## Citations
diff --git a/skills/gget/references/module_reference.md b/skills/gget/references/module_reference.md
index 9f466d33..825ae0fd 100644
--- a/skills/gget/references/module_reference.md
+++ b/skills/gget/references/module_reference.md
@@ -11,7 +11,7 @@ Retrieve Ensembl reference genome FTPs and metadata.
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `species` | str | Species in Genus_species format or shortcuts ('human', 'mouse') | Required |
-| `-w/--which` | str | File types to return: gtf, cdna, dna, cds, cdrna, pep | All |
+| `-w/--which` | str/list | File types to return: gtf, cdna, dna, cds, cdrna, pep | All |
| `-r/--release` | int | Ensembl release number | Latest |
| `-od/--out_dir` | str | Output directory path | None |
| `-o/--out` | str | JSON file path for results | None |
@@ -27,6 +27,7 @@ Retrieve Ensembl reference genome FTPs and metadata.
### gget search
Search for genes by name or description in Ensembl.
+Search includes Ensembl synonyms in current gget versions.
**Parameters:**
| Parameter | Type | Description | Default |
@@ -38,6 +39,7 @@ Search for genes by name or description in Ensembl.
| `-ao/--andor` | str | 'or' (ANY term) or 'and' (ALL terms) | 'or' |
| `-l/--limit` | int | Maximum results to return | None |
| `-o/--out` | str | Output file path (CSV/JSON) | None |
+| `wrap_text` | bool | Python-only wrapped text display for wide results | False |
**Returns:** ensembl_id, gene_name, ensembl_description, ext_ref_description, biotype, URL
@@ -140,18 +142,18 @@ Align multiple sequences using Muscle5.
---
### gget diamond
-Fast local protein/translated DNA alignment.
+Fast local protein alignment and translated nucleotide-to-protein alignment.
**Parameters:**
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `query` | str/list | Query sequences or FASTA file | Required |
-| `--reference` | str/list | Reference sequences or FASTA file | Required |
-| `--sensitivity` | str | fast, mid-sensitive, sensitive, more-sensitive, very-sensitive, ultra-sensitive | very-sensitive |
-| `--threads` | int | CPU threads | 1 |
+| `-ref/--reference` | str/list | Reference sequences or FASTA file | Required |
+| `-s/--sensitivity` | str | fast, mid-sensitive, sensitive, more-sensitive, very-sensitive, ultra-sensitive | very-sensitive |
+| `-t/--threads` | int | CPU threads | 1 |
| `--diamond_binary` | str | Path to DIAMOND installation | Auto-detect |
-| `--diamond_db` | str | Save database for reuse | None |
-| `--translated` | flag | Enable nucleotide-to-amino acid alignment | False |
+| `-db/--diamond_db` | str | Save database for reuse | None |
+| `-x/--translated` | flag | Enable nucleotide query to amino acid reference alignment | False |
| `-o/--out` | str | Output file path | None |
| `-csv` | flag | CSV format (CLI) | False |
| `-q/--quiet` | flag | Suppress progress | False |
@@ -331,14 +333,15 @@ Retrieve disease/drug associations from OpenTargets.
| `-r/--resource` | str | diseases, drugs, tractability, pharmacogenetics, expression, depmap, interactions | 'diseases' |
| `-l/--limit` | int | Maximum results | None |
| `-o/--out` | str | Output file path | None |
+| `--filters` | repeated key=value / dict | Exact-match filters using returned column names | None |
+| `-or/--or` | flag | Combine CLI filters with OR instead of AND | False |
| `-csv` | flag | CSV format (CLI) | False |
| `-q/--quiet` | flag | Suppress progress | False |
-**Resource-specific filters:**
-- drugs: `--filter_disease`
-- pharmacogenetics: `--filter_drug`
-- expression/depmap: `--filter_tissue`, `--filter_anat_sys`, `--filter_organ`
-- interactions: `--filter_protein_a`, `--filter_protein_b`, `--filter_gene_b`
+**Current notes:**
+- gget 0.30.5 rewrote this module for the newer OpenTargets API; output column/key names may differ from older releases.
+- The older `--filter_mode` argument was removed upstream. Use CLI `--or` or Python filter logic documented by the current API.
+- Prefer inspecting returned column names before writing filters, then filter with exact column names such as `protein_a_id` or `gene_b_id`.
**Returns:** Disease/drug associations, tractability, pharmacogenetics, expression, DepMap, interactions
@@ -377,7 +380,7 @@ Plot cancer genomics heatmaps from cBioPortal.
### gget cosmic
Search COSMIC database for cancer mutations.
-**Important:** License fees for commercial use. Requires COSMIC account.
+**Important:** License fees for commercial use. Requires COSMIC account. Avoid passing credentials directly on the command line on shared systems; prefer the interactive prompt or Python code that reads named environment variables.
**Query parameters:**
| Parameter | Type | Description | Default |
@@ -392,11 +395,11 @@ Search COSMIC database for cancer mutations.
|-----------|------|-------------|---------|
| `-d/--download_cosmic` | flag | Activate download mode | False |
| `-gm/--gget_mutate` | flag | Create version for gget mutate | False |
-| `-cp/--cosmic_project` | str | cancer, census, cell_line, resistance, genome_screen, targeted_screen | None |
+| `-cp/--cosmic_project` | str | cancer, cancer_example, census, cell_line, resistance, genome_screen, targeted_screen | cancer |
| `-cv/--cosmic_version` | str | COSMIC version | Latest |
| `-gv/--grch_version` | int | Human reference genome (37 or 38) | None |
-| `--email` | str | COSMIC account email | Required |
-| `--password` | str | COSMIC account password | Required |
+| `--email` | str | COSMIC account email for non-interactive download | Prompt/env preferred |
+| `--password` | str | COSMIC account password for non-interactive download | Prompt/env preferred |
**Note:** First-time users must download database
@@ -404,6 +407,58 @@ Search COSMIC database for cancer mutations.
---
+### gget virus
+Download viral nucleotide sequences and metadata from INSDC sources via NCBI Virus.
+
+**Parameters:**
+| Parameter | Type | Description | Default |
+|-----------|------|-------------|---------|
+| `virus` | str | Virus taxon name, taxon ID, accession(s), or accession text file | Required unless `--download_all_accessions` |
+| `-a/--is_accession` | flag | Treat `virus` as accession input | False |
+| `--is_sars_cov2` | flag | Use optimized SARS-CoV-2 cached data path | False |
+| `--is_alphainfluenza` | flag | Use optimized Influenza A cached data path | False |
+| `--host` | str | Host organism name or NCBI Taxonomy ID | None |
+| `--nuc_completeness` | str | complete or partial | None |
+| `--min_seq_length` / `--max_seq_length` | int | Sequence length filters | None |
+| `--segment` | str | Segment filter for segmented viruses | None |
+| `--source_database` | str | genbank or refseq | None |
+| `--annotated` | bool | Include/exclude annotated sequences | None |
+| `--vaccine_strain` | bool | Include/exclude vaccine strain sequences | None |
+| `-g/--genbank_metadata` | flag | Fetch detailed GenBank metadata | False |
+| `--download_all_accessions` | flag | Apply filters across all viral accessions | False |
+| `--baseline` / `--merge-results` | path/flag | Resume or merge with previous metadata | None/False |
+| `-q/--quiet` | flag | Suppress progress | False |
+
+**Warning:** `--download_all_accessions` without restrictive filters can request the entire Viruses taxonomy and require many hours and substantial disk.
+
+**Returns:** FASTA, CSV, JSONL, optional GenBank metadata, and `command_summary.txt` in an output folder.
+
+---
+
+### gget 8cube
+Query 8cubeDB mouse snRNA-seq specificity and expression metrics.
+
+**Subcommands:**
+| Subcommand | Description | Required arguments |
+|------------|-------------|--------------------|
+| `specificity` | Gene-level psi/zeta specificity values | `genes` |
+| `psi_block` | Block-level specificity values | `genes`, `--analysis_level`, `--analysis_type` |
+| `expression` | Mean/variance normalized expression values | `genes`, `--analysis_level`, `--analysis_type` |
+
+**Common parameters:**
+| Parameter | Type | Description | Default |
+|-----------|------|-------------|---------|
+| `genes` | str/list | Gene symbols or Ensembl gene IDs | Required |
+| `-al/--analysis_level` | str | Biological grouping such as Kidney or Across_tissues | Required for psi_block/expression |
+| `-at/--analysis_type` | str | Partition type such as Sex:Celltype or Strain | Required for psi_block/expression |
+| `-csv/--csv` | flag | Return CSV instead of JSON (CLI) | False |
+| `-o/--out` | str | Output file path | None |
+| `-q/--quiet` | flag | Suppress progress | False |
+
+**Returns:** JSON/CSV on the CLI or DataFrame/JSON in Python.
+
+---
+
## Additional Tools
### gget mutate
@@ -412,17 +467,19 @@ Generate mutated nucleotide sequences.
**Parameters:**
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
-| `sequences` | str/list | FASTA file or sequences | Required |
-| `-m/--mutations` | str/df | CSV/TSV file or DataFrame | Required |
+| `sequences` | str/list | FASTA file or nucleotide sequence(s) | Required |
+| `-m/--mutations` | str/list/df | Mutation string/list, CSV/TSV file, or DataFrame | Required |
| `-mc/--mut_column` | str | Mutation column name | 'mutation' |
| `-sic/--seq_id_column` | str | Sequence ID column | 'seq_ID' |
-| `-mic/--mut_id_column` | str | Mutation ID column | None |
+| `-mic/--mut_id_column` | str | Mutation ID column | Same as mut_column |
| `-k/--k` | int | Length of flanking sequences | 30 |
-| `-o/--out` | str | Output FASTA file path | stdout |
+| `-o/--out` | str | Output FASTA file path | None (return list/stdout) |
| `-q/--quiet` | flag | Suppress progress | False |
**Returns:** Mutated sequences in FASTA format
+**Note:** More complex variant-screening functionality moved upstream to the `kvar` project.
+
---
### gget gpt
@@ -434,15 +491,17 @@ Generate text using OpenAI's API.
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `prompt` | str | Text input for generation | Required |
-| `api_key` | str | OpenAI API key | Required |
+| `api_key` | str | OpenAI API key; prefer reading from `OPENAI_API_KEY` | Required |
| `model` | str | OpenAI model name | gpt-3.5-turbo |
| `temperature` | float | Sampling temperature (0-2) | 1.0 |
| `top_p` | float | Nucleus sampling | 1.0 |
| `max_tokens` | int | Maximum tokens to generate | None |
| `frequency_penalty` | float | Frequency penalty (0-2) | 0 |
| `presence_penalty` | float | Presence penalty (0-2) | 0 |
+| `stop` | str | Stop sequence | None |
+| `logit_bias` | dict | Token bias map | None |
-**Important:** Free tier limited to 3 months. Set billing limits.
+**Important:** Do not hard-code API keys or pass real keys in examples. The upstream CLI accepts a key argument; Python code that reads `OPENAI_API_KEY` is safer for notebooks and scripts.
**Returns:** Generated text string
diff --git a/skills/gget/references/workflows.md b/skills/gget/references/workflows.md
index 487fc625..d31d031f 100644
--- a/skills/gget/references/workflows.md
+++ b/skills/gget/references/workflows.md
@@ -168,6 +168,7 @@ Analyze cancer-associated genes and their mutations.
```python
import gget
+import pandas as pd
import matplotlib.pyplot as plt
print("Cancer Genomics Analysis Workflow")
@@ -263,6 +264,7 @@ Analyze single-cell RNA-seq data for specific cell types and tissues.
```python
import gget
+import numpy as np
import scanpy as sc
print("Single-Cell Expression Analysis Workflow")
diff --git a/skills/pydeseq2/SKILL.md b/skills/pydeseq2/SKILL.md
index 2fd41595..75e4faa7 100644
--- a/skills/pydeseq2/SKILL.md
+++ b/skills/pydeseq2/SKILL.md
@@ -1,9 +1,11 @@
---
name: pydeseq2
-description: Differential gene expression analysis (Python DESeq2). Identify DE genes from bulk RNA-seq counts, Wald tests, FDR correction, volcano/MA plots, for RNA-seq analysis.
+description: Differential gene expression analysis for bulk RNA-seq with PyDESeq2, including formulaic designs, Wald tests, FDR correction, LFC shrinkage, and result visualization.
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python >=3.11 and PyDESeq2 0.5.4-compatible dependencies. Examples target PyDESeq2 0.5.x, formulaic design strings, explicit contrasts, and uv-based installs.
license: MIT license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +13,7 @@ metadata:
## Overview
-PyDESeq2 is a Python implementation of DESeq2 for differential expression analysis with bulk RNA-seq data. Design and execute complete workflows from data loading through result interpretation, including single-factor and multi-factor designs, Wald tests with multiple testing correction, optional apeGLM shrinkage, and integration with pandas and AnnData.
+PyDESeq2 is a Python implementation of DESeq2 for differential expression analysis with bulk RNA-seq data. Design and execute complete workflows from data loading through result interpretation, including formulaic single-factor and multi-factor designs, Wald tests with multiple testing correction, optional apeGLM shrinkage, and integration with pandas and AnnData.
## When to Use This Skill
@@ -30,6 +32,7 @@ For users who want to perform a standard differential expression analysis:
```python
import pandas as pd
from pydeseq2.dds import DeseqDataSet
+from pydeseq2.default_inference import DefaultInference
from pydeseq2.ds import DeseqStats
# 1. Load data
@@ -40,17 +43,26 @@ metadata = pd.read_csv("metadata.csv", index_col=0)
genes_to_keep = counts_df.columns[counts_df.sum(axis=0) >= 10]
counts_df = counts_df[genes_to_keep]
-# 3. Initialize and fit DESeq2
+# 3. Make the reference level explicit and fit DESeq2
+metadata["condition"] = pd.Categorical(
+ metadata["condition"], categories=["control", "treated"]
+)
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
- refit_cooks=True
+ refit_cooks=True,
+ inference=inference,
)
dds.deseq2()
# 4. Perform statistical testing
-ds = DeseqStats(dds, contrast=["condition", "treated", "control"])
+ds = DeseqStats(
+ dds,
+ contrast=["condition", "treated", "control"],
+ inference=inference,
+)
ds.summary()
# 5. Access results
@@ -114,10 +126,11 @@ design = "~group + condition + group:condition" # Interaction effects
```
**Design formula guidelines:**
-- Use Wilkinson formula notation (R-style)
+- Use formulaic/Wilkinson formula notation (R-style)
- Put adjustment variables (e.g., batch) before the main variable of interest
- Ensure variables exist as columns in the metadata DataFrame
-- Use appropriate data types (categorical for discrete variables)
+- Use appropriate data types; continuous variables are detected from the formula, and categorical variables can be forced with `C(variable)` or a pandas categorical dtype
+- Do not use deprecated `design_factors`, `continuous_factors`, or `ref_level` arguments in new workflows
### Step 3: DESeq2 Fitting
@@ -125,13 +138,16 @@ Initialize the DeseqDataSet and run the complete pipeline:
```python
from pydeseq2.dds import DeseqDataSet
+from pydeseq2.default_inference import DefaultInference
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
refit_cooks=True, # Refit after removing outliers
- n_cpus=1 # Parallel processing (adjust as needed)
+ inference=inference,
+ low_memory=False,
)
# Run the complete DESeq2 pipeline
@@ -169,7 +185,8 @@ ds.summary()
**Contrast specification:**
- Format: `[variable, test_level, reference_level]`
- Example: `["condition", "treated", "control"]` tests treated vs control
-- If `None`, uses the last coefficient in the design
+- Use a numeric contrast vector for continuous variables or complex coefficients
+- Default contrasts are no longer supported in PyDESeq2 0.5.x; always provide `contrast`
**Result DataFrame columns:**
- `baseMean`: Mean normalized count across samples
@@ -184,7 +201,7 @@ ds.summary()
Apply shrinkage to reduce noise in fold change estimates:
```python
-ds.lfc_shrink() # Applies apeGLM shrinkage
+ds.lfc_shrink(coeff="condition[T.treated]") # Applies apeGLM shrinkage
```
**When to use LFC shrinkage:**
@@ -199,8 +216,6 @@ ds.lfc_shrink() # Applies apeGLM shrinkage
Save results and intermediate objects:
```python
-import pickle
-
# Export results as CSV
ds.results_df.to_csv("deseq2_results.csv")
@@ -208,11 +223,12 @@ ds.results_df.to_csv("deseq2_results.csv")
significant = ds.results_df[ds.results_df.padj < 0.05]
significant.to_csv("significant_genes.csv")
-# Save DeseqDataSet for later use
-with open("dds_result.pkl", "wb") as f:
- pickle.dump(dds.to_picklable_anndata(), f)
+# Save a portable AnnData object for later inspection
+dds.to_picklable_anndata().write_h5ad("dds_result.h5ad")
```
+Avoid loading pickle files from untrusted sources. For exchange between agents, pipelines, or collaborators, prefer CSV results and `.h5ad` AnnData files.
+
## Common Analysis Patterns
### Two-Group Comparison
@@ -302,6 +318,7 @@ python scripts/run_deseq2_analysis.py \
--min-counts 10 \
--alpha 0.05 \
--n-cpus 4 \
+ --shrink-coeff "condition[T.treated]" \
--plots
```
@@ -310,7 +327,8 @@ python scripts/run_deseq2_analysis.py \
- Gene and sample filtering
- Complete DESeq2 pipeline execution
- Statistical testing with customizable parameters
-- Result export (CSV, pickle)
+- Result export (CSV and portable AnnData/H5AD)
+- Explicit LFC shrinkage coefficient support for PyDESeq2 0.5.x
- Optional visualization (volcano and MA plots)
Refer users to `scripts/run_deseq2_analysis.py` when they need a standalone analysis tool or want to batch process multiple datasets.
@@ -344,7 +362,7 @@ print(f"Downregulated: {len(downregulated)}")
top_by_padj = ds.results_df.sort_values("padj").head(20)
# Sort by absolute fold change (use shrunk values)
-ds.lfc_shrink()
+ds.lfc_shrink(coeff="condition[T.treated]")
ds.results_df["abs_lfc"] = abs(ds.results_df.log2FoldChange)
top_by_lfc = ds.results_df.sort_values("abs_lfc", ascending=False).head(20)
@@ -357,11 +375,11 @@ top_combined = ds.results_df.sort_values("score", ascending=False).head(20)
```python
# Check normalization (size factors should be close to 1)
-print("Size factors:", dds.obsm["size_factors"])
+print("Size factors:", dds.obs["size_factors"])
# Examine dispersion estimates
import matplotlib.pyplot as plt
-plt.hist(dds.varm["dispersions"], bins=50)
+plt.hist(dds.var["dispersions"], bins=50)
plt.xlabel("Dispersion")
plt.ylabel("Frequency")
plt.title("Dispersion Distribution")
@@ -484,11 +502,11 @@ design = "~condition + batch + condition:batch" # Model interaction
**Diagnostics:**
```python
# Check dispersion distribution
-plt.hist(dds.varm["dispersions"], bins=50)
+plt.hist(dds.var["dispersions"], bins=50)
plt.show()
# Check size factors
-print(dds.obsm["size_factors"])
+print(dds.obs["size_factors"])
# Look at top genes by raw p-value
print(ds.results_df.nsmallest(20, "pvalue"))
@@ -529,21 +547,23 @@ Load these references into context when users need:
7. **Contrast specification:** The format is `[variable, test_level, reference_level]` where test_level is compared against reference_level.
-8. **Save intermediate objects:** Use pickle to save DeseqDataSet objects for later use or additional analyses without re-running the expensive fitting step.
+8. **Save intermediate objects:** Prefer `dds.to_picklable_anndata().write_h5ad("dds_result.h5ad")` for portable outputs. Only load pickle files that you created yourself and trust.
## Installation and Requirements
```bash
-uv pip install pydeseq2
+uv pip install pydeseq2==0.5.4
```
**System requirements:**
-- Python 3.10-3.11
-- pandas 1.4.3+
-- numpy 1.23.0+
-- scipy 1.11.0+
-- scikit-learn 1.1.1+
-- anndata 0.8.0+
+- Python 3.11+
+- PyDESeq2 0.5.4
+- pandas 2.2.0+
+- numpy 2.0.0+
+- scipy 1.12.0+
+- scikit-learn 1.4.0+
+- anndata 0.11.0+
+- formulaic 1.0.2+ and formulaic-contrasts 0.2.0+
**Optional for visualization:**
- matplotlib
@@ -552,7 +572,7 @@ uv pip install pydeseq2
## Additional Resources
- **Official Documentation:** https://pydeseq2.readthedocs.io
-- **GitHub Repository:** https://github.com/owkin/PyDESeq2
+- **GitHub Repository:** https://github.com/scverse/PyDESeq2
- **Publication:** Muzellec et al. (2023) Bioinformatics, DOI: 10.1093/bioinformatics/btad547
- **Original DESeq2 (R):** Love et al. (2014) Genome Biology, DOI: 10.1186/s13059-014-0550-8
diff --git a/skills/pydeseq2/references/api_reference.md b/skills/pydeseq2/references/api_reference.md
index 60d1aba2..3c949c20 100644
--- a/skills/pydeseq2/references/api_reference.md
+++ b/skills/pydeseq2/references/api_reference.md
@@ -1,6 +1,6 @@
# PyDESeq2 API Reference
-This document provides comprehensive API reference for PyDESeq2 classes, methods, and utilities.
+This document provides a practical API reference for PyDESeq2 0.5.x classes, methods, and utilities.
## Core Classes
@@ -13,10 +13,16 @@ The main class for differential expression analysis that handles data processing
**Initialization Parameters:**
- `counts`: pandas DataFrame of shape (samples × genes) containing non-negative integer read counts
- `metadata`: pandas DataFrame of shape (samples × variables) with sample annotations
-- `design`: str, Wilkinson formula specifying the statistical model (e.g., "~condition", "~group + condition")
+- `design`: formulaic/Wilkinson formula string or design matrix specifying the statistical model (e.g., `"~condition"`, `"~batch + condition"`)
+- `fit_type`: dispersion trend fit type, `"parametric"` or `"mean"` (default: `"parametric"`)
+- `size_factors_fit_type`: size factor method, `"ratio"`, `"poscounts"`, or `"iterative"` (default: `"ratio"`)
+- `control_genes`: optional genes used for size factor fitting, useful for invariant housekeeping genes
- `refit_cooks`: bool, whether to refit parameters after removing Cook's distance outliers (default: True)
-- `n_cpus`: int, number of CPUs to use for parallel processing (optional)
+- `inference`: optional inference backend, usually `DefaultInference(n_cpus=...)`
- `quiet`: bool, suppress progress messages (default: False)
+- `low_memory`: bool, remove intermediate structures after use (default: False)
+
+**Deprecated 0.5.x parameters:** avoid `design_factors`, `continuous_factors`, and `ref_level` in new workflows. Continuous variables are detected from the formula; categorical handling should be expressed through formulaic syntax or pandas categorical dtypes.
**Key Methods:**
@@ -36,7 +42,7 @@ Run the complete DESeq2 pipeline for normalization and dispersion/LFC fitting.
**Returns:** None (modifies object in-place)
#### `to_picklable_anndata()`
-Convert the DeseqDataSet to an AnnData object that can be saved with pickle.
+Convert the DeseqDataSet to an AnnData object that can be serialized.
**Returns:** AnnData object with:
- `X`: count data matrix
@@ -46,11 +52,11 @@ Convert the DeseqDataSet to an AnnData object that can be saved with pickle.
**Usage:**
```python
-import pickle
-with open("result_adata.pkl", "wb") as f:
- pickle.dump(dds.to_picklable_anndata(), f)
+dds.to_picklable_anndata().write_h5ad("result_adata.h5ad")
```
+Only load pickle files from trusted sources. Prefer `.h5ad` or CSV for exchanging results between tools or collaborators.
+
**Attributes (after running deseq2()):**
- `layers`: dict containing various matrices (normalized counts, etc.)
- `varm`: dict containing gene-level results (log fold changes, dispersions, etc.)
@@ -67,15 +73,20 @@ Class for performing statistical tests and computing p-values for differential e
**Initialization Parameters:**
- `dds`: DeseqDataSet object that has been processed with `deseq2()`
-- `contrast`: list or None, specifies the contrast for testing
+- `contrast`: list or numpy array specifying the contrast for testing
- Format: `[variable, test_level, reference_level]`
- Example: `["condition", "treated", "control"]` tests treated vs control
- - If None, uses the last coefficient in the design formula
+ - Numeric contrast vectors must match the design matrix length
- `alpha`: float, significance threshold for independent filtering (default: 0.05)
- `cooks_filter`: bool, whether to filter outliers based on Cook's distance (default: True)
- `independent_filter`: bool, whether to perform independent filtering (default: True)
-- `n_cpus`: int, number of CPUs for parallel processing (optional)
+- `lfc_null`: log2 fold-change under the null hypothesis for thresholded tests (default: 0.0)
+- `alt_hypothesis`: optional thresholded-test alternative (`"greaterAbs"`, `"lessAbs"`, `"greater"`, or `"less"`)
+- `inference`: optional inference backend, usually the same `DefaultInference` object used for `DeseqDataSet`
- `quiet`: bool, suppress progress messages (default: False)
+- `n_cpus`: int, number of CPUs for parallel processing (optional)
+
+PyDESeq2 0.5.x no longer supports default contrasts. Always pass `contrast`.
**Key Methods:**
@@ -98,13 +109,14 @@ Run Wald tests and compute p-values and adjusted p-values.
- `pvalue`: raw p-value
- `padj`: adjusted p-value (FDR-corrected)
-#### `lfc_shrink(coeff=None)`
+#### `lfc_shrink(coeff, adapt=True)`
Apply shrinkage to log fold changes using the apeGLM method.
**Purpose:** Reduces noise in LFC estimates for better visualization and ranking, especially for genes with low counts or high variability.
**Parameters:**
-- `coeff`: str or None, coefficient name to shrink (if None, uses the coefficient from the contrast)
+- `coeff`: coefficient name to shrink, matching a column in `dds.obsm["design_matrix"]` (for example, `"condition[T.treated]"`)
+- `adapt`: whether to adapt the prior scale from MLE estimates (default: True)
**Important:** Shrinkage is applied only for visualization/ranking purposes. The statistical test results (p-values, adjusted p-values) remain unchanged.
@@ -117,12 +129,14 @@ Apply shrinkage to log fold changes using the apeGLM method.
## Utility Functions
-### `pydeseq2.utils.load_example_data(modality="single-factor")`
+### `pydeseq2.utils.load_example_data(modality, dataset="synthetic", debug=False)`
Load synthetic example datasets for testing and tutorials.
**Parameters:**
-- `modality`: str, either "single-factor" or "multi-factor"
+- `modality`: data modality to load, commonly `"raw_counts"` or `"metadata"`
+- `dataset`: example dataset name, commonly `"synthetic"`
+- `debug`: whether to load a smaller debug dataset
**Returns:** tuple of (counts_df, metadata_df)
- `counts_df`: pandas DataFrame with synthetic count data
@@ -132,7 +146,7 @@ Load synthetic example datasets for testing and tutorials.
## Preprocessing Module
-The `pydeseq2.preprocessing` module provides utilities for data preparation.
+The `pydeseq2.preprocessing` module provides normalization utilities used by the core pipeline.
**Common operations:**
- Gene filtering based on minimum read counts
@@ -185,14 +199,17 @@ Default implementation of inference methods using scipy, sklearn, and numpy.
```python
from pydeseq2.dds import DeseqDataSet
+from pydeseq2.default_inference import DefaultInference
from pydeseq2.ds import DeseqStats
# 1. Initialize dataset
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
- refit_cooks=True
+ refit_cooks=True,
+ inference=inference,
)
# 2. Fit dispersions and LFCs
@@ -202,12 +219,13 @@ dds.deseq2()
ds = DeseqStats(
dds,
contrast=["condition", "treated", "control"],
- alpha=0.05
+ alpha=0.05,
+ inference=inference,
)
ds.summary()
# 4. Optional: Shrink LFCs for visualization
-ds.lfc_shrink()
+ds.lfc_shrink(coeff="condition[T.treated]")
# 5. Access results
results = ds.results_df
@@ -217,12 +235,22 @@ results = ds.results_df
## Version Compatibility
-PyDESeq2 aims to match the default settings of DESeq2 v1.34.0. Some differences may exist as it is a from-scratch reimplementation in Python.
+PyDESeq2 aims to match the default settings of DESeq2 v1.34.0 for single-factor and multi-factor Wald-test workflows. Some differences may exist because it is a from-scratch reimplementation in Python.
**Tested with:**
-- Python 3.10-3.11
-- anndata 0.8.0+
-- numpy 1.23.0+
-- pandas 1.4.3+
-- scikit-learn 1.1.1+
-- scipy 1.11.0+
+- PyDESeq2 0.5.4
+- Python 3.11+
+- anndata 0.11.0+
+- formulaic 1.0.2+
+- formulaic-contrasts 0.2.0+
+- numpy 2.0.0+
+- pandas 2.2.0+
+- scikit-learn 1.4.0+
+- scipy 1.12.0+
+
+**Important 0.5.x changes:**
+- `design` should be a formulaic formula string or an explicit design matrix.
+- `design_factors`, `continuous_factors`, and `ref_level` are deprecated.
+- `DeseqStats` requires an explicit contrast.
+- `lfc_shrink()` requires an explicit `coeff`.
+- Python 3.10 support was dropped in 0.5.3; use Python 3.11 or newer.
diff --git a/skills/pydeseq2/references/workflow_guide.md b/skills/pydeseq2/references/workflow_guide.md
index 128d6257..8ad8c925 100644
--- a/skills/pydeseq2/references/workflow_guide.md
+++ b/skills/pydeseq2/references/workflow_guide.md
@@ -33,6 +33,7 @@ A standard PyDESeq2 analysis consists of 12 main steps across two phases:
```python
import pandas as pd
from pydeseq2.dds import DeseqDataSet
+from pydeseq2.default_inference import DefaultInference
from pydeseq2.ds import DeseqStats
# Load data
@@ -49,11 +50,16 @@ counts_df = counts_df.loc[samples_to_keep]
metadata = metadata.loc[samples_to_keep]
# Initialize DeseqDataSet
+metadata["condition"] = pd.Categorical(
+ metadata["condition"], categories=["control", "treated"]
+)
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
- refit_cooks=True
+ refit_cooks=True,
+ inference=inference,
)
# Run normalization and fitting
@@ -65,12 +71,13 @@ ds = DeseqStats(
contrast=["condition", "treated", "control"],
alpha=0.05,
cooks_filter=True,
- independent_filter=True
+ independent_filter=True,
+ inference=inference,
)
ds.summary()
# Optional: Apply LFC shrinkage for visualization
-ds.lfc_shrink()
+ds.lfc_shrink(coeff="condition[T.treated]")
# Access results
results = ds.results_df
@@ -106,17 +113,17 @@ counts_df = pd.read_csv("counts.tsv", sep="\t", index_col=0).T
metadata = pd.read_csv("metadata.tsv", sep="\t", index_col=0)
```
-**From saved pickle:**
+**From saved AnnData/H5AD:**
```python
-import pickle
-
-with open("counts.pkl", "rb") as f:
- counts_df = pickle.load(f)
+import anndata as ad
-with open("metadata.pkl", "rb") as f:
- metadata = pickle.load(f)
+adata = ad.read_h5ad("counts_and_metadata.h5ad")
+counts_df = pd.DataFrame(adata.X, index=adata.obs_names, columns=adata.var_names)
+metadata = adata.obs
```
+Do not load pickle files from untrusted sources. Use CSV/TSV or `.h5ad` for portable data exchange.
+
**From AnnData:**
```python
import anndata as ad
@@ -184,13 +191,16 @@ Compare treated vs control samples:
```python
from pydeseq2.dds import DeseqDataSet
+from pydeseq2.default_inference import DefaultInference
from pydeseq2.ds import DeseqStats
# Design: model expression as a function of condition
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
- design="~condition"
+ design="~condition",
+ inference=inference,
)
dds.deseq2()
@@ -198,7 +208,8 @@ dds.deseq2()
# Test treated vs control
ds = DeseqStats(
dds,
- contrast=["condition", "treated", "control"]
+ contrast=["condition", "treated", "control"],
+ inference=inference,
)
ds.summary()
@@ -271,8 +282,10 @@ dds = DeseqDataSet(
dds.deseq2()
-# Test the interaction term
-ds = DeseqStats(dds, contrast=["group:condition", ...])
+# Test interaction terms with an explicit numpy contrast vector matching the design matrix
+print(dds.obsm["design_matrix"].columns)
+interaction_contrast_vector = ... # e.g., np.array([...]) with one value per design column
+ds = DeseqStats(dds, contrast=interaction_contrast_vector)
ds.summary()
```
@@ -315,11 +328,8 @@ sorted_results.to_csv("sorted_results.csv")
**Save DeseqDataSet:**
```python
-import pickle
-
-# Save as AnnData for later use
-with open("dds_result.pkl", "wb") as f:
- pickle.dump(dds.to_picklable_anndata(), f)
+# Save as AnnData/H5AD for later inspection
+dds.to_picklable_anndata().write_h5ad("dds_result.h5ad")
```
**Load saved results:**
@@ -328,8 +338,8 @@ with open("dds_result.pkl", "wb") as f:
results = pd.read_csv("deseq2_results.csv", index_col=0)
# Load AnnData
-with open("dds_result.pkl", "rb") as f:
- adata = pickle.load(f)
+import anndata as ad
+adata = ad.read_h5ad("dds_result.h5ad")
```
### Basic Visualization
@@ -409,24 +419,33 @@ metadata["condition"] = metadata["condition"].astype("category")
metadata["batch"] = metadata["batch"].astype("category")
```
+**Use current formulaic design syntax:**
+```python
+# Preferred in PyDESeq2 0.5.x
+design = "~batch + condition"
+
+# Avoid deprecated constructor arguments:
+# design_factors, continuous_factors, ref_level
+```
+
### 3. Statistical Testing Guidelines
**Set appropriate alpha:**
```python
# Standard significance threshold
-ds = DeseqStats(dds, alpha=0.05)
+ds = DeseqStats(dds, contrast=["condition", "treated", "control"], alpha=0.05)
# More stringent for exploratory analysis
-ds = DeseqStats(dds, alpha=0.01)
+ds = DeseqStats(dds, contrast=["condition", "treated", "control"], alpha=0.01)
```
**Use independent filtering:**
```python
# Recommended: filter low-power tests
-ds = DeseqStats(dds, independent_filter=True)
+ds = DeseqStats(dds, contrast=["condition", "treated", "control"], independent_filter=True)
# Only disable if you have specific reasons
-ds = DeseqStats(dds, independent_filter=False)
+ds = DeseqStats(dds, contrast=["condition", "treated", "control"], independent_filter=False)
```
### 4. LFC Shrinkage
@@ -443,7 +462,7 @@ ds = DeseqStats(dds, independent_filter=False)
```python
# Save both versions
ds.results_df.to_csv("results_unshrunken.csv")
-ds.lfc_shrink()
+ds.lfc_shrink(coeff="condition[T.treated]")
ds.results_df.to_csv("results_shrunken.csv")
```
@@ -452,11 +471,12 @@ ds.results_df.to_csv("results_shrunken.csv")
For large datasets:
```python
# Use parallel processing
+inference = DefaultInference(n_cpus=4)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design="~condition",
- n_cpus=4 # Adjust based on available cores
+ inference=inference, # Adjust based on available cores
)
# Process in batches if needed
@@ -553,14 +573,14 @@ design = "~condition + batch + condition:batch" # Add interaction
```python
# Check dispersion estimates
import matplotlib.pyplot as plt
-dispersions = dds.varm["dispersions"]
+dispersions = dds.var["dispersions"]
plt.hist(dispersions, bins=50)
plt.xlabel("Dispersion")
plt.ylabel("Frequency")
plt.show()
# Check size factors (should be close to 1)
-print("Size factors:", dds.obsm["size_factors"])
+print("Size factors:", dds.obs["size_factors"])
# Look at top genes even if not significant
top_genes = ds.results_df.nsmallest(20, "pvalue")
@@ -572,7 +592,8 @@ print(top_genes)
**Solutions:**
```python
# 1. Use fewer CPUs (paradoxically can help)
-dds = DeseqDataSet(..., n_cpus=1)
+inference = DefaultInference(n_cpus=1)
+dds = DeseqDataSet(..., inference=inference)
# 2. Filter more aggressively
genes_to_keep = counts_df.columns[counts_df.sum(axis=0) >= 20]
diff --git a/skills/pydeseq2/scripts/run_deseq2_analysis.py b/skills/pydeseq2/scripts/run_deseq2_analysis.py
index db9df25b..96c61f23 100644
--- a/skills/pydeseq2/scripts/run_deseq2_analysis.py
+++ b/skills/pydeseq2/scripts/run_deseq2_analysis.py
@@ -17,8 +17,6 @@ Requirements:
"""
import argparse
-import os
-import pickle
import sys
from pathlib import Path
@@ -26,9 +24,10 @@ import pandas as pd
try:
from pydeseq2.dds import DeseqDataSet
+ from pydeseq2.default_inference import DefaultInference
from pydeseq2.ds import DeseqStats
except ImportError:
- print("Error: pydeseq2 not installed. Install with: pip install pydeseq2")
+ print("Error: pydeseq2 not installed. Install with: uv pip install pydeseq2==0.5.4")
sys.exit(1)
@@ -94,12 +93,13 @@ def run_deseq2(counts_df, metadata, design, n_cpus=1):
"""Run DESeq2 normalization and fitting."""
print(f"\nInitializing DeseqDataSet with design: {design}")
+ inference = DefaultInference(n_cpus=n_cpus)
dds = DeseqDataSet(
counts=counts_df,
metadata=metadata,
design=design,
refit_cooks=True,
- n_cpus=n_cpus,
+ inference=inference,
quiet=False
)
@@ -116,10 +116,23 @@ def run_deseq2(counts_df, metadata, design, n_cpus=1):
print("\n✓ DESeq2 fitting complete")
- return dds
+ return dds, inference
-def run_statistical_tests(dds, contrast, alpha=0.05, shrink_lfc=True):
+def infer_shrink_coeff(dds, contrast):
+ """Infer the formulaic coefficient name for a categorical contrast."""
+ coeff = f"{contrast[0]}[T.{contrast[1]}]"
+ design_columns = list(dds.obsm["design_matrix"].columns)
+ if coeff in design_columns:
+ return coeff
+ raise ValueError(
+ "Could not infer LFC shrinkage coefficient "
+ f"{coeff!r}. Available design columns: {design_columns}. "
+ "Pass --shrink-coeff explicitly or use --no-shrink."
+ )
+
+
+def run_statistical_tests(dds, contrast, alpha=0.05, shrink_lfc=True, inference=None, shrink_coeff=None):
"""Perform Wald tests and compute p-values."""
print(f"\nPerforming statistical tests...")
print(f" Contrast: {contrast}")
@@ -131,6 +144,7 @@ def run_statistical_tests(dds, contrast, alpha=0.05, shrink_lfc=True):
alpha=alpha,
cooks_filter=True,
independent_filter=True,
+ inference=inference,
quiet=False
)
@@ -146,7 +160,8 @@ def run_statistical_tests(dds, contrast, alpha=0.05, shrink_lfc=True):
# Optional LFC shrinkage
if shrink_lfc:
print("\nApplying LFC shrinkage for visualization...")
- ds.lfc_shrink()
+ coeff = shrink_coeff or infer_shrink_coeff(dds, contrast)
+ ds.lfc_shrink(coeff=coeff)
print("✓ LFC shrinkage complete")
return ds
@@ -176,10 +191,9 @@ def save_results(ds, dds, output_dir, shrink_lfc=True):
sorted_results.to_csv(sorted_path)
print(f" Saved: {sorted_path}")
- # Save DeseqDataSet as pickle
- dds_path = output_dir / "deseq_dataset.pkl"
- with open(dds_path, "wb") as f:
- pickle.dump(dds.to_picklable_anndata(), f)
+ # Save as AnnData/H5AD to avoid unsafe pickle interchange.
+ dds_path = output_dir / "deseq_dataset.h5ad"
+ dds.to_picklable_anndata().write_h5ad(dds_path)
print(f" Saved: {dds_path}")
# Print summary
@@ -286,29 +300,46 @@ Examples:
--design "~batch + condition" \\
--contrast condition treated control \\
--output results/ \\
- --n-cpus 4
+ --n-cpus 4 \\
+ --shrink-coeff "condition[T.treated]"
"""
)
parser.add_argument("--counts", required=True, help="Path to count matrix CSV file")
parser.add_argument("--metadata", required=True, help="Path to metadata CSV file")
parser.add_argument("--design", required=True, help="Design formula (e.g., '~condition')")
- parser.add_argument("--contrast", nargs=3, required=True,
- metavar=("VARIABLE", "TEST", "REFERENCE"),
- help="Contrast specification: variable test_level reference_level")
+ parser.add_argument(
+ "--contrast",
+ nargs=3,
+ required=True,
+ metavar=("VARIABLE", "TEST", "REFERENCE"),
+ help="Contrast specification: variable test_level reference_level",
+ )
parser.add_argument("--output", default="results", help="Output directory (default: results)")
- parser.add_argument("--min-counts", type=int, default=10,
- help="Minimum total counts for gene filtering (default: 10)")
- parser.add_argument("--alpha", type=float, default=0.05,
- help="Significance threshold (default: 0.05)")
- parser.add_argument("--no-transpose", action="store_true",
- help="Don't transpose count matrix (use if already samples × genes)")
- parser.add_argument("--no-shrink", action="store_true",
- help="Skip LFC shrinkage")
- parser.add_argument("--n-cpus", type=int, default=1,
- help="Number of CPUs for parallel processing (default: 1)")
- parser.add_argument("--plots", action="store_true",
- help="Generate volcano and MA plots")
+ parser.add_argument(
+ "--min-counts",
+ type=int,
+ default=10,
+ help="Minimum total counts for gene filtering (default: 10)",
+ )
+ parser.add_argument("--alpha", type=float, default=0.05, help="Significance threshold (default: 0.05)")
+ parser.add_argument(
+ "--no-transpose",
+ action="store_true",
+ help="Don't transpose count matrix (use if already samples × genes)",
+ )
+ parser.add_argument("--no-shrink", action="store_true", help="Skip LFC shrinkage")
+ parser.add_argument(
+ "--shrink-coeff",
+ help="Design-matrix coefficient to shrink (e.g., 'condition[T.treated]')",
+ )
+ parser.add_argument(
+ "--n-cpus",
+ type=int,
+ default=1,
+ help="Number of CPUs for parallel processing (default: 1)",
+ )
+ parser.add_argument("--plots", action="store_true", help="Generate volcano and MA plots")
args = parser.parse_args()
@@ -316,7 +347,7 @@ Examples:
counts_df, metadata = load_and_validate_data(
args.counts,
args.metadata,
- transpose_counts=not args.no_transpose
+ transpose_counts=not args.no_transpose,
)
# Filter data
@@ -325,18 +356,20 @@ Examples:
counts_df,
metadata,
min_counts=args.min_counts,
- condition_col=condition_col
+ condition_col=condition_col,
)
# Run DESeq2
- dds = run_deseq2(counts_df, metadata, args.design, n_cpus=args.n_cpus)
+ dds, inference = run_deseq2(counts_df, metadata, args.design, n_cpus=args.n_cpus)
# Statistical testing
ds = run_statistical_tests(
dds,
contrast=args.contrast,
alpha=args.alpha,
- shrink_lfc=not args.no_shrink
+ shrink_lfc=not args.no_shrink,
+ inference=inference,
+ shrink_coeff=args.shrink_coeff,
)
# Save results
diff --git a/skills/umap-learn/SKILL.md b/skills/umap-learn/SKILL.md
index 8e88e9a4..6d42ce38 100644
--- a/skills/umap-learn/SKILL.md
+++ b/skills/umap-learn/SKILL.md
@@ -1,9 +1,9 @@
---
name: umap-learn
-description: UMAP dimensionality reduction. Fast nonlinear manifold learning for 2D/3D visualization, clustering preprocessing (HDBSCAN), supervised/parametric UMAP, for high-dimensional data.
+description: Use UMAP-learn for nonlinear dimensionality reduction, 2D/3D embeddings, clustering preprocessing, supervised or semi-supervised UMAP, DensMAP, AlignedUMAP, and Parametric UMAP workflows.
license: BSD-3-Clause license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -17,7 +17,7 @@ UMAP (Uniform Manifold Approximation and Projection) is a dimensionality reducti
### Installation
-Requires Python 3.9+. Pin to a verified release:
+Current stable release: **umap-learn 0.5.12** (released April 2026). Requires Python 3.9+ and depends on `scikit-learn>=1.6`, `numba`, `pynndescent`, `numpy`, and `scipy`. Pin to a verified release:
```bash
uv pip install umap-learn==0.5.12
@@ -43,7 +43,7 @@ reducer.fit(scaled_data)
embedding = reducer.embedding_ # Access the trained embedding
```
-**Critical preprocessing requirement:** Always standardize features to comparable scales before applying UMAP to ensure equal weighting across dimensions.
+**Preprocessing requirement:** Match preprocessing to the metric. For numeric Euclidean-style metrics, scale features before fitting so high-variance columns do not dominate. For cosine, binary, precomputed-distance, or mixed-feature workflows, choose preprocessing that matches the metric instead of blindly standardizing every column.
### Typical Workflow
@@ -162,8 +162,6 @@ embedding = umap.UMAP().fit_transform(data, y=labels)
- Preserves internal structure within each class
- Maintains global relationships between classes
-**When to use:** When you have labeled data and want to separate known classes while keeping meaningful point embeddings.
-
### Semi-Supervised UMAP
For partial labels, mark unlabeled points with `-1` following scikit-learn convention:
@@ -179,25 +177,6 @@ embedding = umap.UMAP().fit_transform(data, y=semi_labels)
**When to use:** When labeling is expensive or you have more data than labels available.
-### Metric Learning with UMAP
-
-Train a supervised embedding on labeled data, then apply to new unlabeled data:
-
-```python
-# Train on labeled data
-mapper = umap.UMAP().fit(train_data, train_labels)
-
-# Transform unlabeled test data
-test_embedding = mapper.transform(test_data)
-
-# Use as feature engineering for downstream classifier
-from sklearn.svm import SVC
-clf = SVC().fit(mapper.embedding_, train_labels)
-predictions = clf.predict(test_embedding)
-```
-
-**When to use:** For supervised feature engineering in machine learning pipelines.
-
## UMAP for Clustering
UMAP serves as effective preprocessing for density-based clustering algorithms like HDBSCAN, overcoming the curse of dimensionality.
@@ -318,7 +297,7 @@ print(f"Test accuracy: {accuracy:.3f}")
**Performance:** Transform operations are efficient (typically <1 second), though initial calls may be slower due to Numba JIT compilation.
-**Scikit-learn compatibility:** UMAP follows standard sklearn conventions and works seamlessly in pipelines. Since 0.5.x, `UMAP` implements `get_feature_names_out()` for sklearn column-transformer pipelines:
+**Scikit-learn compatibility:** UMAP follows standard sklearn conventions and works in pipelines. Recent 0.5.x releases also improved feature-name support and compatibility with current scikit-learn validation APIs:
```python
from sklearn.pipeline import Pipeline
@@ -349,7 +328,7 @@ Parametric UMAP replaces direct embedding optimization with a learned neural net
**Installation:**
```bash
uv pip install "umap-learn[parametric-umap]==0.5.12"
-# Requires TensorFlow 2.x (install separately if needed)
+# Installs the TensorFlow-backed Parametric UMAP extra.
```
**Basic usage:**
@@ -370,7 +349,7 @@ import tensorflow as tf
# Define custom encoder
encoder = tf.keras.Sequential([
- tf.keras.layers.InputLayer(input_shape=(input_dim,)),
+ tf.keras.layers.InputLayer(shape=(input_dim,)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(2) # Output dimension
@@ -380,17 +359,24 @@ embedder = ParametricUMAP(encoder=encoder, dims=(input_dim,))
embedding = embedder.fit_transform(data)
```
+**Persistence:** Save Parametric UMAP with its built-in Keras-aware methods rather than plain pickle:
+
+```python
+embedder.save("parametric_umap_model", exclude_raw_data=True)
+
+from umap.parametric_umap import load_ParametricUMAP
+loaded = load_ParametricUMAP("parametric_umap_model")
+new_embedding = loaded.transform(new_data)
+```
+
+Recent 0.5.12 fixes include Parametric UMAP retraining stability improvements and metric-gradient fixes, so prefer the pinned current release for neural-network workflows.
+
**When to use Parametric UMAP:**
- Need efficient transformation of new data after training
- Require reconstruction capabilities (inverse transforms)
- Want to combine UMAP with autoencoders
- Working with complex data types (images, sequences) benefiting from specialized architectures
-**When to use standard UMAP:**
-- Need simplicity and quick prototyping
-- Dataset is small and computational efficiency isn't critical
-- Don't require learned transformations for future data
-
### Inverse Transforms
Inverse transforms enable reconstruction of high-dimensional data from low-dimensional embeddings.
@@ -409,12 +395,6 @@ reconstructed = reducer.inverse_transform(embedding)
- Works poorly outside the convex hull of the embedding
- Accuracy decreases in regions with gaps between clusters
-**Use cases:**
-- Understanding structure of embedded data
-- Visualizing smooth transitions between clusters
-- Exploring interpolations between data points
-- Generating synthetic samples in embedding space
-
**Example: Exploring embedding space:**
```python
import numpy as np
@@ -439,12 +419,18 @@ from umap import AlignedUMAP
# List of related datasets
datasets = [day1_data, day2_data, day3_data]
+# Relations map matching sample indices between consecutive datasets.
+relations = [
+ {day1_idx: day2_idx for day1_idx, day2_idx in matched_day1_to_day2},
+ {day2_idx: day3_idx for day2_idx, day3_idx in matched_day2_to_day3},
+]
+
# Create aligned embeddings
-mapper = AlignedUMAP().fit(datasets)
+mapper = AlignedUMAP().fit(datasets, relations=relations)
aligned_embeddings = mapper.embeddings_ # List of embeddings
```
-**When to use:** Comparing embeddings across related datasets while maintaining consistent coordinate systems.
+**When to use:** Comparing embeddings across related datasets while maintaining consistent coordinate systems. `relations` is required for meaningful alignment; each dictionary describes how samples in one dataset correspond to samples in the next.
## Reproducibility
@@ -456,6 +442,8 @@ reducer = umap.UMAP(random_state=42)
UMAP uses stochastic optimization, so results will vary slightly between runs without a fixed random state.
+Setting `random_state` prioritizes deterministic output. Leave it unset when throughput matters more than exact repeatability, because UMAP can use more parallelism without a fixed seed.
+
## Common Issues and Solutions
**Issue:** Disconnected components or fragmented clusters
@@ -474,11 +462,14 @@ UMAP uses stochastic optimization, so results will vary slightly between runs wi
- **Solution:** Set `low_memory=True` (default), or consider dimensionality reduction with PCA first
**Issue:** NaN or inf values in input data
-- **Solution:** Impute or drop invalid rows before fitting (0.5.6+ accepts NaN/inf in some paths, but clean numeric input is still recommended)
+- **Solution:** Impute or drop invalid rows before fitting. Current UMAP uses scikit-learn-style finite-value checks (`ensure_all_finite`) in `fit()` and `update()`, so clean numeric input is the safest default
**Issue:** All points collapsed to single cluster
- **Solution:** Check data preprocessing (ensure proper scaling), increase `min_dist`
+**Issue:** Imports resolve to a local file instead of the real package
+- **Solution:** Do not keep project files named `umap.py`, `sklearn.py`, `hdbscan.py`, or `tensorflow.py` beside notebooks or scripts. Those names can shadow installed packages and break or poison examples.
+
## Resources
### Official documentation
diff --git a/skills/umap-learn/references/api_reference.md b/skills/umap-learn/references/api_reference.md
index 30239cce..f499529a 100644
--- a/skills/umap-learn/references/api_reference.md
+++ b/skills/umap-learn/references/api_reference.md
@@ -1,10 +1,10 @@
# UMAP API Reference
-Reference for **umap-learn 0.5.12** (Python >=3.9). See [official API guide](https://umap-learn.readthedocs.io/en/latest/api.html) for the full upstream reference.
+Reference for **umap-learn 0.5.12** (Python >=3.9; `scikit-learn>=1.6`). See [official API guide](https://umap-learn.readthedocs.io/en/latest/api.html) and the 0.5.12 GitHub tag for the full upstream reference.
## UMAP Class
-`umap.UMAP(n_neighbors=15, n_components=2, metric='euclidean', n_epochs=None, learning_rate=1.0, init='spectral', min_dist=0.1, spread=1.0, low_memory=True, set_op_mix_ratio=1.0, local_connectivity=1.0, repulsion_strength=1.0, negative_sample_rate=5, transform_queue_size=4.0, a=None, b=None, random_state=None, metric_kwds=None, angular_rp_forest=False, target_n_neighbors=-1, target_metric='categorical', target_metric_kwds=None, target_weight=0.5, transform_seed=42, transform_mode='embedding', force_approximation_algorithm=False, verbose=False, unique=False, densmap=False, dens_lambda=2.0, dens_frac=0.3, dens_var_shift=0.1, output_dens=False, disconnection_distance=None, precomputed_knn=(None, None, None))`
+`umap.UMAP(n_neighbors=15, n_components=2, metric='euclidean', metric_kwds=None, output_metric='euclidean', output_metric_kwds=None, n_epochs=None, learning_rate=1.0, init='spectral', min_dist=0.1, spread=1.0, low_memory=True, n_jobs=-1, set_op_mix_ratio=1.0, local_connectivity=1.0, repulsion_strength=1.0, negative_sample_rate=5, transform_queue_size=4.0, a=None, b=None, random_state=None, angular_rp_forest=False, target_n_neighbors=-1, target_metric='categorical', target_metric_kwds=None, target_weight=0.5, transform_seed=42, transform_mode='embedding', force_approximation_algorithm=False, verbose=False, tqdm_kwds=None, unique=False, densmap=False, dens_lambda=2.0, dens_frac=0.3, dens_var_shift=0.1, output_dens=False, disconnection_distance=None, precomputed_knn=(None, None, None))`
Find low-dimensional embedding that approximates the underlying manifold of the data.
@@ -46,6 +46,9 @@ Distance metric to use. Accepts:
- `'minkowski'`: Minkowski distance (specify p with metric_kwds)
- `'precomputed'`: Use precomputed distance matrix
+#### output_metric (str or callable, default: 'euclidean')
+Distance metric for the embedding space. Most workflows should keep the Euclidean default; advanced workflows can use a supported output metric with `output_metric_kwds`.
+
#### min_dist (float, default: 0.1)
Effective minimum distance between embedded points. Controls how tightly points are packed together. Smaller values result in clumpier embeddings.
@@ -125,9 +128,15 @@ Method for transforming new data:
#### low_memory (bool, default: True)
Whether to use a memory-efficient implementation. Set to False only if memory is not a constraint and you want faster performance.
+#### n_jobs (int, default: -1)
+Number of parallel jobs to use where supported. `-1` uses all available processors. Setting `random_state` can limit parallel optimization in favor of reproducibility.
+
#### verbose (bool, default: False)
Whether to print progress messages during fitting.
+#### tqdm_kwds (dict, default: None)
+Keyword arguments passed to the tqdm progress bar when progress reporting is enabled.
+
#### unique (bool, default: False)
Whether to consider only unique data points. Set to True if you know your data contains many duplicates to improve performance.
@@ -154,7 +163,7 @@ Fraction of dataset used for density estimation in DensMAP.
Regularization parameter for density estimation in DensMAP.
#### output_dens (bool, default: False)
-Whether to output local density estimates in addition to the embedding. Results stored in `rad_orig_` and `rad_emb_` attributes.
+Whether to output local density estimates in addition to the embedding. When enabled, `fit_transform()` returns `(embedding, original_local_radii, embedded_local_radii)` and fitted objects expose density-related attributes such as `rad_orig_` and `rad_emb_`.
### Other Parameters
@@ -178,12 +187,13 @@ Precomputed k-nearest neighbors as (knn_indices, knn_dists, knn_search_index). U
## Methods
-### fit(X, y=None)
+### fit(X, y=None, ensure_all_finite=True, **kwargs)
Fit the UMAP model to the data.
**Parameters:**
- `X`: array-like, shape (n_samples, n_features) - Training data
- `y`: array-like, shape (n_samples,), optional - Target values for supervised dimension reduction
+- `ensure_all_finite`: bool or sklearn-compatible option - Controls finite-value validation during fitting
**Returns:**
- `self`: Fitted UMAP object
@@ -236,11 +246,12 @@ Transform data from the embedded space back to the original data space.
- Works poorly outside the convex hull of the training embedding
- Reconstruction quality varies by region
-### update(X)
+### update(X, ensure_all_finite=True)
Update the model with new data. Allows incremental fitting.
**Parameters:**
- `X`: array-like, shape (n_samples, n_features) - New data to incorporate
+- `ensure_all_finite`: bool or sklearn-compatible option - Controls finite-value validation during update
**Returns:**
- `self`: Updated UMAP object
@@ -287,7 +298,7 @@ list - Random projection forest used for approximate nearest neighbor search.
## ParametricUMAP Class
-`umap.parametric_umap.ParametricUMAP(encoder=None, decoder=None, parametric_reconstruction=False, autoencoder_loss=False, reconstruction_validation=None, dims=None, batch_size=None, n_training_epochs=1, loss_report_frequency=10, optimizer=None, keras_fit_kwargs={}, **kwargs)`
+`umap.parametric_umap.ParametricUMAP(batch_size=None, dims=None, encoder=None, decoder=None, parametric_reconstruction=False, parametric_reconstruction_loss_fcn=None, parametric_reconstruction_loss_weight=1.0, autoencoder_loss=False, reconstruction_validation=None, global_correlation_loss_weight=0, landmark_loss_fn=None, landmark_loss_weight=1.0, keras_fit_kwargs={}, **kwargs)`
Install with `uv pip install "umap-learn[parametric-umap]==0.5.12"`. Parametric UMAP uses neural networks to learn the embedding function.
@@ -302,9 +313,18 @@ Keras model for decoding embeddings back to data space. Only used if parametric_
#### parametric_reconstruction (bool, default: False)
Whether to use parametric reconstruction. Requires decoder model.
+#### parametric_reconstruction_loss_fcn (callable, default: None)
+Custom reconstruction loss function for decoder training.
+
+#### parametric_reconstruction_loss_weight (float, default: 1.0)
+Weight applied to the parametric reconstruction loss.
+
#### autoencoder_loss (bool, default: False)
Whether to include reconstruction loss in the optimization. Requires decoder model.
+#### global_correlation_loss_weight (float, default: 0)
+Weight for global correlation loss, used to encourage preservation of broad distance relationships.
+
#### reconstruction_validation (tuple, default: None)
Validation data (X_val, y_val) for monitoring reconstruction loss during training.
@@ -314,22 +334,28 @@ Input dimensions for the encoder network. Required if providing custom encoder.
#### batch_size (int, default: None)
Batch size for neural network training. If None, determined automatically.
-#### n_training_epochs (int, default: 1)
-Number of training epochs for the neural networks. More epochs improve quality but increase training time.
-
-#### loss_report_frequency (int, default: 10)
-How often to report loss during training.
+#### landmark_loss_fn (callable, default: None)
+Loss function used when retraining with landmark positions.
-#### optimizer (tensorflow.keras.optimizers.Optimizer, default: None)
-Keras optimizer for training. If None, uses Adam with learning_rate parameter.
+#### landmark_loss_weight (float, default: 1.0)
+Weight applied to landmark loss relative to the UMAP loss.
#### keras_fit_kwargs (dict, default: {})
Additional keyword arguments passed to the Keras fit() method.
+#### Training epoch attributes
+`ParametricUMAP` initializes `n_training_epochs=1` and `loss_report_frequency=10` internally. Set these attributes after construction when you need longer neural-network training.
+
### Methods
Same as UMAP class, but transform() and inverse_transform() use learned neural networks for faster inference.
+#### fit(X, y=None, precomputed_distances=None, landmark_positions=None)
+Fit the parametric model. `landmark_positions` can be used for landmarked retraining workflows.
+
+#### save(save_location, verbose=True, exclude_raw_data=False)
+Save the Parametric UMAP object and Keras networks. Use `load_ParametricUMAP(save_location)` to load it again; plain pickle is not sufficient for models that contain Keras networks.
+
## Utility Functions
### umap.nearest_neighbors(X, n_neighbors, metric, metric_kwds={}, angular=False, random_state=None)
@@ -354,7 +380,7 @@ Fit a, b params for the UMAP curve from spread and min_dist.
## AlignedUMAP Class
-`umap.AlignedUMAP(n_neighbors=15, n_components=2, metric='euclidean', alignment_regularisation=1e-2, alignment_window_size=3, **kwargs)`
+`umap.AlignedUMAP(n_neighbors=15, n_components=2, metric='euclidean', metric_kwds=None, n_epochs=None, learning_rate=1.0, init='spectral', alignment_regularisation=0.01, alignment_window_size=3, min_dist=0.1, spread=1.0, low_memory=False, set_op_mix_ratio=1.0, local_connectivity=1.0, repulsion_strength=1.0, negative_sample_rate=5, transform_queue_size=4.0, a=None, b=None, random_state=None, angular_rp_forest=False, target_n_neighbors=-1, target_metric='categorical', target_metric_kwds=None, target_weight=0.5, transform_seed=42, force_approximation_algorithm=False, verbose=False, unique=False)`
UMAP variant for aligning multiple related datasets.
@@ -368,11 +394,15 @@ Number of adjacent datasets to align.
### Methods
-#### fit(X)
+#### fit(X, relations=..., y=None)
Fit model to multiple datasets.
**Parameters:**
- `X`: list of arrays - List of datasets to align
+- `relations`: list of dictionaries - Mappings between sample indices in consecutive datasets; required for meaningful alignment
+
+#### update(X, relations=..., y=None)
+Append a new dataset to an existing aligned model. Use backward-looking relation mappings from the new dataset to the prior window.
**Returns:**
- `self`: Fitted model
@@ -461,7 +491,7 @@ from umap.parametric_umap import ParametricUMAP
# Define custom encoder
encoder = tf.keras.Sequential([
- tf.keras.layers.InputLayer(input_shape=(input_dim,)),
+ tf.keras.layers.InputLayer(shape=(input_dim,)),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(128, activation='relu'),
@@ -471,7 +501,7 @@ encoder = tf.keras.Sequential([
# Define decoder for reconstruction
decoder = tf.keras.Sequential([
- tf.keras.layers.InputLayer(input_shape=(2,)),
+ tf.keras.layers.InputLayer(shape=(2,)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(input_dim)
@@ -484,12 +514,12 @@ embedder = ParametricUMAP(
dims=(input_dim,),
parametric_reconstruction=True,
autoencoder_loss=True,
- n_training_epochs=10,
batch_size=128,
n_neighbors=15,
min_dist=0.1,
random_state=42
)
+embedder.n_training_epochs = 10
embedding = embedder.fit_transform(data)
new_embedding = embedder.transform(new_data)
@@ -510,11 +540,7 @@ reducer = umap.UMAP(
random_state=42
)
-embedding = reducer.fit_transform(data)
-
-# Access density estimates
-original_density = reducer.rad_orig_ # Density in original space
-embedded_density = reducer.rad_emb_ # Density in embedded space
+embedding, original_density, embedded_density = reducer.fit_transform(data)
```
### Aligned UMAP for Time Series
@@ -524,6 +550,11 @@ from umap import AlignedUMAP
# Multiple related datasets (e.g., different time points)
datasets = [day1_data, day2_data, day3_data, day4_data]
+relations = [
+ {day1_idx: day2_idx for day1_idx, day2_idx in matched_day1_to_day2},
+ {day2_idx: day3_idx for day2_idx, day3_idx in matched_day2_to_day3},
+ {day3_idx: day4_idx for day3_idx, day4_idx in matched_day3_to_day4},
+]
# Align embeddings
mapper = AlignedUMAP(
@@ -534,7 +565,7 @@ mapper = AlignedUMAP(
random_state=42
)
-mapper.fit(datasets)
+mapper.fit(datasets, relations=relations)
# Access aligned embeddings
aligned_embeddings = mapper.embeddings_
diff --git a/skills/zarr-python/SKILL.md b/skills/zarr-python/SKILL.md
index 58dbd5fd..b560ce52 100644
--- a/skills/zarr-python/SKILL.md
+++ b/skills/zarr-python/SKILL.md
@@ -3,9 +3,9 @@ name: zarr-python
description: Chunked N-D arrays for cloud storage (Zarr-Python 3). Compressed arrays, parallel I/O, S3/GCS via fsspec, NumPy/Dask/Xarray compatible, for large-scale scientific computing pipelines.
allowed-tools: Read Write Edit Bash
license: MIT license
-compatibility: Requires Python 3.12+ and zarr 3.x. Cloud I/O needs zarr[remote] plus s3fs or gcsfs. Legacy Zarr v2 workflows use zarr==2.* on older Python.
+compatibility: Requires Python 3.12+ and zarr 3.x. Cloud I/O needs zarr[remote] plus pinned s3fs or gcsfs. Legacy Zarr v2 workflows need exact 2.x pins on older Python.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -15,25 +15,23 @@ metadata:
Zarr is a Python library for storing large N-dimensional arrays with chunking and compression. Apply this skill for efficient parallel I/O, cloud-native workflows, and seamless integration with NumPy, Dask, and Xarray.
-**Current upstream:** zarr **3.2.1** (PyPI, May 2026). Docs: [zarr.readthedocs.io](https://zarr.readthedocs.io/en/stable/). New arrays default to **Zarr format 3**; set `zarr_format=2` for legacy interop. This skill is a **community guide** maintained by K-Dense Inc., not an official zarr-developers package.
+**Current upstream:** zarr **3.2.1** (released 2026-05-05). Docs: [zarr.readthedocs.io](https://zarr.readthedocs.io/en/stable/). New arrays default to **Zarr format 3**; set `zarr_format=2` for legacy interop. Zarr 3.2 adds rectilinear chunks and continues to refine the v3 codec pipeline. This skill is a **community guide** maintained by K-Dense Inc., not an official zarr-developers package.
## Quick Start
### Installation
```bash
-uv pip install "zarr>=3.2,<4"
+uv pip install "zarr==3.2.1"
```
-Requires **Python 3.12+** (per PyPI metadata for zarr 3.2.x). For remote stores (S3, GCS, HTTP):
+Requires **Python 3.12+** and NumPy 2.0+ for current stable Zarr-Python. For remote stores (S3, GCS, HTTP), pin the optional extras/backends in your project lockfile:
```bash
-uv pip install "zarr[remote]"
-uv pip install s3fs # AWS S3
-uv pip install gcsfs # Google Cloud Storage
+uv pip install "zarr[remote]==3.2.1" "s3fs==2026.4.0" "gcsfs==2026.5.0"
```
-Pin `zarr>=3,<4` in application dependencies. Use `uv pip install "zarr==2.*"` only when you must stay on Zarr-Python 2 / Python 3.10–3.11.
+Use a version range such as `zarr>=3,<4` only when your project has a committed lockfile and compatibility tests. For Zarr-Python 2 / Python 3.10–3.11 workflows, choose an exact `zarr==2.x.y` patch version from the support-v2 release notes and commit the resulting lockfile.
### Basic Array Creation
@@ -163,13 +161,22 @@ z = zarr.zeros((10000, 10000), chunks=(1000, 1000)) # Square chunks
- Using chunks (1, 200, 200): ~107ms
- Using chunks (200, 200, 1): ~1.65ms (65× faster!)
-### Sharding for Large-Scale Storage
+### Rectilinear Chunks and Sharding
-When arrays have millions of small chunks, use sharding to group chunks into larger storage objects:
+Zarr 3.2 supports **rectilinear chunks** for uneven grids. Pass nested chunk lengths when a dimension has variable tile sizes:
```python
-from zarr.codecs import BloscCodec, BytesCodec, ShardingCodec
+z = zarr.create_array(
+ store="rectilinear.zarr",
+ shape=(60, 100),
+ chunks=([10, 20, 30], [50, 50]),
+ dtype="f4",
+)
+```
+
+When arrays have millions of small chunks, use **sharding** to group chunks into larger storage objects:
+```python
# Create array with sharding
z = zarr.create_array(
store='data.zarr',
@@ -194,18 +201,18 @@ Zarr applies compression per chunk to reduce storage while maintaining fast acce
### Configuring Compression
```python
-from zarr.codecs import BloscCodec, GzipCodec, ZstdCodec, BytesCodec
+from zarr.codecs import BloscCodec, BloscShuffle, GzipCodec
# Default: Blosc with Zstandard
z = zarr.zeros((1000, 1000), chunks=(100, 100)) # Uses default compression
-# Configure Blosc codec
+# Configure Blosc compression
z = zarr.create_array(
store='data.zarr',
shape=(1000, 1000),
chunks=(100, 100),
dtype='f4',
- codecs=[BloscCodec(cname='zstd', clevel=5, shuffle='shuffle')]
+ compressors=BloscCodec(cname='zstd', clevel=5, shuffle=BloscShuffle.bitshuffle)
)
# Available Blosc compressors: 'blosclz', 'lz4', 'lz4hc', 'snappy', 'zlib', 'zstd'
@@ -216,7 +223,7 @@ z = zarr.create_array(
shape=(1000, 1000),
chunks=(100, 100),
dtype='f4',
- codecs=[GzipCodec(level=6)]
+ compressors=GzipCodec(level=6)
)
# Disable compression
@@ -225,7 +232,7 @@ z = zarr.create_array(
shape=(1000, 1000),
chunks=(100, 100),
dtype='f4',
- codecs=[BytesCodec()] # No compression
+ compressors=None
)
```
@@ -239,13 +246,13 @@ z = zarr.create_array(
```python
# Optimal for numeric scientific data
-codecs=[BloscCodec(cname='zstd', clevel=5, shuffle='shuffle')]
+compressors=BloscCodec(cname='zstd', clevel=5, shuffle=BloscShuffle.bitshuffle)
# Optimal for speed
-codecs=[BloscCodec(cname='lz4', clevel=1)]
+compressors=BloscCodec(cname='lz4', clevel=1)
# Optimal for compression ratio
-codecs=[GzipCodec(level=9)]
+compressors=GzipCodec(level=9)
```
## Storage Backends
@@ -303,8 +310,8 @@ Zarr 3 uses **fsspec** backends via URI strings or `FsspecStore` (preferred over
```python
import zarr
-# S3 — credentials from standard AWS env vars (scope reads to these keys only)
-# AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
+# S3 — prefer IAM roles/profiles; fsspec handles provider credential discovery.
+# Never print, log, or copy credential values into prompts or notebooks.
z = zarr.create_array(
store="s3://my-bucket/path/to/array.zarr",
shape=(1000, 1000),
@@ -314,7 +321,7 @@ z = zarr.create_array(
)
z[:] = data
-# GCS — GOOGLE_APPLICATION_CREDENTIALS or gcloud default credentials
+# GCS — prefer workload identity or gcloud application-default credentials.
z = zarr.open_array(
"gs://my-bucket/path/to/array.zarr",
mode="r",
@@ -327,7 +334,7 @@ store = FsspecStore.from_url("s3://my-bucket/data.zarr", storage_options={"anon"
root = zarr.open_group(store=store, mode="r+")
```
-Cloud backends read credentials from provider environment variables locally via fsspec; they are not sent to third-party endpoints outside your configured bucket/project.
+Cloud backends read credentials through the provider SDK/fsspec backend. Do not inspect broad `.env` files; if a user explicitly needs help debugging auth, ask for redacted configuration and read only the named provider variables they approve. Treat all `import zarr`, `import dask`, `import h5py`, and `import xarray` examples as third-party package imports, not bundled script files.
**Cloud Storage Best Practices**:
- Use consolidated metadata to reduce latency: `zarr.consolidate_metadata(store)`
@@ -510,13 +517,26 @@ ds.to_zarr('climate_data.zarr')
## Parallel Computing and Thread Safety
-The `synchronizer` argument (`ThreadSynchronizer`, `ProcessSynchronizer`) is **not ported to Zarr-Python 3** yet. Use these patterns instead:
+Zarr uses async I/O internally. Tune concurrency for remote storage or Dask-heavy workloads:
+
+```python
+import zarr
+
+# Higher values can improve remote throughput; lower values reduce pressure
+# when Dask already supplies many worker threads.
+zarr.config.set({
+ "async.concurrency": 8,
+ "threading.max_workers": 8,
+})
+```
+
+The old `synchronizer` argument (`ThreadSynchronizer`, `ProcessSynchronizer`) is **not available in Zarr-Python 3**. Use these patterns instead:
- **Reads:** always safe across threads/processes.
- **Writes:** safe when each worker writes to **non-overlapping chunks**; most stores support atomic chunk writes.
- **Overlapping writes:** coordinate externally (file locks, workflow design) until synchronizers return.
-For Dask-heavy workloads, tune Zarr async concurrency — see [Optimizing performance](https://zarr.readthedocs.io/en/stable/user-guide/performance/).
+For Dask-heavy workloads, estimate total concurrent I/O as roughly `dask_threads × async.concurrency` and lower Zarr's concurrency settings if the store or memory becomes saturated.
## Consolidated Metadata
@@ -598,7 +618,7 @@ print(z.info)
# Output includes:
# - Type, shape, chunks, dtype
-# - Compression codec and level
+# - Serializer and compressors
# - Storage size (compressed vs uncompressed)
# - Storage location
diff --git a/skills/zarr-python/references/api_reference.md b/skills/zarr-python/references/api_reference.md
index 0abbe4f1..607c3eda 100644
--- a/skills/zarr-python/references/api_reference.md
+++ b/skills/zarr-python/references/api_reference.md
@@ -17,6 +17,8 @@ zarr.create_array(store, *, shape, chunks, dtype='f8', compressors='default',
overwrite=False)
```
+`chunks` may be a regular tuple (for example `(100, 100)`) or, in Zarr 3.2+, a rectilinear nested sequence (for example `([10, 20, 30], [50, 50])`).
+
### `zarr.array()`
```python
zarr.array(data, *, chunks=None, dtype=None, store=None, compressors='default')
@@ -46,7 +48,7 @@ store = MemoryStore()
# ZIP archive
store = ZipStore('data.zip', mode='w') # close when done writing
-# Cloud via fsspec URI (install zarr[remote] + s3fs/gcsfs)
+# Cloud via fsspec URI (install pinned zarr[remote] + pinned backend)
store = FsspecStore.from_url('s3://bucket/path.zarr', storage_options={'anon': False})
group = zarr.open_group(store=store, mode='r')
@@ -59,16 +61,16 @@ zarr.open_group('s3://bucket/data.zarr', mode='r', storage_options={'anon': True
## Compression (zarr.codecs)
```python
-from zarr.codecs import BloscCodec, GzipCodec, ZstdCodec, BytesCodec
+from zarr.codecs import BloscCodec, BloscShuffle, GzipCodec, ZstdCodec
# Default Blosc (zstd) is applied when compressors='default'
-codec = BloscCodec(cname='zstd', clevel=5, shuffle='shuffle')
+codec = BloscCodec(cname='zstd', clevel=5, shuffle=BloscShuffle.bitshuffle)
z = zarr.create_array('data.zarr', shape=(1000, 1000), chunks=(100, 100),
dtype='f4', compressors=codec)
# No compression
z = zarr.create_array('data.zarr', shape=(1000, 1000), chunks=(100, 100),
- dtype='f4', compressors=BytesCodec())
+ dtype='f4', compressors=None)
```
For **Zarr format 2** arrays, import codecs from `numcodecs` instead of `zarr.codecs`.
@@ -139,6 +141,7 @@ ds.to_zarr('output.zarr')
- Reads: safe without coordination.
- Writes: safe across workers when chunks do not overlap.
- `synchronizer=` / `ThreadSynchronizer` / `ProcessSynchronizer`: **not available in v3** (see migration reference).
+- Tune Zarr's internal concurrency with `zarr.config.set({"async.concurrency": 8, "threading.max_workers": 8})`, especially when combining Zarr with Dask.
## Format versions
diff --git a/skills/zarr-python/references/v3_migration.md b/skills/zarr-python/references/v3_migration.md
index 5aabc57b..e4107609 100644
--- a/skills/zarr-python/references/v3_migration.md
+++ b/skills/zarr-python/references/v3_migration.md
@@ -1,6 +1,6 @@
# Zarr-Python 3 Migration Quick Reference
-Targets **zarr 3.2.x** (PyPI stable, May 2026). Official guide: [3.0 Migration Guide](https://zarr.readthedocs.io/en/stable/user-guide/v3_migration/).
+Targets **zarr 3.2.x** (current stable: **3.2.1**, released 2026-05-05). Official guide: [3.0 Migration Guide](https://zarr.readthedocs.io/en/stable/user-guide/v3_migration/).
## Version and format defaults
@@ -41,7 +41,7 @@ import zarr
root = zarr.open_group(
store="s3://my-bucket/path/data.zarr",
mode="r",
- storage_options={"anon": False}, # uses AWS_* env vars via fsspec
+ storage_options={"anon": False}, # provider credentials are handled by fsspec
)
# Explicit FsspecStore
@@ -50,20 +50,21 @@ store = FsspecStore.from_url("s3://my-bucket/path/data.zarr", storage_options={"
root = zarr.open_group(store=store, mode="r")
```
-Install remote I/O extras: `uv pip install "zarr[remote]"` (pulls fsspec). Add `s3fs` or `gcsfs` for the target protocol.
+Install remote I/O extras with pinned versions in production projects, for example: `uv pip install "zarr[remote]==3.2.1" "s3fs==2026.4.0" "gcsfs==2026.5.0"`. Zarr's `remote` extra pulls fsspec; add the protocol backend needed by the target store.
## Codecs and compression
-- Zarr v3 arrays: use `zarr.codecs.*` (e.g. `BloscCodec`, `GzipCodec`, `BytesCodec`) via `compressors=` on `create_array`.
+- Zarr v3 arrays: use `zarr.codecs.*` (e.g. `BloscCodec`, `GzipCodec`) via `compressors=` on `create_array`.
- Zarr v2 arrays: `numcodecs` codecs still work; import from `numcodecs`, not `zarr.*`.
- `compressor=` kwarg on creation functions → use `compressors=` in v3.
+- Disable compression with `compressors=None`; `BytesCodec` is the serializer, not the "no compression" setting.
```python
-from zarr.codecs import BloscCodec
+from zarr.codecs import BloscCodec, BloscShuffle
z = zarr.create_array(
store="data.zarr", shape=(1000, 1000), chunks=(100, 100), dtype="f4",
- compressors=BloscCodec(cname="zstd", clevel=5, shuffle="shuffle"),
+ compressors=BloscCodec(cname="zstd", clevel=5, shuffle=BloscShuffle.bitshuffle),
)
```
@@ -74,6 +75,7 @@ z = zarr.create_array(
| `group.create_dataset(...)` | `group.create_array(...)` |
| `group.require_dataset(...)` | `group.require_array(...)` |
| `group.foo` attribute access | `group["foo"]` only |
+| `zarr.storage.init_group(...)` | `zarr.open_group(...)` or `zarr.create_group(...)` |
## Array operations
@@ -84,6 +86,34 @@ z.resize((15000, 15000)) # not z.resize(15000, 15000)
Advanced indexing: `vindex`, `oindex`, and `blocks` remain as convenience properties; equivalent methods are `get_coordinate_selection`, `get_orthogonal_selection`, etc.
+### Rectilinear chunks (3.2+)
+
+Zarr 3.2 adds support for rectilinear chunk grids. Existing regular chunk tuples still work, but you can now pass nested chunk lengths when chunk boundaries vary by dimension:
+
+```python
+z = zarr.create_array(
+ store="rectilinear.zarr",
+ shape=(60, 100),
+ chunks=([10, 20, 30], [50, 50]),
+ dtype="f4",
+)
+```
+
+### Metadata migration CLI (3.1.3+)
+
+For v2 stores that need v3 metadata, use the Zarr CLI non-destructively first:
+
+```bash
+zarr migrate v3 path/to/input.zarr path/to/output.zarr
+zarr migrate v3 path/to/input.zarr --dry-run
+```
+
+Only remove v2 metadata after downstream readers have been tested:
+
+```bash
+zarr remove-metadata v2 path/to/input.zarr
+```
+
## Not yet ported to v3 (avoid or expect errors)
From the [migration guide WIP list](https://zarr.readthedocs.io/en/stable/user-guide/v3_migration/#work-in-progress):
@@ -94,4 +124,4 @@ From the [migration guide WIP list](https://zarr.readthedocs.io/en/stable/user-g
## Zarr-Python 2 support
-Install last 2.x: `uv pip install "zarr==2.*"`. Maintenance lives on the `support/v2` branch (security fixes for ~6 months after 3.0).
+For legacy workflows, choose an exact `zarr==2.x.y` release from the support-v2 release notes and commit a lockfile. Maintenance lives on the `support/v2` branch (security fixes for ~6 months after 3.0).