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.

docs: update dependencies and skills documentation for dask, pymoo, and scanpy

Timothy Kassisaba68b8165e6
diff --git a/docs/skills.md b/docs/skills.md
index 274b0af6..3f618126 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -50,7 +50,7 @@
- **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
- **pysam** - Read, write, and manipulate genomic data files (SAM/BAM/CRAM alignments, VCF/BCF variants, FASTA/FASTQ sequences) with pileup analysis, coverage calculations, and bioinformatics workflows
- **PyDESeq2** - Python implementation of the DESeq2 differential gene expression analysis method for bulk RNA-seq data. Provides statistical methods for determining differential expression between experimental conditions using negative binomial generalized linear models. Key features include: size factor estimation for library size normalization, dispersion estimation and shrinkage, hypothesis testing with Wald test or likelihood ratio test, multiple testing correction (Benjamini-Hochberg FDR), results filtering and ranking, and integration with pandas DataFrames. Handles complex experimental designs, batch effects, and replicates. Produces fold-change estimates, p-values, and adjusted p-values for each gene. Use cases: identifying differentially expressed genes between conditions, RNA-seq experiment analysis, biomarker discovery, and gene expression studies requiring rigorous statistical analysis
-- **Scanpy** - Comprehensive Python toolkit for single-cell RNA-seq data analysis built on AnnData. Provides end-to-end workflows for preprocessing (quality control, normalization, log transformation), dimensionality reduction (PCA, UMAP, t-SNE, ForceAtlas2), clustering (Leiden, Louvain, hierarchical clustering), marker gene identification, trajectory inference (PAGA, diffusion maps), and visualization. Key features include: efficient handling of large datasets (millions of cells) using sparse matrices, integration with scvi-tools for advanced analysis, support for multi-modal data (RNA+ATAC, CITE-seq), batch correction methods, and publication-quality plotting functions. Includes extensive documentation, tutorials, and integration with other single-cell tools. Supports GPU acceleration for certain operations. Use cases: single-cell RNA-seq analysis, cell-type identification, trajectory analysis, batch correction, and comprehensive single-cell genomics workflows
+- **Scanpy** - Comprehensive Python toolkit for single-cell RNA-seq data analysis built on AnnData (scanpy 1.12.x; Python 3.12+). Provides end-to-end workflows for preprocessing (quality control, scrublet doublet detection, normalization, log transformation), dimensionality reduction (PCA, UMAP, t-SNE), Leiden clustering, marker gene identification, pseudobulk aggregation via `get.aggregate()`, trajectory inference (PAGA, diffusion maps), and visualization. Key features include: efficient handling of large datasets using sparse matrices and experimental Dask out-of-core support, integration with scvi-tools for advanced analysis, batch correction methods (ComBat), and publication-quality plotting. Optional GPU acceleration via rapids-singlecell. Use cases: single-cell RNA-seq analysis, cell-type identification, exploratory cluster markers, pseudobulk DE workflows (with pydeseq2), trajectory analysis, and comprehensive single-cell genomics workflows
- **scVelo** - RNA velocity analysis for estimating cell state transitions from unspliced/spliced mRNA dynamics. Infers trajectory directions, computes latent time, and identifies driver genes in single-cell RNA-seq data. Complements Scanpy/scVI-tools for trajectory inference, enabling the study of cellular differentiation dynamics and lineage decisions at single-cell resolution
- **scvi-tools** - Probabilistic deep learning models for single-cell omics analysis. PyTorch-based framework providing variational autoencoders (VAEs) for dimensionality reduction, batch correction, differential expression, and data integration across modalities. Includes 25+ models: scVI/scANVI (RNA-seq integration and cell type annotation), totalVI (CITE-seq protein+RNA), MultiVI (multiome RNA+ATAC integration), PeakVI (ATAC-seq analysis), DestVI/Stereoscope/Tangram (spatial transcriptomics deconvolution), MethylVI (methylation), CytoVI (flow/mass cytometry), VeloVI (RNA velocity), contrastiveVI (perturbation studies), and Solo (doublet detection). Supports seamless integration with Scanpy/AnnData ecosystem, GPU acceleration, reference mapping (scArches), and probabilistic differential expression with uncertainty quantification
- **scikit-bio** - Python library for bioinformatics providing data structures, algorithms, and parsers for biological sequence analysis. Built on NumPy, SciPy, and pandas. Key features include: sequence objects (DNA, RNA, protein sequences) with biological alphabet validation, sequence alignment algorithms (local, global, semiglobal), phylogenetic tree manipulation, diversity metrics (alpha diversity, beta diversity, phylogenetic diversity), distance metrics for sequences and communities, file format parsers (FASTA, FASTQ, QIIME formats, Newick), and statistical analysis tools. Provides scikit-learn compatible transformers for machine learning workflows. Supports efficient processing of large sequence datasets. Use cases: sequence analysis, microbial ecology (16S rRNA analysis), metagenomics, phylogenetic analysis, and bioinformatics research requiring sequence manipulation and diversity calculations
@@ -133,7 +133,7 @@
- **SymPy** - Symbolic mathematics in Python for exact computation using mathematical symbols rather than numerical approximations. Provides comprehensive support for symbolic algebra (simplification, expansion, factorization), calculus (derivatives, integrals, limits, series), equation solving (algebraic, differential, systems of equations), matrices and linear algebra (eigenvalues, decompositions, solving linear systems), physics (classical mechanics with Lagrangian/Hamiltonian formulations, quantum mechanics, vector analysis, units), number theory (primes, factorization, modular arithmetic, Diophantine equations), geometry (2D/3D analytic geometry), combinatorics (permutations, combinations, partitions, group theory), logic and sets, statistics (probability distributions, random variables), special functions (gamma, Bessel, orthogonal polynomials), and code generation (lambdify to NumPy/SciPy functions, C/Fortran code generation, LaTeX output for documentation). Emphasizes exact arithmetic using rational numbers and symbolic representations, supports assumptions for improved simplification (positive, real, integer), integrates seamlessly with NumPy/SciPy through lambdify for fast numerical evaluation, and enables symbolic-to-numeric pipelines for scientific computing workflows
### Data Analysis & Visualization
-- **Dask** - Parallel computing for larger-than-memory datasets with distributed DataFrames, Arrays, Bags, and Futures
+- **Dask** - Parallel and distributed computing for larger-than-RAM pandas/NumPy workflows (dask 2026.x; Python 3.10+). Provides lazy DataFrames (expression-based query planning since 2025.1), Arrays, Bags, delayed tasks, and Futures via dask.distributed. Scales from multi-core laptops to clusters with a diagnostic dashboard. PyArrow 16+ required for DataFrame I/O; cloud paths need s3fs/gcsfs. Use for parallel file processing, out-of-core ETL, and scaling existing pandas/NumPy code. For single-machine out-of-core analytics without a cluster, consider vaex; for in-memory speed use polars
- **GeoMaster** - Comprehensive geospatial science skill covering remote sensing, GIS, spatial analysis, machine learning for earth observation, and 30+ scientific domains. Supports satellite imagery processing (Sentinel, Landsat, MODIS, SAR, hyperspectral), vector and raster data operations, spatial statistics, point cloud processing, network analysis, cloud-native workflows (STAC, COG, Planetary Computer), and 8 programming languages (Python, R, Julia, JavaScript, C++, Java, Go, Rust) with 500+ code examples. Use for remote sensing workflows, GIS analysis, spatial ML, Earth observation data processing, terrain analysis, hydrological modeling, marine spatial analysis, atmospheric science, and any geospatial computation task
- **GeoPandas** - Python library extending pandas for working with geospatial vector data including shapefiles, GeoJSON, and GeoPackage files. Provides GeoDataFrame and GeoSeries data structures combining geometric data with tabular attributes for spatial analysis. Key features include: reading/writing spatial file formats (Shapefile, GeoJSON, GeoPackage, PostGIS, Parquet) with Arrow acceleration for 2-4x faster I/O, geometric operations (buffer, simplify, centroid, convex hull, affine transformations) through Shapely integration, spatial analysis (spatial joins with predicates like intersects/contains/within, nearest neighbor joins, overlay operations for union/intersection/difference, dissolve for aggregation, clipping), coordinate reference system (CRS) management (setting CRS, reprojecting between coordinate systems, UTM estimation), and visualization (static choropleth maps with matplotlib, interactive maps with folium, multi-layer mapping, classification schemes with mapclassify). Supports spatial indexing for performance, filtering during read operations (bbox, mask, SQL WHERE), and integration with cartopy for cartographic projections. Use cases: spatial data manipulation, buffer analysis, spatial joins between datasets, dissolving boundaries, calculating areas/distances in projected CRS, reprojecting coordinate systems, creating choropleth maps, converting between spatial file formats, PostGIS database integration, and geospatial data analysis workflows
- **Matplotlib** - Comprehensive Python plotting library for creating publication-quality static, animated, and interactive visualizations. Provides extensive customization options for creating figures, subplots, axes, and annotations. Key features include: support for multiple plot types (line, scatter, bar, histogram, contour, 3D, and many more), extensive customization (colors, fonts, styles, layouts), multiple backends (PNG, PDF, SVG, interactive backends), LaTeX integration for mathematical notation, and integration with NumPy and pandas. Includes specialized modules (pyplot for MATLAB-like interface, artist layer for fine-grained control, backend layer for rendering). Supports complex multi-panel figures, color maps, legends, and annotations. Use cases: scientific figure creation, data visualization, exploratory data analysis, publication graphics, and any application requiring high-quality plots
diff --git a/pyproject.toml b/pyproject.toml
index 571e69a1..1e5edf4e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,3 +9,8 @@ dependencies = [
"firecrawl-py>=4.9.0",
"python-dotenv>=1.0.0",
]
+
+[dependency-groups]
+dev = [
+ "skills-ref @ git+https://github.com/agentskills/agentskills.git#subdirectory=skills-ref",
+]
diff --git a/skills/dask/SKILL.md b/skills/dask/SKILL.md
index 1c3ef044..5f6756f4 100644
--- a/skills/dask/SKILL.md
+++ b/skills/dask/SKILL.md
@@ -1,9 +1,11 @@
---
name: dask
description: Distributed computing for larger-than-RAM pandas/NumPy workflows. Use when you need to scale existing pandas/NumPy code beyond memory or across clusters. Best for parallel file processing, distributed ML, integration with existing pandas code. For out-of-core analytics on single machine use vaex; for in-memory speed use polars.
+allowed-tools: Read Write Edit Bash
license: BSD-3-Clause license
+compatibility: Requires Python 3.10+ and dask 2025.1+. DataFrame workflows need pandas 2+ and PyArrow 16+. Cloud paths (s3://, gcs://) need s3fs or gcsfs. Cluster deployment uses dask.distributed (included with dask[complete]).
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -18,6 +20,31 @@ Dask is a Python library for parallel and distributed computing that enables thr
Dask scales from laptops (processing ~100 GiB) to clusters (processing ~100 TiB) while maintaining familiar Python APIs.
+**Current upstream:** dask **2026.3.0** (PyPI, March 2026). Docs: [docs.dask.org](https://docs.dask.org/en/stable/). Since **2025.1.0**, the expression-based DataFrame API with query planning is the only implementation — do not install `dask-expr` separately or set `dataframe.query-planning: False`.
+
+## Quick Start
+
+### Installation
+
+```bash
+uv pip install "dask>=2025.1"
+```
+
+For a typical pandas/NumPy workflow with the distributed scheduler and dashboard:
+
+```bash
+uv pip install "dask[complete]"
+```
+
+Remote object storage (S3, GCS, Azure):
+
+```bash
+uv pip install s3fs # s3:// paths
+uv pip install gcsfs # gs:// paths
+```
+
+Requires **Python 3.10+** (3.9 support dropped in 2024.12). DataFrame I/O requires **PyArrow 16+** (as of dask 2026.1.2).
+
## When to Use This Skill
This skill should be used when:
@@ -329,8 +356,8 @@ x = da.from_zarr('large_dataset.zarr')
# Process in chunks
normalized = (x - x.mean()) / x.std()
-# Save result
-da.to_zarr(normalized, 'normalized.zarr')
+# Save result (use mode= for overwrite; zarr_array_kwargs for compression)
+da.to_zarr(normalized, 'normalized.zarr', mode='w')
```
### Custom Parallel Workflow
diff --git a/skills/dask/references/arrays.md b/skills/dask/references/arrays.md
index 1737e109..37aba34c 100644
--- a/skills/dask/references/arrays.md
+++ b/skills/dask/references/arrays.md
@@ -332,16 +332,14 @@ numpy_array = dask_array.compute()
### To Disk
```python
+# Save to Zarr (dask 2026.1+: use mode= and zarr_array_kwargs= for zarr-python 3)
+da.to_zarr(x, 'output.zarr', mode='w')
+
# Save to HDF5
import h5py
with h5py.File('output.hdf5', mode='w') as f:
dset = f.create_dataset('/data', shape=x.shape, dtype=x.dtype)
da.store(x, dset)
-
-# Save to Zarr
-import zarr
-z = zarr.open('output.zarr', mode='w', shape=x.shape, dtype=x.dtype, chunks=x.chunks)
-da.store(x, z)
```
## Performance Considerations
diff --git a/skills/dask/references/dataframes.md b/skills/dask/references/dataframes.md
index 64e91603..26e3d752 100644
--- a/skills/dask/references/dataframes.md
+++ b/skills/dask/references/dataframes.md
@@ -4,6 +4,8 @@
Dask DataFrames enable parallel processing of large tabular data by distributing work across multiple pandas DataFrames. As described in the documentation, "Dask DataFrames are a collection of many pandas DataFrames" with identical APIs, making the transition from pandas straightforward.
+Since **dask 2025.1.0**, the expression-based implementation with logical query planning is the only DataFrame backend. Import from `dask.dataframe` only — avoid legacy submodule paths. DataFrame I/O requires **PyArrow 16+** (dask 2026.1.2+).
+
## Core Concept
A Dask DataFrame is divided into multiple pandas DataFrames (partitions) along the index:
@@ -54,10 +56,10 @@ ddf = dd.read_parquet('data.parquet')
```python
# Read multiple files using glob patterns
ddf = dd.read_csv('data/*.csv')
-ddf = dd.read_parquet('s3://mybucket/data/*.parquet')
-
-# Read with path structure
ddf = dd.read_parquet('data/year=*/month=*/day=*.parquet')
+
+# Remote Parquet (requires s3fs: uv pip install s3fs)
+ddf = dd.read_parquet('s3://mybucket/data/*.parquet', storage_options={'anon': False})
```
### Optimizations
@@ -304,8 +306,8 @@ ddf = dd.read_parquet('timeseries/*.parquet')
# Set timestamp index
ddf = ddf.set_index('timestamp', sorted=True)
-# Resample (if available in Dask version)
-hourly = ddf.resample('1H').mean()
+# Resample time series (requires sorted datetime index)
+hourly = ddf.resample('1h').mean()
# Compute statistics
result = hourly.compute()
diff --git a/skills/dask/references/schedulers.md b/skills/dask/references/schedulers.md
index 01763b87..e503791f 100644
--- a/skills/dask/references/schedulers.md
+++ b/skills/dask/references/schedulers.md
@@ -339,16 +339,29 @@ client = Client(
- Use more workers with fewer threads
- Example: 8 cores → 8 workers with 1 thread each
-### Environment Variables
+### Configuration via dask.config
-```bash
-# Set thread count via environment
-export DASK_NUM_WORKERS=4
-export DASK_THREADS_PER_WORKER=2
+Prefer `dask.config` over shell environment variables so worker settings stay explicit in code:
-# Or via config file
+```python
+import dask
+
+dask.config.set({
+ "distributed.worker.memory.target": 0.60,
+ "distributed.worker.memory.spill": 0.70,
+})
+```
+
+When creating a `Client`, pass resource limits directly:
+
+```python
+from dask.distributed import Client
+
+client = Client(n_workers=4, threads_per_worker=2, memory_limit='4GB')
```
+Upstream also supports `DASK_*` environment variables (for example `DASK_SCHEDULER_ADDRESS` when connecting to an existing cluster). Set only the specific variables documented for your deployment — do not copy entire `.env` files into the environment.
+
## Common Patterns
### Development to Production
diff --git a/skills/pymoo/SKILL.md b/skills/pymoo/SKILL.md
index 159a2c41..d66a6f28 100644
--- a/skills/pymoo/SKILL.md
+++ b/skills/pymoo/SKILL.md
@@ -2,8 +2,10 @@
name: pymoo
description: Multi-objective optimization framework. NSGA-II, NSGA-III, MOEA/D, Pareto fronts, constraint handling, benchmarks (ZDT, DTLZ), for engineering design and optimization problems.
license: Apache-2.0 license
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.10+ and pymoo (uv pip install). Optional matplotlib for visualization plots; optional autograd for gradient-based features; optional joblib for JoblibParallelization.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +13,19 @@ metadata:
## Overview
-Pymoo is a comprehensive Python framework for optimization with emphasis on multi-objective problems. Solve single and multi-objective optimization using state-of-the-art algorithms (NSGA-II/III, MOEA/D), benchmark problems (ZDT, DTLZ), customizable genetic operators, and multi-criteria decision making methods. Excels at finding trade-off solutions (Pareto fronts) for problems with conflicting objectives.
+Pymoo is a comprehensive Python framework for optimization with emphasis on multi-objective problems. Solve single and multi-objective optimization using state-of-the-art algorithms (NSGA-II/III, MOEA/D, SPEA2), benchmark problems (ZDT, DTLZ), customizable genetic operators, and multi-criteria decision making methods. Excels at finding trade-off solutions (Pareto fronts) for problems with conflicting objectives. Current stable release: **pymoo 0.6.1.6** (November 2025).
+
+## Installation
+
+```bash
+uv pip install pymoo
+```
+
+For reproducible environments, pin a version: `uv pip install "pymoo==0.6.1.6"`.
+
+**Dependencies:** NumPy (2.x compatible since 0.6.1.3), SciPy, matplotlib (visualization). Autograd is optional for gradient-based features (since 0.6.1.3).
+
+**Documentation:** https://pymoo.org/ — LLM-friendly index: https://pymoo.org/llms.txt
## When to Use This Skill
@@ -50,12 +64,21 @@ result = minimize(
- `result.G`: Constraint violations (if constrained)
- `result.algorithm`: Algorithm object with history
+### Problem Definition Styles
+
+Pymoo supports three problem definition styles:
+
+- **`Problem`**: Vectorized — `_evaluate` receives a batch of solutions (matrix)
+- **`ElementwiseProblem`**: One solution per call — recommended for custom problems and parallel evaluation
+- **`FunctionalProblem`**: Define objectives and constraints as separate functions without subclassing
+
### Problem Types
**Single-objective:** One objective to minimize/maximize
**Multi-objective:** 2-3 conflicting objectives → Pareto front
**Many-objective:** 4+ objectives → High-dimensional Pareto front
**Constrained:** Objectives + inequality/equality constraints
+**Mixed-variable:** Continuous, integer, binary, and categorical variables in one problem
**Dynamic:** Time-varying objectives or constraints
## Quick Start Workflows
@@ -168,7 +191,7 @@ from pymoo.visualization.pcp import PCP
problem = get_problem("dtlz2", n_obj=5)
# Generate reference directions (required for NSGA-III)
-ref_dirs = get_reference_directions("das-dennis", n_dim=5, n_partitions=12)
+ref_dirs = get_reference_directions("das-dennis", n_obj=5, n_partitions=12)
# Configure NSGA-III
algorithm = NSGA3(ref_dirs=ref_dirs)
@@ -383,6 +406,80 @@ plot.show()
**See:** `references/visualization.md` for all visualization types and usage
+### Workflow 8: Parallel Evaluation
+
+**When:** Each `_evaluate` call is expensive (simulations, ML models, external solvers)
+
+**Approach:** Pass an `elementwise_runner` to `ElementwiseProblem` using `StarmapParallelization` or `JoblibParallelization`.
+
+**Example (thread pool):**
+```python
+from multiprocessing.pool import ThreadPool
+from pymoo.algorithms.soo.nonconvex.ga import GA
+from pymoo.core.problem import ElementwiseProblem
+from pymoo.optimize import minimize
+from pymoo.parallelization.starmap import StarmapParallelization
+
+class MyProblem(ElementwiseProblem):
+ def __init__(self, elementwise_runner=None, **kwargs):
+ super().__init__(
+ n_var=10, n_obj=1, xl=-5, xu=5,
+ elementwise_runner=elementwise_runner, **kwargs,
+ )
+
+ def _evaluate(self, x, out, *args, **kwargs):
+ out["F"] = (x ** 2).sum() # Replace with expensive evaluation
+
+pool = ThreadPool(4)
+runner = StarmapParallelization(pool.starmap)
+problem = MyProblem(elementwise_runner=runner)
+
+result = minimize(problem, GA(), ("n_gen", 50), seed=1)
+pool.close()
+```
+
+**See:** `references/parallelization.md` for process pools, joblib, and pickling notes
+
+### Workflow 9: Mixed-Variable Optimization
+
+**When:** Decision variables include continuous, integer, binary, and/or categorical types
+
+**Approach:** Define a `vars` dict with typed variables; use `MixedVariableGA` (SOO) or add MOO survival.
+
+**Example:**
+```python
+from pymoo.core.problem import ElementwiseProblem
+from pymoo.core.variable import Real, Integer, Choice, Binary
+from pymoo.core.mixed import MixedVariableGA
+from pymoo.optimize import minimize
+
+class MixedProblem(ElementwiseProblem):
+ def __init__(self, **kwargs):
+ vars = {
+ "b": Binary(),
+ "x": Choice(options=["nothing", "multiply"]),
+ "y": Integer(bounds=(0, 2)),
+ "z": Real(bounds=(0, 5)),
+ }
+ super().__init__(vars=vars, n_obj=1, **kwargs)
+
+ def _evaluate(self, X, out, *args, **kwargs):
+ b, x, z, y = X["b"], X["x"], X["z"], X["y"]
+ f = z + y
+ if b:
+ f = 100 * f
+ if x == "multiply":
+ f = 10 * f
+ out["F"] = f
+
+algorithm = MixedVariableGA(pop_size=20)
+result = minimize(MixedProblem(), algorithm, ("n_evals", 1000), seed=1)
+```
+
+For multi-objective mixed-variable problems, use `MixedVariableGA(pop_size=20, survival=RankAndCrowdingSurvival())`. For single-objective mixed search, pymoo also wraps [Optuna](https://optuna.org) via `pymoo.algorithms.soo.nonconvex.optuna.Optuna`.
+
+**See:** `references/algorithms.md` for MixedVariableGA and Optuna details
+
## Algorithm Selection Guide
### Single-Objective Problems
@@ -399,6 +496,7 @@ plot.show()
| Algorithm | Best For | Key Features |
|-----------|----------|--------------|
| **NSGA-II** | Standard benchmark | Fast, reliable, well-tested |
+| **SPEA2** | Archive-based MOO | Strength-based fitness, external archive |
| **R-NSGA-II** | Preference regions | Reference point guidance |
| **MOEA/D** | Decomposable problems | Scalarization approach |
@@ -500,7 +598,7 @@ algorithm = GA(
- Reduce population size
- Decrease number of generations
- Use simpler operators
-- Enable parallelization (if problem supports)
+- Enable parallel evaluation via `elementwise_runner` (see Workflow 8)
### Best practices:
@@ -524,6 +622,7 @@ Detailed documentation for in-depth understanding:
- **operators.md**: Genetic operators (sampling, selection, crossover, mutation) with configuration
- **visualization.md**: All visualization types with examples and selection guide
- **constraints_mcdm.md**: Constraint handling techniques and multi-criteria decision making methods
+- **parallelization.md**: Parallel evaluation with StarmapParallelization and JoblibParallelization
**Search patterns for references:**
- Algorithm details: `grep -r "NSGA-II\|NSGA-III\|MOEA/D" references/`
@@ -550,19 +649,9 @@ python3 scripts/decision_making_example.py
## Additional Notes
-**Installation:**
-```bash
-uv pip install pymoo
-```
-
-**Dependencies:** NumPy, SciPy, matplotlib, autograd (optional for gradient-based)
-
-**Documentation:** https://pymoo.org/
-
-**Version:** This skill is based on pymoo 0.6.x
-
**Common patterns:**
-- Always use `ElementwiseProblem` for custom problems
+- Use `ElementwiseProblem` for custom problems (or `FunctionalProblem` for function-based definitions)
+- Use `vars` dict with typed variables for mixed-variable problems
- Constraints formulated as `g(x) <= 0` and `h(x) = 0`
- Reference directions required for NSGA-III
- Normalize objectives before MCDM
diff --git a/skills/pymoo/references/algorithms.md b/skills/pymoo/references/algorithms.md
index ca888c3d..ccf50069 100644
--- a/skills/pymoo/references/algorithms.md
+++ b/skills/pymoo/references/algorithms.md
@@ -47,6 +47,37 @@ algorithm = GA(pop_size=100, eliminate_duplicates=True)
**Purpose:** Simplex-based optimization
**Best for:** Local optimization of continuous functions
+### MixedVariableGA
+**Purpose:** Single-objective optimization with mixed variable types
+**Best for:** Problems with continuous, integer, binary, and categorical variables
+
+**Usage:**
+```python
+from pymoo.core.mixed import MixedVariableGA
+from pymoo.core.variable import Real, Integer, Choice, Binary
+
+# Define problem with vars dict (see mixed-variable docs)
+algorithm = MixedVariableGA(pop_size=20)
+```
+
+For multi-objective mixed-variable problems, pass a survival operator:
+```python
+from pymoo.algorithms.moo.nsga2 import RankAndCrowdingSurvival
+algorithm = MixedVariableGA(pop_size=20, survival=RankAndCrowdingSurvival())
+```
+
+### Optuna (Mixed-Variable SOO)
+**Purpose:** Single-objective mixed-variable search via Optuna wrapper
+**Best for:** Hyperparameter-style mixed search when Optuna's TPE/samplers are preferred
+
+**Usage:**
+```python
+from pymoo.algorithms.soo.nonconvex.optuna import Optuna
+algorithm = Optuna()
+```
+
+Requires Optuna installed separately: `uv pip install optuna`
+
## Multi-Objective Optimization Algorithms
### NSGA-II (Non-dominated Sorting Genetic Algorithm II)
@@ -78,6 +109,27 @@ algorithm = NSGA2(pop_size=100)
- Need for distributed solutions across Pareto front
- Standard multi-objective benchmark
+### SPEA2 (Strength Pareto Evolutionary Algorithm 2)
+**Purpose:** Multi-objective optimization with external archive
+**Best for:** Bi- and tri-objective problems; alternative to NSGA-II when archive-based selection is preferred
+**Selection strategy:** Strength-based fitness + k-nearest-neighbor density estimation
+
+**Key features:**
+- External archive of non-dominated solutions
+- Strength value measures how many solutions a point dominates
+- Improved in pymoo 0.6.1.6
+
+**Usage:**
+```python
+from pymoo.algorithms.moo.spea2 import SPEA2
+algorithm = SPEA2(pop_size=100)
+```
+
+**When to use:**
+- 2-3 objectives
+- Prefer archive-based selection over crowding distance
+- Compare against NSGA-II on benchmark problems
+
### NSGA-III
**Purpose:** Many-objective optimization (4+ objectives)
**Best for:** Problems with 4 or more objectives requiring uniform Pareto front coverage
@@ -100,7 +152,7 @@ algorithm = NSGA2(pop_size=100)
from pymoo.algorithms.moo.nsga3 import NSGA3
from pymoo.util.ref_dirs import get_reference_directions
-ref_dirs = get_reference_directions("das-dennis", n_dim=4, n_partitions=12)
+ref_dirs = get_reference_directions("das-dennis", n_obj=4, n_partitions=12)
algorithm = NSGA3(ref_dirs=ref_dirs)
```
@@ -164,7 +216,7 @@ algorithm = NSGA3(ref_dirs=ref_dirs)
- Use CMA-ES for difficult/noisy landscapes
**For multi-objective problems:**
-- 2-3 objectives: NSGA-II
+- 2-3 objectives: NSGA-II or SPEA2
- 4+ objectives: NSGA-III
- Preference articulation: R-NSGA-II
- Decomposition-friendly: MOEA/D
diff --git a/skills/pymoo/references/parallelization.md b/skills/pymoo/references/parallelization.md
new file mode 100644
index 00000000..d92744ec
--- /dev/null
+++ b/skills/pymoo/references/parallelization.md
@@ -0,0 +1,80 @@
+# Pymoo Parallelization Reference
+
+Reference for parallel evaluation of expensive `ElementwiseProblem` instances.
+
+## When to Use
+
+Use parallelization when `_evaluate` is the bottleneck (simulations, ML inference, external solvers). Pymoo evaluates one solution per `_evaluate` call for `ElementwiseProblem`; pass a runner to evaluate multiple solutions concurrently.
+
+**Requirements:**
+- Subclass `ElementwiseProblem` (not vectorized `Problem`)
+- Set `elementwise_evaluation=True` (default for `ElementwiseProblem`)
+- Pass `elementwise_runner` to the problem constructor
+
+## Starmap Interface (Threads or Processes)
+
+Uses Python's `multiprocessing.Pool.starmap` interface via `StarmapParallelization`.
+
+```python
+import multiprocessing
+from multiprocessing.pool import ThreadPool
+
+from pymoo.algorithms.soo.nonconvex.ga import GA
+from pymoo.core.problem import ElementwiseProblem
+from pymoo.optimize import minimize
+from pymoo.parallelization.starmap import StarmapParallelization
+
+
+class MyProblem(ElementwiseProblem):
+ def __init__(self, elementwise_runner=None, **kwargs):
+ super().__init__(
+ n_var=10, n_obj=1, xl=-5, xu=5,
+ elementwise_runner=elementwise_runner,
+ **kwargs,
+ )
+
+ def _evaluate(self, x, out, *args, **kwargs):
+ out["F"] = (x ** 2).sum()
+
+
+# Thread pool (shared memory; good for I/O-bound evaluation)
+n_threads = 4
+pool = ThreadPool(n_threads)
+runner = StarmapParallelization(pool.starmap)
+problem = MyProblem(elementwise_runner=runner)
+
+result = minimize(problem, GA(), ("n_gen", 50), seed=1)
+pool.close()
+
+# Process pool (separate memory; good for CPU-bound evaluation)
+n_processes = 4
+pool = multiprocessing.Pool(n_processes)
+runner = StarmapParallelization(pool.starmap)
+problem = MyProblem(elementwise_runner=runner)
+
+result = minimize(problem, GA(), ("n_gen", 50), seed=1)
+pool.close()
+```
+
+## Joblib Interface
+
+Alternative using the joblib library:
+
+```python
+from joblib import Parallel, delayed
+from pymoo.parallelization.joblib import JoblibParallelization
+
+runner = JoblibParallelization(lambda func, X: Parallel(n_jobs=4)(delayed(func)(x) for x in X))
+problem = MyProblem(elementwise_runner=runner)
+```
+
+Install joblib if needed: `uv pip install joblib`
+
+## Notes
+
+- Always close the pool after `minimize()` completes
+- Process pools require picklable problem definitions (avoid lambdas in class bodies)
+- Parallelization speedup depends on evaluation cost vs. overhead
+- For vectorized problems (`Problem` subclass evaluating batches), implement batching inside `_evaluate` instead
+
+**Documentation:** https://pymoo.org/parallelization/starmap.html
diff --git a/skills/pymoo/scripts/many_objective_example.py b/skills/pymoo/scripts/many_objective_example.py
index 2f3cb249..27499e5c 100644
--- a/skills/pymoo/scripts/many_objective_example.py
+++ b/skills/pymoo/scripts/many_objective_example.py
@@ -22,7 +22,7 @@ def run_many_objective_optimization():
# Generate reference directions for NSGA-III
# Das-Dennis method for uniform distribution
- ref_dirs = get_reference_directions("das-dennis", n_obj, n_partitions=12)
+ ref_dirs = get_reference_directions("das-dennis", n_obj=n_obj, n_partitions=12)
print(f"Number of reference directions: {len(ref_dirs)}")
diff --git a/skills/scanpy/SKILL.md b/skills/scanpy/SKILL.md
index 77bd6232..b4875d69 100644
--- a/skills/scanpy/SKILL.md
+++ b/skills/scanpy/SKILL.md
@@ -3,7 +3,7 @@ name: scanpy
description: Standard single-cell RNA-seq analysis pipeline. Use for QC, normalization, dimensionality reduction (PCA/UMAP/t-SNE), clustering, differential expression, and visualization. Best for exploratory scRNA-seq analysis with established workflows. For deep learning models use scvi-tools; for data format questions use anndata.
license: BSD-3-Clause
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +11,27 @@ metadata:
## Overview
-Scanpy is a scalable Python toolkit for analyzing single-cell RNA-seq data, built on AnnData. Apply this skill for complete single-cell workflows including quality control, normalization, dimensionality reduction, clustering, marker gene identification, visualization, and trajectory analysis.
+Scanpy is a scalable Python toolkit for analyzing single-cell RNA-seq data, built on AnnData. Apply this skill for complete single-cell workflows including quality control, normalization, dimensionality reduction, clustering, marker gene identification, visualization, and trajectory analysis. Current stable release: **scanpy 1.12.x** (January 2026).
+
+## Installation
+
+Requires Python **3.12+** (scanpy 1.12 dropped Python ≤3.11) and anndata **≥0.10**.
+
+```bash
+uv pip install "scanpy[leiden]"
+```
+
+The `[leiden]` extra installs `python-igraph` and `leidenalg`, required for Leiden clustering. For reproducible environments, pin a version: `uv pip install "scanpy[leiden]==1.12.1"`.
+
+For large or out-of-core datasets, many functions support [Dask](https://docs.dask.org/) arrays (experimental):
+
+```bash
+uv pip install "scanpy[leiden]" dask
+```
+
+See the [Using dask with Scanpy](https://scanpy.scverse.org/en/stable/tutorials/experimental/dask.html) tutorial. For GPU-accelerated scanpy-like operations, use [rapids-singlecell](https://rapids-singlecell.readthedocs.io/) as a separate package.
+
+For AnnData structure and I/O details, use the **anndata** skill. For probabilistic models and batch correction, use **scvi-tools**.
## When to Use This Skill
@@ -37,6 +57,7 @@ import numpy as np
sc.settings.verbosity = 3
sc.settings.set_figure_params(dpi=80, facecolor='white')
sc.settings.figdir = './figures/'
+sc.settings.autosave = True # Preferred over per-plot save= (deprecated in scanpy 1.12)
```
### Loading Data
@@ -93,9 +114,17 @@ sc.pp.filter_genes(adata, min_cells=3)
adata = adata[adata.obs.pct_counts_mt < 5, :] # Remove high MT% cells
```
-**Use the QC script for automated analysis:**
+**Doublet detection (optional, on raw counts before normalization):**
+
+```python
+sc.pp.scrublet(adata) # Core API since scanpy 1.10 (was scanpy.external.pp)
+adata = adata[~adata.obs['predicted_doublet'], :].copy()
+```
+
+**Use the QC script for automated analysis** (run from the skill directory or pass the full path):
+
```bash
-python scripts/qc_analysis.py input_file.h5ad --output filtered.h5ad
+python skills/scanpy/scripts/qc_analysis.py input_file.h5ad --output filtered.h5ad
```
### 2. Normalization and Preprocessing
@@ -156,8 +185,10 @@ for res in [0.3, 0.5, 0.8, 1.0]:
### 5. Marker Gene Identification
+Use `rank_genes_groups` for **exploratory cluster markers** only. Per-cell statistical tests inflate p-values because cells are not independent observations. For rigorous differential expression between conditions or samples, pseudobulk first (see below) and use **pydeseq2** or similar tools.
+
```python
-# Find marker genes for each cluster
+# Find marker genes for each cluster (exploratory)
sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')
# Visualize results
@@ -207,28 +238,29 @@ adata.var.to_csv('results/gene_metadata.csv')
### Creating Publication-Quality Plots
+Prefer `sc.settings.autosave` and `sc.settings.figdir` for saving figures. The per-plot `save=` parameter is deprecated in scanpy 1.12.
+
```python
# Set high-quality defaults
sc.settings.set_figure_params(dpi=300, frameon=False, figsize=(5, 5))
sc.settings.file_format_figs = 'pdf'
+sc.settings.figdir = './figures/'
+sc.settings.autosave = True
-# UMAP with custom styling
+# UMAP with custom styling (saved as figures/umap.pdf via autosave)
sc.pl.umap(adata, color='cell_type',
palette='Set2',
legend_loc='on data',
legend_fontsize=12,
legend_fontoutline=2,
- frameon=False,
- save='_publication.pdf')
+ frameon=False)
# Heatmap of marker genes
sc.pl.heatmap(adata, var_names=genes, groupby='cell_type',
- swap_axes=True, show_gene_labels=True,
- save='_markers.pdf')
+ swap_axes=True, show_gene_labels=True)
# Dot plot
-sc.pl.dotplot(adata, var_names=genes, groupby='cell_type',
- save='_dotplot.pdf')
+sc.pl.dotplot(adata, var_names=genes, groupby='cell_type')
```
Refer to `references/plotting_guide.md` for comprehensive visualization examples.
@@ -246,10 +278,24 @@ sc.tl.dpt(adata)
sc.pl.umap(adata, color='dpt_pseudotime')
```
-### Differential Expression Between Conditions
+### Pseudobulk and Differential Expression Between Conditions
+
+Pseudobulk by sample and cell type, then run proper DE (e.g., pydeseq2) rather than per-cell `rank_genes_groups`:
+
+```python
+# Aggregate counts by sample and cell type (dask-compatible in scanpy 1.12)
+pb = sc.get.aggregate(
+ adata,
+ by=['sample', 'cell_type'],
+ func='sum',
+ layer='counts', # Use raw counts layer if available
+)
+# Downstream: export pb and use pydeseq2 for condition comparisons
+```
+
+For quick exploratory comparisons within a cluster, `rank_genes_groups` is acceptable but interpret p-values cautiously:
```python
-# Compare treated vs control within cell types
adata_subset = adata[adata.obs['cell_type'] == 'T cells']
sc.tl.rank_genes_groups(adata_subset, groupby='condition',
groups=['treated'], reference='control')
@@ -299,12 +345,14 @@ sc.pp.combat(adata, key='batch')
1. **Always save raw counts**: `adata.raw = adata` before filtering genes
2. **Check QC plots carefully**: Adjust thresholds based on dataset quality
-3. **Use Leiden over Louvain**: More efficient and better results
+3. **Use Leiden clustering**: `sc.tl.louvain` is deprecated in scanpy 1.12
4. **Try multiple clustering resolutions**: Find optimal granularity
5. **Validate cell type annotations**: Use multiple marker genes
-6. **Use `use_raw=True` for gene expression plots**: Shows original counts
+6. **Use `use_raw=True` for gene expression plots**: Shows normalized counts from `.raw`
7. **Check PCA variance ratio**: Determine optimal number of PCs
8. **Save intermediate results**: Long workflows can fail partway through
+9. **Pseudobulk for DE**: Do not treat `rank_genes_groups` p-values as rigorous DE between conditions
+10. **Save plots via settings**: Use `sc.settings.autosave` instead of deprecated `save=` on plot functions
## Bundled Resources
@@ -312,7 +360,7 @@ sc.pp.combat(adata, key='batch')
Automated quality control script that calculates metrics, generates plots, and filters data:
```bash
-python scripts/qc_analysis.py input.h5ad --output filtered.h5ad \
+python skills/scanpy/scripts/qc_analysis.py input.h5ad --output filtered.h5ad \
--mt-threshold 5 --min-genes 200 --min-cells 3
```
@@ -323,7 +371,8 @@ Complete step-by-step workflow with detailed explanations and code examples for:
- Normalization and scaling
- Feature selection
- Dimensionality reduction (PCA, UMAP, t-SNE)
-- Clustering (Leiden, Louvain)
+- Clustering (Leiden)
+- Doublet detection (scrublet) and pseudobulk aggregation
- Marker gene identification
- Cell type annotation
- Trajectory inference
@@ -368,8 +417,9 @@ The template includes all standard steps with configurable parameters and helpfu
## Additional Resources
-- **Official scanpy documentation**: https://scanpy.readthedocs.io/
-- **Scanpy tutorials**: https://scanpy-tutorials.readthedocs.io/
+- **Official scanpy documentation**: https://scanpy.scverse.org/en/stable/
+- **Scanpy tutorials**: https://scanpy.scverse.org/en/stable/tutorials/index.html
+- **Release notes**: https://scanpy.scverse.org/en/stable/release-notes/index.html
- **scverse ecosystem**: https://scverse.org/ (related tools: squidpy, scvi-tools, cellrank)
- **Best practices**: Luecken & Theis (2019) "Current best practices in single-cell RNA-seq"
diff --git a/skills/scanpy/assets/analysis_template.py b/skills/scanpy/assets/analysis_template.py
index fa3d34e3..99aa281e 100644
--- a/skills/scanpy/assets/analysis_template.py
+++ b/skills/scanpy/assets/analysis_template.py
@@ -37,6 +37,7 @@ LEIDEN_RESOLUTION = 0.5 # Clustering resolution
sc.settings.verbosity = 3
sc.settings.set_figure_params(dpi=80, facecolor='white')
sc.settings.figdir = FIGURES_DIR
+sc.settings.autosave = True
# ============================================================================
# 1. LOAD DATA
@@ -84,6 +85,11 @@ adata = adata[adata.obs.pct_counts_mt < MT_THRESHOLD, :]
print(f"After filtering: {adata.n_obs} cells, {adata.n_vars} genes")
+# Optional: doublet detection (uncomment; run before normalization)
+# sc.pp.scrublet(adata)
+# adata = adata[~adata.obs['predicted_doublet'], :].copy()
+# print(f"After doublet removal: {adata.n_obs} cells")
+
# ============================================================================
# 3. NORMALIZATION
# ============================================================================
@@ -176,7 +182,7 @@ print("\n" + "=" * 80)
print("MARKER GENE IDENTIFICATION")
print("=" * 80)
-# Find marker genes
+# Find marker genes (exploratory — pseudobulk + pydeseq2 for rigorous DE)
sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')
# Visualize top markers
diff --git a/skills/scanpy/references/api_reference.md b/skills/scanpy/references/api_reference.md
index 40f6659a..333a7106 100644
--- a/skills/scanpy/references/api_reference.md
+++ b/skills/scanpy/references/api_reference.md
@@ -40,6 +40,8 @@ adata.write_zarr(filename) # Write to zarr format
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], inplace=True)
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)
+sc.pp.scrublet(adata) # Doublet detection (core since 1.10)
+sc.pp.scrublet_simulate_doublets(adata) # Simulate doublets for benchmarking
```
### Normalization and Transformation
@@ -55,6 +57,7 @@ sc.pp.sqrt(adata) # Square root transformation
```python
sc.pp.highly_variable_genes(adata, min_mean=0.0125, max_mean=3, min_disp=0.5)
sc.pp.highly_variable_genes(adata, flavor='seurat_v3', n_top_genes=2000)
+# seurat, cell_ranger, seurat_v3 flavors support dask arrays (scanpy 1.10+)
```
### Scaling and Regression
@@ -69,6 +72,7 @@ sc.pp.regress_out(adata, ['total_counts', 'pct_counts_mt']) # Regress out unwan
```python
sc.pp.pca(adata, n_comps=50) # Principal component analysis
sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40) # Compute neighborhood graph
+sc.pp.neighbors(adata, method='jaccard') # Jaccard connectivities (scanpy 1.12)
```
### Batch Correction
@@ -93,7 +97,7 @@ sc.tl.draw_graph(adata, layout='fa') # Force-directed graph
```python
sc.tl.leiden(adata, resolution=0.5) # Leiden clustering (recommended)
-sc.tl.louvain(adata, resolution=0.5) # Louvain clustering
+# sc.tl.louvain(adata, resolution=0.5) # Deprecated in scanpy 1.12 — use leiden
sc.tl.kmeans(adata, n_clusters=10) # K-means clustering
```
@@ -106,6 +110,15 @@ sc.tl.rank_genes_groups(adata, groupby='leiden', method='logreg')
# Get results as dataframe
sc.get.rank_genes_groups_df(adata, group='0')
+# Exploratory only — per-cell tests inflate p-values; pseudobulk for rigorous DE
+```
+
+### Aggregation (Pseudobulk)
+
+```python
+sc.get.aggregate(adata, by='cell_type', func='sum', layer='counts')
+sc.get.aggregate(adata, by=['sample', 'cell_type'], func=['sum', 'mean'])
+# Dask-compatible for sum/mean/count (scanpy 1.12); use pydeseq2 for DE on pseudobulk
```
### Trajectory Inference
@@ -203,8 +216,8 @@ sc.pl.tracksplot(adata, var_names=genes, groupby='leiden')
- `alpha`: Point transparency
### Saving Parameters
-- `save`: Filename to save plot
- `show`: Whether to show plot
+- Prefer `sc.settings.autosave` + `sc.settings.figdir` over deprecated `save=`
## AnnData Structure
@@ -235,12 +248,15 @@ adata[adata.obs['leiden'] == '0', :]
sc.settings.verbosity = 3 # 0=error, 1=warning, 2=info, 3=hint
sc.settings.set_figure_params(dpi=80, facecolor='white')
sc.settings.autoshow = False # Don't show plots automatically
-sc.settings.autosave = True # Autosave figures
+sc.settings.autosave = True # Save figures to figdir (preferred over save=)
sc.settings.figdir = './figures/' # Figure directory
+sc.settings.file_format_figs = 'pdf' # Output format when autosave is True
sc.settings.cachedir = './cache/' # Cache directory
sc.settings.n_jobs = 8 # Number of parallel jobs
```
+Note: the `save=` parameter on individual `sc.pl.*` functions is deprecated in scanpy 1.12. Use `sc.settings.autosave` and `sc.settings.figdir` instead.
+
## Useful Utilities
```python
diff --git a/skills/scanpy/references/plotting_guide.md b/skills/scanpy/references/plotting_guide.md
index 3fc4f620..9bf832b7 100644
--- a/skills/scanpy/references/plotting_guide.md
+++ b/skills/scanpy/references/plotting_guide.md
@@ -7,9 +7,15 @@ Comprehensive guide for creating publication-quality visualizations with scanpy.
All scanpy plotting functions follow consistent patterns:
- Functions in `sc.pl.*` mirror analysis functions in `sc.tl.*`
- Most accept `color` parameter for gene names or metadata columns
-- Results are saved via `save` parameter
+- Prefer `sc.settings.autosave = True` and `sc.settings.figdir` for saving (the per-plot `save=` parameter is deprecated in scanpy 1.12)
- Multiple plots can be generated in a single call
+```python
+sc.settings.figdir = './figures/'
+sc.settings.autosave = True
+sc.settings.file_format_figs = 'pdf'
+```
+
## Essential Quality Control Plots
### Visualize QC Metrics
@@ -106,8 +112,8 @@ sc.pl.umap(adata, color='leiden', size=50, edges=True,
### Cluster Comparison
```python
-# Compare clustering results
-sc.pl.umap(adata, color=['leiden', 'louvain'],
+# Compare clustering resolutions
+sc.pl.umap(adata, color=['leiden_0.3', 'leiden_0.5', 'leiden_0.8'],
save='_cluster_comparison.pdf')
# Cluster dendrogram
@@ -297,14 +303,21 @@ sc.pl.umap(adata, color='leiden', legend_loc=None,
## Exporting Plots
-### Save Individual Plots
+### Save via Settings (recommended)
```python
-# Automatic saving with save parameter
-sc.pl.umap(adata, color='leiden', save='_leiden.pdf')
-# Saves to: sc.settings.figdir + 'umap_leiden.pdf'
+sc.settings.figdir = './figures/'
+sc.settings.autosave = True
+sc.settings.file_format_figs = 'pdf'
-# Manual saving
+sc.pl.umap(adata, color='leiden') # Saves to figures/umap.pdf
+```
+
+The per-plot `save=` parameter still works but is deprecated in scanpy 1.12.
+
+### Manual Saving
+
+```python
import matplotlib.pyplot as plt
fig = sc.pl.umap(adata, color='leiden', show=False, return_fig=True)
fig.savefig('figures/my_umap.pdf', dpi=300, bbox_inches='tight')
@@ -313,9 +326,9 @@ fig.savefig('figures/my_umap.pdf', dpi=300, bbox_inches='tight')
### Batch Export
```python
-# Save multiple versions
-for gene in ['CD3D', 'CD14', 'MS4A1']:
- sc.pl.umap(adata, color=gene, save=f'_{gene}.pdf')
+genes = ['CD3D', 'CD14', 'MS4A1']
+for gene in genes:
+ sc.pl.umap(adata, color=gene) # Each saved via autosave
```
## Common Customization Parameters
@@ -336,9 +349,9 @@ for gene in ['CD3D', 'CD14', 'MS4A1']:
- `use_raw`: Use raw counts for gene expression
### Saving Parameters
-- `save`: Filename suffix for saving
- `show`: Whether to display plot
- `dpi`: Resolution for raster formats
+- Use `sc.settings.autosave` + `sc.settings.figdir` instead of deprecated `save=`
## Tips for Publication Figures
diff --git a/skills/scanpy/references/standard_workflow.md b/skills/scanpy/references/standard_workflow.md
index 7184ee93..f50b8ee3 100644
--- a/skills/scanpy/references/standard_workflow.md
+++ b/skills/scanpy/references/standard_workflow.md
@@ -34,6 +34,10 @@ sc.pp.filter_genes(adata, min_cells=3)
# Remove cells with high mitochondrial content
adata = adata[adata.obs.pct_counts_mt < 5, :]
+# Optional: doublet detection (run on raw counts before normalization)
+# sc.pp.scrublet(adata)
+# adata = adata[~adata.obs['predicted_doublet'], :].copy()
+
# Visualize QC metrics
sc.pl.violin(adata, ['n_genes_by_counts', 'total_counts', 'pct_counts_mt'],
jitter=0.4, multi_panel=True)
@@ -100,20 +104,19 @@ sc.tl.umap(adata)
### 7. Clustering
```python
-# Leiden clustering (recommended)
+# Leiden clustering
sc.tl.leiden(adata, resolution=0.5)
-# Alternative: Louvain clustering
-# sc.tl.louvain(adata, resolution=0.5)
-
# Visualize clustering results
sc.pl.umap(adata, color=['leiden'], legend_loc='on data')
```
### 8. Marker Gene Identification
+`rank_genes_groups` is appropriate for exploratory cluster markers. Per-cell tests produce inflated p-values; for rigorous DE between conditions, pseudobulk with `sc.get.aggregate()` and use pydeseq2.
+
```python
-# Find marker genes for each cluster
+# Find marker genes for each cluster (exploratory)
sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')
# Visualize top marker genes
@@ -171,8 +174,21 @@ sc.pl.umap(adata, color=['dpt_pseudotime'])
### Differential Expression Between Conditions
+Pseudobulk by sample and cell type, then run proper DE (e.g., pydeseq2):
+
+```python
+pb = sc.get.aggregate(
+ adata,
+ by=['sample', 'cell_type'],
+ func='sum',
+ layer='counts',
+)
+# Export pb and use pydeseq2 for condition comparisons
+```
+
+For quick exploratory comparisons only:
+
```python
-# Compare conditions within a cell type
sc.tl.rank_genes_groups(adata, groupby='condition', groups=['treated'],
reference='control', method='wilcoxon')
sc.pl.rank_genes_groups(adata, groups=['treated'])
@@ -200,7 +216,8 @@ sc.pl.umap(adata, color='T_cell_score')
1. Always visualize QC metrics before filtering
2. Save raw counts before normalization (`adata.raw = adata`)
-3. Use Leiden instead of Louvain for clustering (more efficient)
+3. Use Leiden clustering (`sc.tl.louvain` deprecated in scanpy 1.12)
4. Try multiple clustering resolutions to find optimal granularity
5. Validate cell type annotations with known marker genes
-6. Save intermediate results at key steps
+6. Pseudobulk for rigorous DE; treat `rank_genes_groups` p-values as exploratory
+7. Save intermediate results at key steps
diff --git a/uv.lock b/uv.lock
index 391ffa61..67d34e0b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1421,6 +1421,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/5a/dc/491b7661614ab97483abf2056be1deee4dc2490ecbf7bff9ab5cdbac86e1/pyreadline3-3.5.4-py3-none-any.whl", hash = "sha256:eaf8e6cc3c49bcccf145fc6067ba8643d1df34d604a1ec0eccbf7a18e6d3fae6", size = 83178, upload-time = "2024-09-19T02:40:08.598Z" },
]
+[[package]]
+name = "python-dateutil"
+version = "2.9.0.post0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "six" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" },
+]
+
[[package]]
name = "python-dotenv"
version = "1.2.1"
@@ -1676,6 +1688,11 @@ dependencies = [
{ name = "python-dotenv" },
]
+[package.dev-dependencies]
+dev = [
+ { name = "skills-ref" },
+]
+
[package.metadata]
requires-dist = [
{ name = "cisco-ai-skill-scanner", specifier = ">=2.0.8" },
@@ -1683,6 +1700,9 @@ requires-dist = [
{ name = "python-dotenv", specifier = ">=1.0.0" },
]
+[package.metadata.requires-dev]
+dev = [{ name = "skills-ref", git = "https://github.com/agentskills/agentskills.git?subdirectory=skills-ref" }]
+
[[package]]
name = "shellingham"
version = "1.5.4"
@@ -1692,6 +1712,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" },
]
+[[package]]
+name = "six"
+version = "1.17.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" },
+]
+
+[[package]]
+name = "skills-ref"
+version = "0.1.0"
+source = { git = "https://github.com/agentskills/agentskills.git?subdirectory=skills-ref#5d4c1fda3f786fff826c7f56b6cb3341e7f3a911" }
+dependencies = [
+ { name = "click" },
+ { name = "strictyaml" },
+]
+
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -1713,6 +1751,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d9/52/1064f510b141bd54025f9b55105e26d1fa970b9be67ad766380a3c9b74b0/starlette-0.50.0-py3-none-any.whl", hash = "sha256:9e5391843ec9b6e472eed1365a78c8098cfceb7a74bfd4d6b1c0c0095efb3bca", size = 74033, upload-time = "2025-11-01T15:25:25.461Z" },
]
+[[package]]
+name = "strictyaml"
+version = "1.7.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "python-dateutil" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b3/08/efd28d49162ce89c2ad61a88bd80e11fb77bc9f6c145402589112d38f8af/strictyaml-1.7.3.tar.gz", hash = "sha256:22f854a5fcab42b5ddba8030a0e4be51ca89af0267961c8d6cfa86395586c407", size = 115206, upload-time = "2023-03-10T12:50:27.062Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/96/7c/a81ef5ef10978dd073a854e0fa93b5d8021d0594b639cc8f6453c3c78a1d/strictyaml-1.7.3-py3-none-any.whl", hash = "sha256:fb5c8a4edb43bebb765959e420f9b3978d7f1af88c80606c03fb420888f5d1c7", size = 123917, upload-time = "2023-03-10T12:50:17.242Z" },
+]
+
[[package]]
name = "sympy"
version = "1.14.0"