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.

Update anndata skill documentation to version 1.1, enhancing compatibility notes and installation instructions. Introduce experimental APIs for lazy loading and concatenation, and clarify usage of deprecated methods. Update best practices for I/O operations and metadata handling.

Timothy Kassisb24a631e443f
diff --git a/docs/skills.md b/docs/skills.md
index 1ec8e6a0..87029a55 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -107,7 +107,7 @@
- **aeon** - Comprehensive scikit-learn compatible Python toolkit for time series machine learning providing state-of-the-art algorithms across 7 domains: classification (13 algorithm categories including ROCKET variants, deep learning with InceptionTime/ResNet/FCN, distance-based with DTW/ERP/LCSS, shapelet-based, dictionary methods like BOSS/WEASEL, and hybrid ensembles HIVECOTE), regression (9 categories mirroring classification approaches), clustering (k-means/k-medoids with temporal distances, deep learning autoencoders, spectral methods), forecasting (ARIMA, ETS, Theta, Threshold Autoregressive, TCN, DeepAR), anomaly detection (STOMP/MERLIN matrix profile, clustering-based CBLOF/KMeans, isolation methods, copula-based COPOD), segmentation (ClaSP, FLUSS, HMM, binary segmentation), and similarity search (MASS algorithm, STOMP motif discovery, approximate nearest neighbors). Includes 40+ distance metrics (elastic: DTW/DDTW/WDTW/Shape-DTW, edit-based: ERP/EDR/LCSS/TWE/MSM, lock-step: Euclidean/Manhattan), extensive transformations (ROCKET/MiniRocket/MultiRocket for features, Catch22/TSFresh for statistics, SAX/PAA for symbolic representation, shapelet transforms, wavelets, matrix profile), 20+ deep learning architectures (FCN, ResNet, InceptionTime, TCN, autoencoders with attention mechanisms), comprehensive benchmarking tools (UCR/UEA archives with 100+ datasets, published results repository, statistical testing), and performance-optimized implementations using numba. Features progressive model complexity from fast baselines (MiniRocket: <1 second training, 0.95+ accuracy on many benchmarks) to state-of-the-art ensembles (HIVECOTE V2), GPU acceleration support, and extensive visualization utilities. Use cases: physiological signal classification (ECG, EEG), industrial sensor monitoring, financial forecasting, change point detection, pattern discovery, activity recognition from wearables, predictive maintenance, climate time series analysis, and any sequential data requiring specialized temporal modeling beyond standard ML
- **Cirq** - Google quantum computing framework for designing, simulating, and running quantum circuits. Best suited for targeting Google Quantum AI hardware, designing noise-aware circuits, and running quantum characterization experiments. Provides low-level circuit design, noise modeling, and hardware-specific optimizations. For IBM hardware use Qiskit; for quantum ML with autodiff use PennyLane; for physics simulations use QuTiP
- **PufferLib** - High-performance reinforcement learning library achieving 1M-4M steps/second through optimized vectorization, native multi-agent support, and efficient PPO training (PuffeRL). Use this skill for RL training on any environment (Gymnasium, PettingZoo, Atari, Procgen), creating custom PufferEnv environments, developing policies (CNN, LSTM, multi-input architectures), optimizing parallel simulation performance, or scaling multi-agent systems. Includes Ocean suite (20+ environments), seamless framework integration with automatic space flattening, zero-copy vectorization with shared memory buffers, distributed training support, and comprehensive reference guides for training workflows, environment development, vectorization optimization, policy architectures, and third-party integrations
-- **PyMC** - Comprehensive Python library for Bayesian statistical modeling and probabilistic programming. Provides intuitive syntax for building probabilistic models, advanced MCMC sampling algorithms (NUTS, Metropolis-Hastings, Slice sampling), variational inference methods (ADVI, SVGD), Gaussian processes, time series models (ARIMA, state space models), and model comparison tools (WAIC, LOO). Features include: automatic differentiation via Aesara (formerly Theano), GPU acceleration support, parallel sampling, model diagnostics and convergence checking, and integration with ArviZ for visualization and analysis. Supports hierarchical models, mixture models, survival analysis, and custom distributions. Use cases: Bayesian data analysis, uncertainty quantification, A/B testing, time series forecasting, hierarchical modeling, and probabilistic machine learning
+- **PyMC** - Comprehensive Python library for Bayesian statistical modeling and probabilistic programming. Provides intuitive syntax for building probabilistic models, advanced MCMC sampling algorithms (NUTS, nutpie, Metropolis-Hastings, Slice sampling), variational inference methods (ADVI, SVGD), Gaussian processes, time series distributions, and model comparison tools (WAIC, LOO). Features include automatic differentiation via PyTensor, compiled backends such as Numba/JAX, parallel sampling, model diagnostics and convergence checking, PyMC 6 data-container prediction workflows, and integration with ArviZ for visualization and analysis. Supports hierarchical models, mixture models, survival analysis, and custom distributions. Use cases: Bayesian data analysis, uncertainty quantification, A/B testing, time series forecasting, hierarchical modeling, and probabilistic machine learning
- **PyMOO** - Python framework for multi-objective optimization using evolutionary algorithms. Provides implementations of state-of-the-art algorithms including NSGA-II, NSGA-III, MOEA/D, SPEA2, and reference-point based methods. Features include: support for constrained and unconstrained optimization, multiple problem types (continuous, discrete, mixed-variable), performance indicators (hypervolume, IGD, GD), visualization tools (Pareto front plots, convergence plots), and parallel evaluation support. Supports custom problem definitions, algorithm configuration, and result analysis. Designed for engineering design, parameter optimization, and any problem requiring optimization of multiple conflicting objectives simultaneously. Use cases: multi-objective optimization problems, Pareto-optimal solution finding, engineering design optimization, and research in evolutionary computation
- **PyTorch Lightning** - Deep learning framework (lightning 2.6+) that organizes PyTorch code to eliminate boilerplate while maintaining full flexibility. Automates training workflows (epoch/batch iteration, optimizer steps, gradient management, checkpointing), supports multi-GPU/TPU training with DDP/FSDP/DeepSpeed strategies, includes LightningModule for model organization, Trainer for automation, LightningDataModule for data pipelines, callbacks for extensibility, and integrations with TensorBoard, Wandb, and MLflow for experiment tracking
- **PennyLane** - Cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Enables building and training quantum circuits with automatic differentiation, seamless integration with PyTorch/JAX/NumPy, and device-independent execution across simulators and quantum hardware (IBM, Amazon Braket, Google, Rigetti, IonQ). Key features include: quantum circuit construction with QNodes (quantum functions with automatic differentiation), 100+ quantum gates and operations (Pauli, Hadamard, rotation, controlled gates), circuit templates and layers for common ansatze (StronglyEntanglingLayers, BasicEntanglerLayers, UCCSD for chemistry), gradient computation methods (parameter-shift rule for hardware, backpropagation for simulators, adjoint differentiation), quantum chemistry module (molecular Hamiltonian construction, VQE for ground state energy, differentiable Hartree-Fock solver), ML framework integration (TorchLayer for PyTorch models, JAX transformations, TensorFlow deprecated), built-in optimizers (Adam, GradientDescent, QNG, Rotosolve), measurement types (expectation values, probabilities, samples, state vectors), device ecosystem (default.qubit simulator, lightning.qubit for performance, hardware plugins for IBM/Braket/Cirq/Rigetti/IonQ), and Catalyst for just-in-time compilation with adaptive circuits. Supports variational quantum algorithms (VQE, QAOA), quantum neural networks, hybrid quantum-classical models, data encoding strategies (angle, amplitude, IQP embeddings), and pulse-level programming. Use cases: variational quantum eigensolver for molecular simulations, quantum circuit machine learning with gradient-based optimization, hybrid quantum-classical neural networks, quantum chemistry calculations with differentiable workflows, quantum algorithm prototyping with hardware-agnostic code, quantum machine learning research with automatic differentiation, and deploying quantum circuits across multiple quantum computing platforms
@@ -141,7 +141,7 @@
- **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
- **NetworkX** - Comprehensive toolkit for creating, analyzing, and visualizing complex networks and graphs. Supports four graph types (Graph, DiGraph, MultiGraph, MultiDiGraph) with nodes as any hashable objects and rich edge attributes. Provides 100+ algorithms including shortest paths (Dijkstra, Bellman-Ford, A*), centrality measures (degree, betweenness, closeness, eigenvector, PageRank), clustering (coefficients, triangles, transitivity), community detection (modularity-based, label propagation, Girvan-Newman), connectivity analysis (components, cuts, flows), tree algorithms (MST, spanning trees), matching, graph coloring, isomorphism, and traversal (DFS, BFS). Includes 50+ graph generators for classic (complete, cycle, wheel), random (Erdős-Rényi, Barabási-Albert, Watts-Strogatz, stochastic block model), lattice (grid, hexagonal, hypercube), and specialized networks. Supports I/O across formats (edge lists, GraphML, GML, JSON, Pajek, GEXF, DOT) with Pandas/NumPy/SciPy integration. Visualization capabilities include 8+ layout algorithms (spring/force-directed, circular, spectral, Kamada-Kawai), customizable node/edge appearance, interactive visualizations with Plotly/PyVis, and publication-quality figure generation. Use cases: social network analysis, biological networks (protein-protein interactions, gene regulatory networks, metabolic pathways), transportation systems, citation networks, knowledge graphs, web structure analysis, infrastructure networks, and any domain involving pairwise relationships requiring structural analysis or graph-based modeling
- **Plotly** - Interactive scientific and statistical data visualization library for Python with 40+ chart types. Provides both high-level API (Plotly Express) for quick visualizations and low-level API (graph objects) for fine-grained control. Key features include: comprehensive chart types (scatter, line, bar, histogram, box, violin, heatmap, contour, 3D plots, geographic maps, financial charts, statistical distributions, hierarchical charts), interactive features (hover tooltips, pan/zoom, legend toggling, animations, rangesliders, buttons/dropdowns), publication-quality output (static images in PNG/PDF/SVG via Kaleido, interactive HTML with embeddable figures), extensive customization (templates, themes, color scales, fonts, layouts, annotations, shapes), subplot support (multi-plot figures with shared axes), and Dash integration for building analytical web applications. Plotly Express offers one-line creation of complex visualizations with automatic color encoding, faceting, and trendlines. Graph objects provide precise control for specialized visualizations (candlestick charts, 3D surfaces, sankey diagrams, gauge charts). Supports pandas DataFrames, NumPy arrays, and various data formats. Use cases: scientific data visualization, statistical analysis, financial charting, interactive dashboards, publication figures, exploratory data analysis, and any application requiring interactive or publication-quality visualizations
-- **Polars** - High-performance DataFrame library written in Rust with Python bindings, designed for fast data manipulation and analysis. Provides lazy evaluation for query optimization, efficient memory usage, and parallel processing. Key features include: DataFrame operations (filtering, grouping, joining, aggregations), support for large datasets (larger than RAM), integration with pandas and NumPy, expression API for complex transformations, and support for multiple data formats (CSV, Parquet, JSON, Excel, Arrow). Features query optimization through lazy evaluation, automatic parallelization, and efficient memory management. Often 5-30x faster than pandas for many operations. Use cases: large-scale data processing, ETL pipelines, data analysis workflows, and high-performance data manipulation tasks
+- **Polars** - High-performance DataFrame library written in Rust with Python bindings for fast data manipulation, ETL, analytics, and pandas migration. Provides expression-based transformations, lazy query optimization, automatic parallel execution, streaming out-of-core processing, Arrow interoperability, and optional GPU execution. Supports common data sources and formats including CSV, Parquet, JSON/NDJSON, Excel, Arrow IPC, cloud object storage, databases, and BigQuery. Use cases: large-scale data processing, memory-conscious analytical pipelines, feature engineering, and high-performance DataFrame workflows
- **Seaborn** - Statistical data visualization with dataset-oriented interface, automatic confidence intervals, publication-quality themes, colorblind-safe palettes, and comprehensive support for exploratory analysis, distribution comparisons, correlation matrices, regression plots, and multi-panel figures
- **Vaex** - High-performance Python library for lazy, out-of-core DataFrames to process and visualize tabular datasets larger than available RAM. Processes over a billion rows per second through memory-mapped files (HDF5, Apache Arrow), lazy evaluation, and virtual columns (zero memory overhead). Provides instant file opening, efficient aggregations across billions of rows, interactive visualizations without sampling, machine learning pipelines with transformers (scalers, encoders, PCA), and seamless integration with pandas/NumPy/Arrow. Includes comprehensive ML framework (vaex.ml) with feature scaling, categorical encoding, dimensionality reduction, and integration with scikit-learn/XGBoost/LightGBM/CatBoost. Supports distributed computing via Dask, asynchronous operations, and state management for production deployment. Use cases: processing gigabyte to terabyte datasets, fast statistical aggregations on massive data, visualizing billion-row datasets, ML pipelines on big data, converting between data formats, and working with astronomical, financial, or scientific large-scale datasets
diff --git a/skills/anndata/SKILL.md b/skills/anndata/SKILL.md
index 7b24a82c..fb8a68e0 100644
--- a/skills/anndata/SKILL.md
+++ b/skills/anndata/SKILL.md
@@ -2,8 +2,10 @@
name: anndata
description: Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.
license: BSD-3-Clause license
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.11+ and uv. Examples target AnnData 0.12.16, with experimental APIs clearly marked where used.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -26,18 +28,25 @@ Use this skill when:
## Installation
-Requires Python 3.11+ (anndata 0.11+ dropped 3.9). Current stable release: 0.12.x.
+Requires Python 3.11+. Current stable release: 0.12.16 (released 2026-05-18).
```bash
-uv pip install anndata
+uv pip install "anndata==0.12.16"
# Lazy I/O and dask-backed operations
-uv pip install "anndata[dask,lazy]"
+uv pip install "anndata[dask,lazy]==0.12.16"
# Development / docs (contributors)
-uv pip install "anndata[dev,test,doc]"
+uv pip install "anndata[dev,test,doc]==0.12.16"
```
+Use unpinned installs only when intentionally tracking the latest compatible release.
+
+Current API notes:
+- Use `anndata.io` for non-native `read_*` and `write_*` helpers. Top-level `anndata.read_h5ad` and `anndata.read_zarr` remain supported.
+- Avoid deprecated APIs: `ad.read`, `AnnData.concatenate()`, `AnnData.*_keys()`, and `anndata.__version__`. Prefer `ad.read_h5ad`, `ad.concat`, mapping `.keys()`, and `importlib.metadata.version("anndata")`.
+- Treat `anndata.experimental` APIs as useful but unstable. Prefer them for large-data workflows only when their current caveats are acceptable.
+
## Quick Start
### Creating an AnnData object
@@ -177,11 +186,17 @@ adata = ad.concat(
# Concatenate variables (combine modalities)
adata = ad.concat([adata_rna, adata_protein], axis=1)
-# Lazy concatenation
+# Lazy collection over backed AnnData objects (experimental)
from anndata.experimental import AnnCollection
+
+backed_adatas = [
+ ad.read_h5ad(path, backed='r')
+ for path in ['data1.h5ad', 'data2.h5ad']
+]
collection = AnnCollection(
- ['data1.h5ad', 'data2.h5ad'],
+ backed_adatas,
join_obs='outer',
+ join_vars='inner',
label='dataset'
)
```
@@ -389,9 +404,11 @@ Use compression and appropriate formats:
adata.strings_to_categoricals()
adata.write_h5ad('file.h5ad', compression='gzip')
-# Use Zarr for cloud storage (v3 optional since anndata 0.12)
-import anndata
-anndata.settings.zarr_write_format = 3 # default is 2
+# Use Zarr for cloud storage; v3 writes are opt-in in anndata 0.12
+import anndata as ad
+
+ad.settings.zarr_write_format = 3
+ad.settings.auto_shard_zarr_v3 = True # experimental; independent of zarr_write_format
adata.write_zarr('file.zarr', chunks=(1000, 1000))
```
diff --git a/skills/anndata/references/best_practices.md b/skills/anndata/references/best_practices.md
index 91244c76..c1252024 100644
--- a/skills/anndata/references/best_practices.md
+++ b/skills/anndata/references/best_practices.md
@@ -111,11 +111,11 @@ import anndata
# Default is Zarr v2; opt into v3 for cloud workflows (anndata 0.12+)
anndata.settings.zarr_write_format = 3
-anndata.settings.auto_shard_zarr_v3 = True
+anndata.settings.auto_shard_zarr_v3 = True # experimental; independent of zarr_write_format
adata.write_zarr('data.zarr', chunks=(100, 100))
```
- Excellent for cloud storage (S3, GCS)
-- Supports parallel I/O and Zarr v3 sharding (0.12+)
+- Supports parallel I/O and opt-in Zarr v3 sharding (0.12+)
- Good compression
- Best for: Large datasets, cloud workflows, parallel processing
@@ -167,10 +167,13 @@ adata_filtered = high_quality.to_memory()
# Open in read-write backed mode
adata = ad.read_h5ad('data.h5ad', backed='r+')
-# Modify metadata (written to disk)
-adata.obs['new_annotation'] = values
+# Modify X (persisted to disk)
+adata.X[0, 0] = 0
-# X remains on disk, modifications saved immediately
+# Metadata changes are not persisted from backed mode; load and write a new file
+adata_memory = adata.to_memory()
+adata_memory.obs['new_annotation'] = values
+adata_memory.write_h5ad('data_with_annotations.h5ad')
```
### Chunked processing
diff --git a/skills/anndata/references/concatenation.md b/skills/anndata/references/concatenation.md
index 6cb307c6..85273a0c 100644
--- a/skills/anndata/references/concatenation.md
+++ b/skills/anndata/references/concatenation.md
@@ -257,15 +257,17 @@ adata_combined = ad.concat([adata1, adata2], uns_merge='unique')
## Lazy Concatenation (AnnCollection)
-For very large datasets, use lazy concatenation that doesn't load all data:
+For very large datasets, use `AnnCollection` to lazily concatenate AnnData objects along the observation axis. This API is experimental; use backed AnnData objects when the inputs are stored in `.h5ad` files.
```python
+import anndata as ad
from anndata.experimental import AnnCollection
-# Create collection from file paths (doesn't load data)
files = ['data1.h5ad', 'data2.h5ad', 'data3.h5ad']
+backed_adatas = [ad.read_h5ad(path, backed='r') for path in files]
+
collection = AnnCollection(
- files,
+ backed_adatas,
join_obs='outer',
join_vars='inner',
label='dataset',
@@ -298,6 +300,7 @@ first_dataset = collection[0]
For datasets too large for memory, concatenate directly on disk:
```python
+import anndata as ad
from anndata.experimental import concat_on_disk
# Concatenate without loading into memory
diff --git a/skills/anndata/references/io_operations.md b/skills/anndata/references/io_operations.md
index 5528c92f..f604defb 100644
--- a/skills/anndata/references/io_operations.md
+++ b/skills/anndata/references/io_operations.md
@@ -9,6 +9,8 @@ import anndata as ad
from anndata.io import read_csv, read_mtx, read_loom, read_elem, write_elem
```
+Avoid deprecated I/O aliases such as `ad.read`; use `ad.read_h5ad` or `anndata.io.read_h5ad` explicitly.
+
## Native Formats
### H5AD (HDF5-based)
@@ -35,10 +37,11 @@ adata = ad.read_h5ad('data.h5ad')
# Read in backed mode (lazy loading for large files)
adata = ad.read_h5ad('data.h5ad', backed='r') # Read-only
-adata = ad.read_h5ad('data.h5ad', backed='r+') # Read-write
+adata = ad.read_h5ad('data.h5ad', backed='r+') # Read-write for X
# Backed mode enables working with datasets larger than RAM
# Only accessed data is loaded into memory
+# In backed mode, only X updates are persisted; write a new file for obs/var/uns changes.
```
#### Backed mode operations
@@ -84,20 +87,24 @@ import anndata
# Default writes Zarr v2; opt into v3 and optional auto-sharding
anndata.settings.zarr_write_format = 3
-anndata.settings.auto_shard_zarr_v3 = True # shards="auto" for v3 arrays
+anndata.settings.auto_shard_zarr_v3 = True # experimental; independent of zarr_write_format
adata.write_zarr('data.zarr', chunks=(1000, 1000))
```
+Zarr v3 writing is available in anndata 0.12, with structured-array exceptions and evolving performance guidance. Consolidated metadata is recommended for remote Zarr stores.
+
#### Remote Zarr access
+Only open remote stores from trusted, expected locations. Prefer allowlisted HTTPS/S3/GCS paths or signed URLs, and avoid asking an agent to fetch arbitrary user-supplied URLs.
+
```python
import fsspec
-# Access Zarr from S3
+# Access Zarr from an expected S3 location
store = fsspec.get_mapper('s3://bucket-name/data.zarr')
adata = ad.read_zarr(store)
-# Access Zarr from URL
+# Access Zarr from a trusted HTTPS location
store = fsspec.get_mapper('https://example.com/data.zarr')
adata = ad.read_zarr(store)
```
@@ -264,7 +271,16 @@ with h5py.File('data.h5ad', 'a') as f:
## Lazy Operations
-For very large datasets, use lazy reading to avoid loading entire datasets:
+For very large datasets, use lazy reading to avoid loading entire datasets. `read_lazy` is experimental and is designed for on-disk or in-cloud AnnData stores, including lazy `obs` and `var` access.
+
+```python
+from anndata.experimental import read_lazy
+
+adata = read_lazy('large_data.zarr')
+print(adata.obs.head()) # Does not require loading X
+```
+
+For element-level control, use `read_elem_lazy` on an open store:
```python
import h5py
@@ -305,36 +321,44 @@ print(adata.var.columns)
# X is not loaded into memory
```
-### Append to existing file
+### Update backed data or write a new file
```python
-# Open in read-write mode
+# Open in read-write mode for X updates
adata = ad.read_h5ad('data.h5ad', backed='r+')
-# Modify metadata
-adata.obs['new_column'] = values
+# X updates can be persisted in backed mode
+adata.X[0, 0] = 0
-# Changes are written to disk
+# Metadata changes are not persisted from backed mode; write a new file instead
+adata_memory = adata.to_memory()
+adata_memory.obs['new_column'] = values
+adata_memory.write_h5ad('data_with_metadata.h5ad')
```
-### Download from URL
+### Download from a trusted URL
+Validate remote sources before downloading. Prefer local files or vetted object-store paths over arbitrary URLs.
+
```python
import anndata as ad
+import urllib.request
+from urllib.parse import urlparse
-# Read directly from URL (for h5ad files)
-url = 'https://example.com/data.h5ad'
-adata = ad.read_h5ad(url, backed='r') # Streaming access
+url = 'https://example.org/datasets/reference.h5ad'
+parsed = urlparse(url)
+trusted_hosts = {'example.org'}
-# For other formats, download first
-import urllib.request
-urllib.request.urlretrieve(url, 'local_file.h5ad')
-adata = ad.read_h5ad('local_file.h5ad')
+if parsed.scheme != 'https' or parsed.netloc not in trusted_hosts:
+ raise ValueError('Refusing to download from an untrusted host')
+
+urllib.request.urlretrieve(url, 'reference.h5ad')
+adata = ad.read_h5ad('reference.h5ad')
```
## Performance Tips
### Reading
- Use `backed='r'` for large files you only need to query
-- Use `backed='r+'` if you need to modify metadata without loading all data
+- Use `backed='r+'` only for `X` updates; write a new file for metadata changes
- H5AD format is generally fastest for random access
- Zarr is better for cloud storage and parallel access
- Consider compression for storage, but note it may slow down reading
@@ -392,10 +416,14 @@ for i in range(0, adata.n_obs, chunk_size):
### Strategy 3: Use AnnCollection
```python
+import anndata as ad
from anndata.experimental import AnnCollection
-# Create collection without loading data
-adatas = [f'dataset_{i}.h5ad' for i in range(10)]
+# Create backed objects, then lazily concatenate along observations
+adatas = [
+ ad.read_h5ad(f'dataset_{i}.h5ad', backed='r')
+ for i in range(10)
+]
collection = AnnCollection(
adatas,
join_obs='inner',
@@ -429,12 +457,10 @@ adata.X = csr_matrix(adata.X)
adata.write_h5ad('compressed.h5ad', compression='gzip')
```
-### Issue: Cannot modify backed object
-**Solution**: Either load to memory or open in 'r+' mode
+### Issue: Cannot modify backed metadata
+**Solution**: Load to memory and write a new file. Backed mode only persists updates to `X`.
```python
-# Option 1: Load to memory
adata = adata.to_memory()
-
-# Option 2: Open in read-write mode
-adata = ad.read_h5ad('file.h5ad', backed='r+')
+adata.obs['new_column'] = values
+adata.write_h5ad('updated_file.h5ad')
```
diff --git a/skills/anndata/references/manipulation.md b/skills/anndata/references/manipulation.md
index de0afb01..9266ebd3 100644
--- a/skills/anndata/references/manipulation.md
+++ b/skills/anndata/references/manipulation.md
@@ -177,14 +177,14 @@ print(adata.obs['tissue'].dtype) # category
### Sparse to dense and vice versa
```python
-from scipy.sparse import csr_matrix
+from scipy.sparse import csr_matrix, issparse
# Dense to sparse
-if not isinstance(adata.X, csr_matrix):
+if not issparse(adata.X):
adata.X = csr_matrix(adata.X)
# Sparse to dense
-if isinstance(adata.X, csr_matrix):
+if issparse(adata.X):
adata.X = adata.X.toarray()
# Convert layer
diff --git a/skills/biopython/SKILL.md b/skills/biopython/SKILL.md
index ab60e127..221173b6 100644
--- a/skills/biopython/SKILL.md
+++ b/skills/biopython/SKILL.md
@@ -1,9 +1,11 @@
---
name: biopython
description: Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.
-license: Unknown
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.10+, NumPy, and Biopython. Entrez and web BLAST examples require network access; local BLAST/MUSCLE examples require those command-line tools installed separately.
+license: Biopython License Agreement
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +13,7 @@ metadata:
## Overview
-Biopython is a comprehensive set of freely available Python tools for biological computation. It provides functionality for sequence manipulation, file I/O, database access, structural bioinformatics, phylogenetics, and many other bioinformatics tasks. The current version is **Biopython 1.87** (released March 2026). It requires **Python 3.10+** and NumPy.
+Biopython is a comprehensive set of freely available Python tools for biological computation. It provides functionality for sequence manipulation, file I/O, database access, structural bioinformatics, phylogenetics, and many other bioinformatics tasks. The current version is **Biopython 1.87** (released 30 March 2026). It supports **Python 3.10-3.14** and PyPy3.10, and requires NumPy. Biopython 1.87 also addresses **CVE-2025-68463** in `Bio.Entrez.Parser` when parsing untrusted files, so prefer 1.87+ for workflows that parse externally supplied Entrez XML.
## When to Use This Skill
@@ -44,19 +46,20 @@ Biopython is organized into modular sub-packages, each addressing specific bioin
## Installation and Setup
-Install Biopython (requires Python 3.10+ and NumPy):
+Install the current stable Biopython release with an explicit version pin for reproducibility:
```bash
-uv pip install biopython
+uv pip install "biopython==1.87"
```
-For NCBI database access, always set your email address (required by NCBI). For higher rate limits (10 req/s instead of 3 req/s), read `NCBI_API_KEY` from the environment — do not hardcode keys:
+For NCBI database access, always set your email address (required by NCBI). For reusable software, set a stable `Entrez.tool` value and register the tool/email with NCBI. For higher rate limits (10 req/s instead of 3 req/s), read only `NCBI_API_KEY` from the environment — do not hardcode keys or load unrelated environment variables:
```python
import os
from Bio import Entrez
Entrez.email = "[email protected]" # required — use your real email
+Entrez.tool = "your_tool_name" # optional but recommended for reusable software
# Optional: register at https://www.ncbi.nlm.nih.gov/account/settings/
if api_key := os.environ.get("NCBI_API_KEY"):
@@ -247,13 +250,13 @@ When a user asks about a specific Biopython task:
Example search patterns for reference files:
```bash
# Find information about specific functions
-grep -n "SeqIO.parse" references/sequence_io.md
+rg -n "SeqIO.parse" references/sequence_io.md
# Find examples of specific tasks
-grep -n "BLAST" references/blast.md
+rg -n "BLAST" references/blast.md
# Find information about specific concepts
-grep -n "alignment" references/alignment.md
+rg -n "alignment" references/alignment.md
```
### Writing Biopython Code
@@ -266,10 +269,13 @@ Follow these principles when writing Biopython code:
from Bio.Seq import Seq
```
-2. **Set Entrez email** when using NCBI databases; load `NCBI_API_KEY` from the environment if present
+2. **Set Entrez email** when using NCBI databases; load only `NCBI_API_KEY` from the environment if present
```python
import os
+ from Bio import Entrez
+
Entrez.email = "[email protected]"
+ Entrez.tool = "your_tool_name"
if api_key := os.environ.get("NCBI_API_KEY"):
Entrez.api_key = api_key
```
@@ -293,6 +299,8 @@ Follow these principles when writing Biopython code:
6. **Handle errors gracefully** - Network operations and file parsing can fail
```python
+ from urllib.error import HTTPError
+
try:
handle = Entrez.efetch(db="nucleotide", id=accession)
except HTTPError as e:
@@ -385,7 +393,7 @@ Phylo.draw_ascii(tree)
3. **Validate file formats** before parsing
4. **Handle missing data gracefully** - Not all records have all fields
5. **Cache downloaded data** - Don't repeatedly download the same sequences
-6. **Respect NCBI rate limits** - Use API keys and proper delays
+6. **Respect NCBI rate limits** - Use API keys, registered tool/email values for reusable software, and Entrez history/batching for large jobs
7. **Test with small datasets** before processing large files
8. **Keep Biopython updated** to get latest features and bug fixes
9. **Use appropriate genetic code tables** for translation
@@ -423,6 +431,8 @@ Phylo.draw_ascii(tree)
- **Tutorial**: https://biopython.org/docs/latest/Tutorial/
- **Cookbook**: https://biopython.org/docs/latest/Tutorial/ (advanced examples)
- **GitHub**: https://github.com/biopython/biopython
+- **Release notes**: https://github.com/biopython/biopython/blob/master/NEWS.rst
+- **Deprecated APIs**: https://github.com/biopython/biopython/blob/master/DEPRECATED.rst
- **Mailing List**: [email protected]
## Quick Reference
@@ -431,13 +441,13 @@ To locate information in reference files, use these search patterns:
```bash
# Search for specific functions
-grep -n "function_name" references/*.md
+rg -n "function_name" references/*.md
# Find examples of specific tasks
-grep -n "example" references/sequence_io.md
+rg -n "example" references/sequence_io.md
# Find all occurrences of a module
-grep -n "Bio.Seq" references/*.md
+rg -n "Bio.Seq" references/*.md
```
## Summary
diff --git a/skills/biopython/references/advanced.md b/skills/biopython/references/advanced.md
index 02fef358..7a0c60b6 100644
--- a/skills/biopython/references/advanced.md
+++ b/skills/biopython/references/advanced.md
@@ -43,7 +43,7 @@ pwm = motif.counts.normalize(pseudocounts=0.5)
print(pwm)
# Calculate information content
-ic = motif.counts.information_content()
+ic = sum(motif.relative_entropy)
print(f"Information content: {ic:.2f} bits")
```
@@ -324,24 +324,28 @@ gd_diagram.draw(format="linear", pagesize="A4", fragments=1)
gd_diagram.write("genome_diagram.pdf", "PDF")
```
-## Sequence Comparison with Bio.pairwise2
+## Sequence Comparison with PairwiseAligner
-**Note**: `Bio.pairwise2` is deprecated — use `Bio.Align.PairwiseAligner` instead (see `alignment.md`). For HMM workflows, `Bio.HMM` and `Bio.MarkovModel` were removed in Biopython 1.86; use [hmmlearn](https://pypi.org/project/hmmlearn/) instead.
-
-Legacy `pairwise2` example (avoid in new code):
+`Bio.pairwise2` is deprecated (since Biopython 1.80). Use `Bio.Align.PairwiseAligner` for new pairwise alignment code (see `alignment.md`). For HMM workflows, `Bio.HMM` and `Bio.MarkovModel` were removed in Biopython 1.86; use [hmmlearn](https://pypi.org/project/hmmlearn/) instead.
```python
-from Bio import pairwise2
-from Bio.pairwise2 import format_alignment
+from Bio.Align import PairwiseAligner
+
+aligner = PairwiseAligner()
+aligner.mode = "global"
+aligner.match_score = 1
+aligner.mismatch_score = 0
+aligner.gap_score = 0 # Optional: mimic the old globalxx scoring style
-# Global alignment
-alignments = pairwise2.align.globalxx("ACCGT", "ACGT")
+alignments = aligner.align("ACCGT", "ACGT")
-# Print top alignments
for alignment in alignments[:3]:
- print(format_alignment(*alignment))
+ print(alignment)
+ print(f"Score: {alignment.score}")
```
+Avoid importing `Bio.pairwise2` in new code. It remains a legacy migration concern only.
+
## Working with PubChem
```python
@@ -486,7 +490,6 @@ for orf in orfs:
```python
from Bio import SeqIO
-from Bio.SeqUtils import CodonUsage
def analyze_codon_usage(fasta_file):
"""Analyze codon usage in coding sequences."""
diff --git a/skills/biopython/references/alignment.md b/skills/biopython/references/alignment.md
index 2a45961e..e6da935e 100644
--- a/skills/biopython/references/alignment.md
+++ b/skills/biopython/references/alignment.md
@@ -180,21 +180,25 @@ seq_record = alignment[0] # First sequence
### Alignment Analysis
```python
-# Calculate alignment statistics
-from Bio.Align import AlignInfo
+# Calculate alignment statistics with current Biopython APIs.
+# Avoid Bio.AlignInfo.SummaryInfo: it is deprecated in 1.86 and several
+# methods were removed in 1.85/1.86.
+from Bio import AlignIO
+from Bio.motifs import Motif
-summary = AlignInfo.SummaryInfo(alignment)
+msa = AlignIO.read("alignment.aln", "clustal")
+alignment = msa.alignment # New-style Bio.Align.Alignment
-# Get consensus sequence
-consensus = summary.gap_consensus(threshold=0.7)
+# Build a motif from a DNA alignment to inspect per-column counts
+motif = Motif("ACGT", alignment)
+counts = motif.counts
+consensus = counts.consensus
-# Position-specific scoring matrix (PSSM)
-pssm = summary.pos_specific_score_matrix(consensus)
+# Information content replacement for deprecated SummaryInfo methods
+information_content = sum(motif.relative_entropy)
-# Calculate information content
-from Bio import motifs
-motif = motifs.create([record.seq for record in alignment])
-information = motif.counts.information_content()
+# Replacement dictionary from the new-style Alignment object
+substitutions = alignment.substitutions
```
## Creating Alignments Programmatically
@@ -237,8 +241,6 @@ alignment.extend(other_alignment)
```python
# Remove all gap-only columns
-from Bio.Align import AlignInfo
-
no_gaps = []
for i in range(alignment.get_alignment_length()):
column = alignment[:, i]
@@ -272,36 +274,43 @@ for i, record1 in enumerate(alignment):
## Running External Alignment Tools
-### Clustal Omega (via Command Line)
+Biopython 1.86 removed `Bio.Application` and all command-line wrapper modules, including `Bio.Align.Applications`. Use Python's standard `subprocess` module with argument lists. Keep executable names and flags explicit, and do not construct command arguments from unsanitized user input.
+
+### Clustal Omega (via subprocess)
```python
-from Bio.Align.Applications import ClustalOmegaCommandline
+import subprocess
+from Bio import AlignIO
-# Setup command
-clustal_cmd = ClustalOmegaCommandline(
- infile="sequences.fasta",
- outfile="alignment.aln",
- verbose=True,
- auto=True
-)
+cmd = [
+ "clustalo",
+ "-i", "sequences.fasta",
+ "-o", "alignment.aln",
+ "--outfmt", "clu",
+ "--force",
+ "--auto",
+]
-# Run alignment
-stdout, stderr = clustal_cmd()
+subprocess.run(cmd, check=True)
# Read result
alignment = AlignIO.read("alignment.aln", "clustal")
```
-### MUSCLE (via Command Line)
+### MUSCLE (via subprocess)
```python
-from Bio.Align.Applications import MuscleCommandline
+import subprocess
+from Bio import AlignIO
+
+cmd = [
+ "muscle",
+ "-align", "sequences.fasta",
+ "-output", "alignment.fasta",
+]
-muscle_cmd = MuscleCommandline(
- input="sequences.fasta",
- out="alignment.aln"
-)
-stdout, stderr = muscle_cmd()
+subprocess.run(cmd, check=True)
+alignment = AlignIO.read("alignment.fasta", "fasta")
```
## Best Practices
diff --git a/skills/biopython/references/blast.md b/skills/biopython/references/blast.md
index 634cc629..eda42b39 100644
--- a/skills/biopython/references/blast.md
+++ b/skills/biopython/references/blast.md
@@ -166,49 +166,50 @@ Local BLAST requires:
1. BLAST+ command-line tools installed
2. BLAST databases downloaded locally
-### Using Command-Line Wrappers
+### Running BLAST+ via subprocess
+
+Biopython 1.86 removed `Bio.Application` and the BLAST command-line wrappers in `Bio.Blast.Applications`. Use the standard library `subprocess` module with explicit argument lists. Keep command names and flags fixed, validate file paths before running, and do not interpolate unsanitized user input into shell commands.
```python
-from Bio.Blast.Applications import NcbiblastnCommandline
-
-# Setup BLAST command
-blastn_cline = NcbiblastnCommandline(
- query="input.fasta",
- db="local_database",
- evalue=0.001,
- outfmt=5, # XML format
- out="results.xml"
-)
+import subprocess
+from Bio.Blast import NCBIXML
-# Run BLAST
-stdout, stderr = blastn_cline()
+cmd = [
+ "blastn",
+ "-query", "input.fasta",
+ "-db", "local_database",
+ "-evalue", "0.001",
+ "-outfmt", "5", # XML format for NCBIXML
+ "-out", "results.xml",
+]
+subprocess.run(cmd, check=True)
# Parse results
-from Bio.Blast import NCBIXML
with open("results.xml") as result_handle:
blast_record = NCBIXML.read(result_handle)
```
-### Available Command-Line Wrappers
+### Common BLAST+ commands
-- `NcbiblastnCommandline` - BLASTN wrapper
-- `NcbiblastpCommandline` - BLASTP wrapper
-- `NcbiblastxCommandline` - BLASTX wrapper
-- `NcbitblastnCommandline` - TBLASTN wrapper
-- `NcbitblastxCommandline` - TBLASTX wrapper
+- `blastn` - nucleotide vs nucleotide
+- `blastp` - protein vs protein
+- `blastx` - translated nucleotide vs protein
+- `tblastn` - protein vs translated nucleotide
+- `tblastx` - translated nucleotide vs translated nucleotide
+- `makeblastdb` - create local BLAST databases
### Creating BLAST Databases
```python
-from Bio.Blast.Applications import NcbimakeblastdbCommandline
-
-# Create nucleotide database
-makedb_cline = NcbimakeblastdbCommandline(
- input_file="sequences.fasta",
- dbtype="nucl",
- out="my_database"
-)
-stdout, stderr = makedb_cline()
+import subprocess
+
+cmd = [
+ "makeblastdb",
+ "-in", "sequences.fasta",
+ "-dbtype", "nucl",
+ "-out", "my_database",
+]
+subprocess.run(cmd, check=True)
```
## Analyzing BLAST Results
@@ -288,13 +289,16 @@ def fetch_hit_sequences(blast_record, num_sequences=5):
### Tab-Delimited Output (outfmt 6/7)
```python
-# Run BLAST with tabular output
-blastn_cline = NcbiblastnCommandline(
- query="input.fasta",
- db="database",
- outfmt=6,
- out="results.txt"
-)
+import subprocess
+
+cmd = [
+ "blastn",
+ "-query", "input.fasta",
+ "-db", "database",
+ "-outfmt", "6",
+ "-out", "results.txt",
+]
+subprocess.run(cmd, check=True)
# Parse tabular results
with open("results.txt") as f:
@@ -313,13 +317,17 @@ with open("results.txt") as f:
### Custom Output Formats
```python
+import subprocess
+
# Specify custom columns (outfmt 6 with custom fields)
-blastn_cline = NcbiblastnCommandline(
- query="input.fasta",
- db="database",
- outfmt="6 qseqid sseqid pident length evalue bitscore qseq sseq",
- out="results.txt"
-)
+cmd = [
+ "blastn",
+ "-query", "input.fasta",
+ "-db", "database",
+ "-outfmt", "6 qseqid sseqid pident length evalue bitscore qseq sseq",
+ "-out", "results.txt",
+]
+subprocess.run(cmd, check=True)
```
## Best Practices
diff --git a/skills/biopython/references/databases.md b/skills/biopython/references/databases.md
index 75c271e9..b199ad46 100644
--- a/skills/biopython/references/databases.md
+++ b/skills/biopython/references/databases.md
@@ -15,11 +15,15 @@ from Bio import Entrez
# Always set your email
Entrez.email = "[email protected]"
+
+# For reusable software, set a stable tool name and register
+# the tool/email pair with NCBI.
+Entrez.tool = "your_tool_name"
```
### API Key (Recommended)
-Using an API key increases rate limits from 3 to 10 requests per second. Register at https://www.ncbi.nlm.nih.gov/account/settings/ and read the key from the environment — do not hardcode it:
+Using an API key increases E-utilities rate limits from 3 to 10 requests per second. Register at https://www.ncbi.nlm.nih.gov/account/settings/ and read only `NCBI_API_KEY` from the environment — do not hardcode it and do not load unrelated environment variables:
```python
import os
@@ -35,7 +39,7 @@ Biopython automatically respects NCBI rate limits:
- **Without API key**: 3 requests per second
- **With API key**: 10 requests per second
-The module handles this automatically, so you don't need to add delays between requests.
+The module handles ordinary request pacing automatically and retries transient HTTP 5XX failures. For large jobs, use Entrez history (`usehistory="y"` / `WebEnv` / `query_key`) and batch requests rather than making one request per record. NCBI also recommends scheduling large jobs for weekends or between 9:00 PM and 5:00 AM Eastern time.
## Core Entrez Functions
@@ -396,15 +400,16 @@ handle.close()
## Best Practices
1. **Always set Entrez.email** - Required by NCBI
-2. **Use `NCBI_API_KEY` from the environment** for higher rate limits (10 req/s vs 3 req/s); never hardcode keys
-3. **Close handles** after reading to free resources
-4. **Batch large requests** - Use retstart and retmax for pagination
-5. **Use WebEnv for large downloads** - Store results on server
-6. **Cache locally** - Download once and save to avoid repeated requests
-7. **Handle errors gracefully** - Network issues and API limits can occur
-8. **Respect NCBI guidelines** - Don't overwhelm the service
-9. **Use appropriate rettype** - Choose format that matches your needs
-10. **Parse XML carefully** - Structure varies by database and record type
+2. **Set Entrez.tool** for reusable software and register the tool/email pair with NCBI
+3. **Use `NCBI_API_KEY` from the environment** for higher rate limits (10 req/s vs 3 req/s); never hardcode keys
+4. **Close handles** after reading to free resources
+5. **Batch large requests** - Use retstart and retmax for pagination
+6. **Use WebEnv for large downloads** - Store results on server
+7. **Cache locally** - Download once and save to avoid repeated requests
+8. **Handle errors gracefully** - Network issues and API limits can occur
+9. **Respect NCBI guidelines** - Don't overwhelm the service
+10. **Use appropriate rettype** - Choose format that matches your needs
+11. **Parse XML carefully** - Structure varies by database and record type
## Error Handling
diff --git a/skills/biopython/references/sequence_io.md b/skills/biopython/references/sequence_io.md
index a6a5e31d..0f0acdfb 100644
--- a/skills/biopython/references/sequence_io.md
+++ b/skills/biopython/references/sequence_io.md
@@ -92,8 +92,12 @@ Common formats include:
- **embl** - EMBL format
- **swiss** - SwissProt format
- **fasta-2line** - FASTA with sequence on one line
+- **fasta-pearson** - Pearson FASTA with comment lines before the first record
+- **fasta-blast** - BLAST-style FASTA where `#`, `;`, or `!` comment lines are ignored
- **tab** - Simple tab-separated format
+**Biopython 1.87 note:** `format="fasta"` no longer accepts comment lines before the first `>` record. If you need to parse FASTA files with leading comments, use `format="fasta-pearson"` or `format="fasta-blast"` depending on the source convention.
+
### The SeqRecord Object
`SeqRecord` objects combine sequence data with annotations:
diff --git a/skills/matplotlib/SKILL.md b/skills/matplotlib/SKILL.md
index c204004e..3cdc52b4 100644
--- a/skills/matplotlib/SKILL.md
+++ b/skills/matplotlib/SKILL.md
@@ -1,9 +1,14 @@
---
name: matplotlib
description: Low-level plotting library for full customization. Use when you need fine-grained control over every plot element, creating novel plot types, or integrating with specific scientific workflows. Export to PNG/PDF/SVG for publication. For quick statistical plots use seaborn; for interactive plots use plotly; for publication-ready multi-panel figures with journal styling, use scientific-visualization.
+allowed-tools:
+ - Read
+ - Write
+ - Bash
license: https://github.com/matplotlib/matplotlib/tree/main/LICENSE
+compatibility: Requires Python 3.10+ and Matplotlib 3.10.x. Use `uv add matplotlib` in projects; interactive Jupyter widgets require `ipympl`.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -25,6 +30,24 @@ This skill should be used when:
- Working with 3D visualizations
- Integrating plots into Jupyter notebooks or GUI applications
+## Setup
+
+For project work, install Matplotlib with uv:
+
+```bash
+uv add matplotlib
+```
+
+For notebook interactivity:
+
+```bash
+uv add matplotlib ipympl
+```
+
+Then enable the widget backend in Jupyter with `%matplotlib widget` or `%matplotlib ipympl`.
+
+Matplotlib 3.10 requires Python 3.10+ and NumPy 1.23+. Non-interactive file output works through backends such as Agg, PDF, and SVG. For GUI windows, Matplotlib auto-selects an available backend; if `TkAgg` fails in a uv-managed Python, update uv and Python builds with `uv self update` and `uv python upgrade --reinstall`, or install a Qt backend with `uv add pyside6`.
+
## Core Concepts
### The Matplotlib Hierarchy
@@ -89,7 +112,7 @@ ax.legend()
ax.grid(True, alpha=0.3)
# Save and/or display
-plt.savefig('plot.png', dpi=300, bbox_inches='tight')
+fig.savefig('plot.png', dpi=300, bbox_inches='tight')
plt.show()
```
@@ -159,7 +182,7 @@ ax.clabel(contour, inline=True, fontsize=8)
**Box plots** - Statistical distributions
```python
-ax.boxplot([data1, data2, data3], labels=['A', 'B', 'C'])
+ax.boxplot([data1, data2, data3], tick_labels=['A', 'B', 'C'])
```
**Violin plots** - Distribution densities
@@ -209,14 +232,14 @@ For detailed styling options and colormap guidelines, see `references/styling_gu
**Export to various formats:**
```python
# High-resolution PNG for presentations/papers
-plt.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
+fig.savefig('figure.png', dpi=300, bbox_inches='tight', facecolor='white')
# Vector format for publications (scalable)
-plt.savefig('figure.pdf', bbox_inches='tight')
-plt.savefig('figure.svg', bbox_inches='tight')
+fig.savefig('figure.pdf', bbox_inches='tight')
+fig.savefig('figure.svg', bbox_inches='tight')
# Transparent background
-plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
+fig.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
```
**Important parameters:**
@@ -228,8 +251,6 @@ plt.savefig('figure.png', dpi=300, bbox_inches='tight', transparent=True)
### 6. Working with 3D Plots
```python
-from mpl_toolkits.mplot3d import Axes3D
-
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
@@ -303,7 +324,7 @@ def create_analysis_plot(data, title):
# Use the function
fig, ax = create_analysis_plot(my_data, 'My Analysis')
-plt.savefig('analysis.png', dpi=300, bbox_inches='tight')
+fig.savefig('analysis.png', dpi=300, bbox_inches='tight')
```
## Quick Reference Scripts
@@ -315,7 +336,7 @@ Template script demonstrating various plot types with best practices. Use this a
**Usage:**
```bash
-python scripts/plot_template.py
+uv run python scripts/plot_template.py
```
### `style_configurator.py`
@@ -323,7 +344,7 @@ Interactive utility to configure matplotlib style preferences and generate custo
**Usage:**
```bash
-python scripts/style_configurator.py
+uv run python scripts/style_configurator.py
```
## Detailed References
diff --git a/skills/matplotlib/references/api_reference.md b/skills/matplotlib/references/api_reference.md
index 9ca3c619..7b3e19de 100644
--- a/skills/matplotlib/references/api_reference.md
+++ b/skills/matplotlib/references/api_reference.md
@@ -56,7 +56,7 @@ ax = fig.add_subplot(111) # Alternative method
**Statistical plots:**
- `ax.hist(data, bins=10, density=False)` - Histogram
-- `ax.boxplot(data, labels=None)` - Box plot
+- `ax.boxplot(data, tick_labels=None, orientation='vertical')` - Box plot
- `ax.violinplot(data)` - Violin plot
**2D plots:**
@@ -88,7 +88,7 @@ ax = fig.add_subplot(111) # Alternative method
**Ticks:**
- `ax.set_xticks(positions)` - Set x-tick positions
-- `ax.set_xticklabels(labels)` - Set x-tick labels
+- `ax.set_xticks(positions, labels)` - Set x-tick positions and labels together
- `ax.tick_params(axis='both', labelsize=10)` - Customize tick appearance
**Grid and spines:**
@@ -299,8 +299,6 @@ ax5 = fig.add_subplot(gs[2, 2]) # Bottom row, right column
## 3D Plotting
```python
-from mpl_toolkits.mplot3d import Axes3D
-
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
@@ -399,8 +397,7 @@ fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
ax2 = ax1.twinx()
# Remove tick labels
-ax.set_xticklabels([])
-ax.set_yticklabels([])
+ax.tick_params(labelbottom=False, labelleft=False)
# Scientific notation
ax.ticklabel_format(style='scientific', axis='y', scilimits=(0,0))
diff --git a/skills/matplotlib/references/common_issues.md b/skills/matplotlib/references/common_issues.md
index e1304c7b..8e1e220b 100644
--- a/skills/matplotlib/references/common_issues.md
+++ b/skills/matplotlib/references/common_issues.md
@@ -80,7 +80,8 @@ plt.subplots_adjust(left=0.15, right=0.95, top=0.95, bottom=0.15)
plt.savefig('figure.png', bbox_inches='tight')
# Solution 5: Rotate long tick labels
-ax.set_xticklabels(labels, rotation=45, ha='right')
+ax.set_xticks(positions, labels)
+plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
```
### Issue: Colorbar Affects Subplot Size
@@ -198,9 +199,9 @@ ax.hexbin(x, y, gridsize=50, cmap='viridis')
from matplotlib.font_manager import findfont, FontProperties
print(findfont(FontProperties(family='sans-serif')))
-# Solution 2: Rebuild font cache
-import matplotlib.font_manager
-matplotlib.font_manager._rebuild()
+# Solution 2: Check Matplotlib's cache directory, then restart Python
+import matplotlib
+print(matplotlib.get_cachedir())
# Solution 3: Suppress warnings
import warnings
@@ -434,8 +435,6 @@ scatter = ax.scatter(x, y, z, c=z, cmap='viridis')
**Solution:**
```python
-from mpl_toolkits.mplot3d import Axes3D
-
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z)
diff --git a/skills/matplotlib/references/plot_types.md b/skills/matplotlib/references/plot_types.md
index 2aad9aa4..2bedc098 100644
--- a/skills/matplotlib/references/plot_types.md
+++ b/skills/matplotlib/references/plot_types.md
@@ -91,8 +91,7 @@ width = 0.35
ax.bar(x - width/2, values1, width, label='Group 1')
ax.bar(x + width/2, values2, width, label='Group 2')
-ax.set_xticks(x)
-ax.set_xticklabels(categories)
+ax.set_xticks(x, categories)
ax.legend()
```
@@ -168,15 +167,16 @@ plt.colorbar(h[3], ax=ax, label='Counts')
### Box Plot
```python
ax.boxplot([data1, data2, data3],
- labels=['Group A', 'Group B', 'Group C'],
+ tick_labels=['Group A', 'Group B', 'Group C'],
showmeans=True, meanline=True)
ax.set_ylabel('Values')
```
### Horizontal Box Plot
```python
-ax.boxplot([data1, data2, data3], vert=False,
- labels=['Group A', 'Group B', 'Group C'])
+ax.boxplot([data1, data2, data3],
+ orientation='horizontal',
+ tick_labels=['Group A', 'Group B', 'Group C'])
ax.set_xlabel('Values')
```
@@ -185,8 +185,7 @@ ax.set_xlabel('Values')
parts = ax.violinplot([data1, data2, data3],
positions=[1, 2, 3],
showmeans=True, showmedians=True)
-ax.set_xticks([1, 2, 3])
-ax.set_xticklabels(['Group A', 'Group B', 'Group C'])
+ax.set_xticks([1, 2, 3], ['Group A', 'Group B', 'Group C'])
```
## 6. Heatmaps
@@ -220,10 +219,8 @@ im = ax.imshow(corr, cmap='RdBu_r', vmin=-1, vmax=1)
plt.colorbar(im, ax=ax, label='Correlation')
# Set tick labels
-ax.set_xticks(range(len(corr)))
-ax.set_yticks(range(len(corr)))
-ax.set_xticklabels(corr.columns, rotation=45, ha='right')
-ax.set_yticklabels(corr.columns)
+ax.set_xticks(range(len(corr)), corr.columns, rotation=45, ha='right')
+ax.set_yticks(range(len(corr)), corr.columns)
```
## 7. Contour Plots
@@ -304,8 +301,7 @@ angles_closed = np.concatenate((angles, [angles[0]]))
ax = plt.subplot(111, projection='polar')
ax.plot(angles_closed, values_closed, 'o-', linewidth=2)
ax.fill(angles_closed, values_closed, alpha=0.25)
-ax.set_xticks(angles)
-ax.set_xticklabels(categories)
+ax.set_xticks(angles, categories)
```
## 10. Stream and Quiver Plots
@@ -355,8 +351,6 @@ ax.legend()
### 3D Scatter
```python
-from mpl_toolkits.mplot3d import Axes3D
-
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(x, y, z, c=colors, cmap='viridis',
@@ -433,8 +427,7 @@ ax.broken_barh([(10, 20), (50, 50), (120, 30)], (20, 9),
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('Time')
-ax.set_yticks([15, 25])
-ax.set_yticklabels(['Task 1', 'Task 2'])
+ax.set_yticks([15, 25], ['Task 1', 'Task 2'])
```
## 14. Time Series Plots
diff --git a/skills/matplotlib/references/styling_guide.md b/skills/matplotlib/references/styling_guide.md
index 8f9fbaf0..be6cd225 100644
--- a/skills/matplotlib/references/styling_guide.md
+++ b/skills/matplotlib/references/styling_guide.md
@@ -50,7 +50,9 @@ Best for categorical/nominal data without inherent ordering.
**Usage:**
```python
-colors = plt.cm.tab10(np.linspace(0, 1, n_categories))
+import matplotlib as mpl
+
+colors = mpl.colormaps['tab10'](np.linspace(0, 1, n_categories))
for i, category in enumerate(categories):
ax.plot(x, y[i], color=colors[i], label=category)
```
@@ -76,6 +78,7 @@ Best for cyclic data (e.g., phase, angle).
```python
from matplotlib.colors import LinearSegmentedColormap
+import matplotlib as mpl
# From color list
colors = ['blue', 'white', 'red']
@@ -88,15 +91,19 @@ cmap = LinearSegmentedColormap.from_list('custom', colors)
# Use the custom colormap
ax.imshow(data, cmap=cmap)
+
+# Optionally register it by name for reuse
+mpl.colormaps.register(cmap, name='custom')
```
### Discrete Colormaps
```python
import matplotlib.colors as mcolors
+import matplotlib as mpl
# Create discrete colormap from continuous
-cmap = plt.cm.viridis
+cmap = mpl.colormaps['viridis']
bounds = np.linspace(0, 10, 11)
norm = mcolors.BoundaryNorm(bounds, cmap.N)
im = ax.imshow(data, cmap=cmap, norm=norm)
@@ -284,8 +291,10 @@ plt.rcParams['savefig.transparent'] = False
### Named Color Sets
```python
+import matplotlib as mpl
+
# Tableau colors
-tableau_colors = plt.cm.tab10.colors
+tableau_colors = mpl.colormaps['tab10'].colors
# CSS4 colors (subset)
css_colors = ['steelblue', 'coral', 'teal', 'goldenrod', 'crimson']
@@ -309,9 +318,11 @@ plt.rcParams['axes.prop_cycle'] = cycler(color=colors) + cycler(linestyle=['-',
### Palette Generation
```python
+import matplotlib as mpl
+
# Evenly spaced colors from colormap
n_colors = 5
-colors = plt.cm.viridis(np.linspace(0, 1, n_colors))
+colors = mpl.colormaps['viridis'](np.linspace(0, 1, n_colors))
# Use in plot
for i, (x, y) in enumerate(data):
diff --git a/skills/matplotlib/scripts/plot_template.py b/skills/matplotlib/scripts/plot_template.py
index 88721c1a..68ae452e 100644
--- a/skills/matplotlib/scripts/plot_template.py
+++ b/skills/matplotlib/scripts/plot_template.py
@@ -13,6 +13,7 @@ Plot types:
"""
import numpy as np
+import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import argparse
@@ -63,6 +64,7 @@ def generate_sample_data():
def create_line_plot(data, ax=None):
"""Create line plot with best practices."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
@@ -80,13 +82,14 @@ def create_line_plot(data, ax=None):
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
- if ax is None:
+ if created_fig:
return fig
return ax
def create_scatter_plot(data, ax=None):
"""Create scatter plot with color and size variations."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
@@ -107,13 +110,14 @@ def create_scatter_plot(data, ax=None):
cbar = plt.colorbar(scatter, ax=ax)
cbar.set_label('Distance from origin')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_bar_chart(data, ax=None):
"""Create bar chart with error bars and styling."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
@@ -125,28 +129,28 @@ def create_bar_chart(data, ax=None):
capsize=5, alpha=0.8)
# Color bars by value
- colors = plt.cm.viridis(data['bar_values'] / data['bar_values'].max())
+ colors = mpl.colormaps['viridis'](data['bar_values'] / data['bar_values'].max())
for bar, color in zip(bars, colors):
bar.set_facecolor(color)
ax.set_xlabel('Category')
ax.set_ylabel('Values')
ax.set_title('Bar Chart Example')
- ax.set_xticks(x_pos)
- ax.set_xticklabels(data['categories'])
+ ax.set_xticks(x_pos, data['categories'])
ax.grid(True, axis='y', alpha=0.3, linestyle='--')
# Remove top and right spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
- if ax is None:
+ if created_fig:
return fig
return ax
def create_histogram(data, ax=None):
"""Create histogram with density overlay."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
@@ -166,13 +170,14 @@ def create_histogram(data, ax=None):
ax.legend()
ax.grid(True, axis='y', alpha=0.3, linestyle='--')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_heatmap(data, ax=None):
"""Create heatmap with colorbar and annotations."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 8), constrained_layout=True)
@@ -193,13 +198,14 @@ def create_heatmap(data, ax=None):
ax.set_ylabel('Y Index')
ax.set_title('Heatmap Example')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_contour_plot(data, ax=None):
"""Create contour plot with filled contours and labels."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 8), constrained_layout=True)
@@ -223,37 +229,39 @@ def create_contour_plot(data, ax=None):
ax.set_title('Contour Plot Example')
ax.set_aspect('equal')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_box_plot(data, ax=None):
"""Create box plot comparing distributions."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
# Generate multiple distributions
box_data = [np.random.normal(0, std, 100) for std in range(1, 5)]
- bp = ax.boxplot(box_data, labels=['Group 1', 'Group 2', 'Group 3', 'Group 4'],
- patch_artist=True, showmeans=True,
- boxprops=dict(facecolor='lightblue', edgecolor='black'),
- medianprops=dict(color='red', linewidth=2),
- meanprops=dict(marker='D', markerfacecolor='green', markersize=8))
+ ax.boxplot(box_data, tick_labels=['Group 1', 'Group 2', 'Group 3', 'Group 4'],
+ patch_artist=True, showmeans=True,
+ boxprops=dict(facecolor='lightblue', edgecolor='black'),
+ medianprops=dict(color='red', linewidth=2),
+ meanprops=dict(marker='D', markerfacecolor='green', markersize=8))
ax.set_xlabel('Groups')
ax.set_ylabel('Values')
ax.set_title('Box Plot Example')
ax.grid(True, axis='y', alpha=0.3, linestyle='--')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_violin_plot(data, ax=None):
"""Create violin plot showing distribution shapes."""
+ created_fig = ax is None
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6), constrained_layout=True)
@@ -272,19 +280,16 @@ def create_violin_plot(data, ax=None):
ax.set_xlabel('Groups')
ax.set_ylabel('Values')
ax.set_title('Violin Plot Example')
- ax.set_xticks(range(1, 5))
- ax.set_xticklabels(['Group 1', 'Group 2', 'Group 3', 'Group 4'])
+ ax.set_xticks(range(1, 5), ['Group 1', 'Group 2', 'Group 3', 'Group 4'])
ax.grid(True, axis='y', alpha=0.3, linestyle='--')
- if ax is None:
+ if created_fig:
return fig
return ax
def create_3d_plot():
"""Create 3D surface plot."""
- from mpl_toolkits.mplot3d import Axes3D
-
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(111, projection='3d')
diff --git a/skills/matplotlib/scripts/style_configurator.py b/skills/matplotlib/scripts/style_configurator.py
index 1a0aca23..0bcd15a5 100644
--- a/skills/matplotlib/scripts/style_configurator.py
+++ b/skills/matplotlib/scripts/style_configurator.py
@@ -14,10 +14,10 @@ Presets:
"""
import numpy as np
+import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import argparse
-import os
# Predefined style presets
@@ -166,7 +166,7 @@ def create_style_preview(style_dict=None):
bars = ax3.bar(data['categories'], data['bar_values'],
edgecolor='black', linewidth=1)
# Color bars with gradient
- colors = plt.cm.viridis(np.linspace(0.2, 0.8, len(bars)))
+ colors = mpl.colormaps['viridis'](np.linspace(0.2, 0.8, len(bars)))
for bar, color in zip(bars, colors):
bar.set_facecolor(color)
ax3.set_xlabel('Categories')
@@ -299,7 +299,8 @@ def interactive_mode():
print(" 5. Color scheme")
print(" 6. Done, show preview")
- while True:
+ max_customization_steps = 20
+ for _ in range(max_customization_steps):
choice = input("\nSelect option (1-6): ").strip()
if choice == '1':
@@ -332,6 +333,8 @@ def interactive_mode():
elif choice == '6':
break
+ else:
+ print("\nReached customization step limit; showing preview with current settings.")
return style_dict
diff --git a/skills/polars/SKILL.md b/skills/polars/SKILL.md
index c30d10e0..9ec0c23c 100644
--- a/skills/polars/SKILL.md
+++ b/skills/polars/SKILL.md
@@ -1,9 +1,11 @@
---
name: polars
-description: Fast in-memory DataFrame library for datasets that fit in RAM. Use when pandas is too slow but data still fits in memory. Lazy evaluation, parallel execution, Apache Arrow backend. Best for 1-100GB datasets, ETL pipelines, faster pandas replacement. For larger-than-RAM data use dask or vaex.
+description: High-performance DataFrame library for Python ETL, analytics, and pandas migration. Use for expression-based data manipulation with lazy query optimization, parallel execution, streaming out-of-core processing, Arrow interoperability, and optional GPU execution.
license: https://github.com/pola-rs/polars/blob/main/LICENSE
+allowed-tools: Read
+compatibility: Requires Python 3.10+ for polars 1.41.x. Install with uv pip install; optional extras enable Excel, database, cloud, pandas/NumPy, and GPU integrations.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -17,9 +19,14 @@ Polars is a lightning-fast DataFrame library for Python and Rust built on Apache
### Installation and Basic Usage
-Install Polars:
-```python
-uv pip install polars
+Install the current stable Polars release verified during this refresh:
+```bash
+uv pip install "polars==1.41.2"
+```
+
+Install optional integrations only when needed:
+```bash
+uv pip install "polars[excel,database,fsspec,pandas,numpy]==1.41.2"
```
Basic DataFrame creation and operations:
@@ -267,7 +274,7 @@ pl.concat([df1, df2], how="diagonal")
Reshape data:
```python
# Pivot (wide format)
-df.pivot(values="sales", index="date", columns="product")
+df.pivot(on="product", values="sales", index="date")
# Unpivot (long format)
df.unpivot(index="id", on=["col1", "col2"])
@@ -332,7 +339,7 @@ For comprehensive migration guide, load `references/pandas_migration.md`.
3. **Use streaming for very large data:**
```python
- lf.collect(streaming=True)
+ lf.collect(engine="streaming")
```
4. **Select only needed columns early:**
diff --git a/skills/polars/references/best_practices.md b/skills/polars/references/best_practices.md
index 0585ed6d..b4c4f13b 100644
--- a/skills/polars/references/best_practices.md
+++ b/skills/polars/references/best_practices.md
@@ -81,7 +81,7 @@ Enable streaming for datasets larger than RAM:
```python
# Streaming mode processes data in chunks
lf = pl.scan_parquet("very_large.parquet")
-result = lf.filter(pl.col("value") > 100).collect(streaming=True)
+result = lf.filter(pl.col("value") > 100).collect(engine="streaming")
# Or use sink for direct streaming writes
lf.filter(pl.col("value") > 100).sink_parquet("output.parquet")
@@ -98,7 +98,7 @@ df = pl.read_csv("data.csv")
# Good: Specify optimal types
df = pl.read_csv(
"data.csv",
- dtypes={
+ schema_overrides={
"id": pl.UInt32, # Instead of Int64 if values fit
"category": pl.Categorical, # For low-cardinality strings
"date": pl.Date, # Instead of String
@@ -151,8 +151,8 @@ combined = pl.concat([df1, df2, df3], rechunk=True)
```python
df.with_columns(
status=pl.when(pl.col("age") >= 18)
- .then("adult")
- .otherwise("minor")
+ .then(pl.lit("adult"))
+ .otherwise(pl.lit("minor"))
)
```
@@ -160,14 +160,14 @@ df.with_columns(
```python
df.with_columns(
grade=pl.when(pl.col("score") >= 90)
- .then("A")
+ .then(pl.lit("A"))
.when(pl.col("score") >= 80)
- .then("B")
+ .then(pl.lit("B"))
.when(pl.col("score") >= 70)
- .then("C")
+ .then(pl.lit("C"))
.when(pl.col("score") >= 60)
- .then("D")
- .otherwise("F")
+ .then(pl.lit("D"))
+ .otherwise(pl.lit("F"))
)
```
@@ -177,12 +177,12 @@ df.with_columns(
category=pl.when(
(pl.col("revenue") > 1000000) & (pl.col("customers") > 100)
)
- .then("enterprise")
+ .then(pl.lit("enterprise"))
.when(
(pl.col("revenue") > 100000) | (pl.col("customers") > 50)
)
- .then("business")
- .otherwise("starter")
+ .then(pl.lit("business"))
+ .otherwise(pl.lit("starter"))
)
```
@@ -245,14 +245,16 @@ df.select(pl.col(".*revenue.*"))
**By type:**
```python
+import polars.selectors as cs
+
# All numeric columns
-df.select(pl.col(pl.NUMERIC_DTYPES))
+df.select(cs.numeric())
# All string columns
-df.select(pl.col(pl.Utf8))
+df.select(cs.string())
# Multiple types
-df.select(pl.col(pl.NUMERIC_DTYPES, pl.Boolean))
+df.select(cs.numeric() | cs.boolean())
```
**Exclude columns:**
@@ -377,7 +379,7 @@ df = pl.read_csv("data.csv")
# Good: Specify types for correctness and performance
df = pl.read_csv(
"data.csv",
- dtypes={"id": pl.Int64, "date": pl.Date, "category": pl.Categorical}
+ schema_overrides={"id": pl.Int64, "date": pl.Date, "category": pl.Categorical}
)
```
@@ -429,7 +431,7 @@ print(lf.explain()) # See query plan
lf = pl.scan_parquet("data.parquet")
# 2. Stream results
-result = lf.collect(streaming=True)
+result = lf.collect(engine="streaming")
# 3. Select only needed columns
lf = lf.select("col1", "col2")
@@ -478,7 +480,7 @@ print(df.schema)
# Ensure schema matches expectation
expected_schema = {
"id": pl.Int64,
- "name": pl.Utf8,
+ "name": pl.String,
"date": pl.Date
}
@@ -538,7 +540,7 @@ lf = pl.scan_parquet("data/*.parquet") # Parallel reading
# 3. Specify schema when known
lf = pl.scan_csv(
"data.csv",
- dtypes={"id": pl.Int64, "date": pl.Date}
+ schema_overrides={"id": pl.Int64, "date": pl.Date}
)
# 4. Use predicate pushdown
@@ -573,10 +575,10 @@ df.write_parquet(
# Define reusable expressions
age_group = (
pl.when(pl.col("age") < 18)
- .then("minor")
+ .then(pl.lit("minor"))
.when(pl.col("age") < 65)
- .then("adult")
- .otherwise("senior")
+ .then(pl.lit("adult"))
+ .otherwise(pl.lit("senior"))
)
revenue_per_customer = pl.col("revenue") / pl.col("customer_count")
diff --git a/skills/polars/references/core_concepts.md b/skills/polars/references/core_concepts.md
index e3a0e56f..d983fd93 100644
--- a/skills/polars/references/core_concepts.md
+++ b/skills/polars/references/core_concepts.md
@@ -78,11 +78,13 @@ df.select(pl.all() * 2)
**Pattern matching:**
```python
+import polars.selectors as cs
+
# All columns ending with "_value"
df.select(pl.col("^.*_value$") * 100)
# All numeric columns
-df.select(pl.col(pl.NUMERIC_DTYPES) + 1)
+df.select(cs.numeric() + 1)
```
**Exclude patterns:**
@@ -148,7 +150,7 @@ Convert between types explicitly:
df.select(
pl.col("age").cast(pl.Float64),
pl.col("date_string").str.strptime(pl.Date, "%Y-%m-%d"),
- pl.col("id").cast(pl.Utf8)
+ pl.col("id").cast(pl.String)
)
```
@@ -271,7 +273,7 @@ Process data larger than memory:
```python
# Enable streaming for very large datasets
lf = pl.scan_csv("very_large.csv")
-result = lf.filter(pl.col("age") > 25).collect(streaming=True)
+result = lf.filter(pl.col("age") > 25).collect(engine="streaming")
```
**Streaming benefits:**
@@ -358,7 +360,7 @@ Polars enforces strict typing:
# Must cast explicitly
df.with_columns(
- pl.col("int_col").cast(pl.Utf8) + "_suffix"
+ pl.col("int_col").cast(pl.String) + "_suffix"
)
```
diff --git a/skills/polars/references/io_guide.md b/skills/polars/references/io_guide.md
index bbb9dc92..dbd450ae 100644
--- a/skills/polars/references/io_guide.md
+++ b/skills/polars/references/io_guide.md
@@ -21,7 +21,7 @@ df = pl.read_csv(
columns=["col1", "col2"], # Select specific columns
n_rows=1000, # Read only first 1000 rows
skip_rows=10, # Skip first 10 rows
- dtypes={"col1": pl.Int64, "col2": pl.Utf8}, # Specify types
+ schema_overrides={"col1": pl.Int64, "col2": pl.String}, # Specify types
null_values=["NA", "null", ""], # Define null values
encoding="utf-8",
ignore_errors=False
@@ -265,13 +265,13 @@ lf = pl.scan_parquet("s3://bucket/path/*.parquet")
# Write to S3
df.write_parquet("s3://bucket/path/output.parquet")
-# With credentials
-import os
-os.environ["AWS_ACCESS_KEY_ID"] = "your_key"
-os.environ["AWS_SECRET_ACCESS_KEY"] = "your_secret"
-os.environ["AWS_REGION"] = "us-west-2"
-
-df = pl.read_parquet("s3://bucket/file.parquet")
+# Prefer cloud profiles, IAM roles, or Polars credential providers over
+# hardcoding secrets in scripts.
+lf = pl.scan_parquet(
+ "s3://bucket/file.parquet",
+ credential_provider=pl.CredentialProviderAWS(profile_name="analytics"),
+)
+df = lf.collect()
```
### Azure Blob Storage
@@ -283,9 +283,15 @@ df = pl.read_parquet("az://container/path/file.parquet")
# Write to Azure
df.write_parquet("az://container/path/output.parquet")
-# With credentials
-os.environ["AZURE_STORAGE_ACCOUNT_NAME"] = "account"
-os.environ["AZURE_STORAGE_ACCOUNT_KEY"] = "key"
+# Prefer managed identity or an Azure SDK credential provider.
+from azure.identity import DefaultAzureCredential
+
+df = pl.read_parquet(
+ "abfss://[email protected]/path/file.parquet",
+ credential_provider=pl.CredentialProviderAzure(
+ credential=DefaultAzureCredential()
+ ),
+)
```
### Google Cloud Storage (GCS)
@@ -297,8 +303,9 @@ df = pl.read_parquet("gs://bucket/path/file.parquet")
# Write to GCS
df.write_parquet("gs://bucket/path/output.parquet")
-# With credentials
-os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/to/credentials.json"
+# Prefer Application Default Credentials or workload identity configured
+# outside the script.
+df = pl.read_parquet("gs://bucket/path/file.parquet")
```
## Google BigQuery
@@ -429,11 +436,11 @@ For datasets larger than memory, use lazy mode with streaming:
```python
# Streaming mode
lf = pl.scan_csv("very_large.csv")
-result = lf.filter(pl.col("value") > 100).collect(streaming=True)
+result = lf.filter(pl.col("value") > 100).collect(engine="streaming")
# Streaming with multiple files
lf = pl.scan_parquet("data/*.parquet")
-result = lf.group_by("category").agg(pl.col("value").sum()).collect(streaming=True)
+result = lf.group_by("category").agg(pl.col("value").sum()).collect(engine="streaming")
```
## Best Practices
@@ -478,7 +485,7 @@ result = (
)
# 3. Use streaming for very large data
-result = lf.filter(...).select(...).collect(streaming=True)
+result = lf.filter(...).select(...).collect(engine="streaming")
# 4. Read only needed rows during development
df = pl.read_csv("large.csv", n_rows=10000) # Sample for testing
@@ -504,7 +511,7 @@ lf.sink_parquet("output.parquet") # Streaming write
# 1. Specify dtypes when reading CSV
df = pl.read_csv(
"data.csv",
- dtypes={"id": pl.Int64, "name": pl.Utf8} # Avoids inference
+ schema_overrides={"id": pl.Int64, "name": pl.String} # Avoids inference
)
# 2. Use appropriate compression
@@ -544,14 +551,14 @@ else:
schema = pl.read_csv("data.csv", n_rows=1000).schema
# Use inferred schema for full read
-df = pl.read_csv("data.csv", dtypes=schema)
+df = pl.read_csv("data.csv", schema=schema)
# Define schema explicitly
schema = {
"id": pl.Int64,
- "name": pl.Utf8,
+ "name": pl.String,
"date": pl.Date,
"value": pl.Float64
}
-df = pl.read_csv("data.csv", dtypes=schema)
+df = pl.read_csv("data.csv", schema=schema)
```
diff --git a/skills/polars/references/operations.md b/skills/polars/references/operations.md
index 40441f58..87f7ca63 100644
--- a/skills/polars/references/operations.md
+++ b/skills/polars/references/operations.md
@@ -17,11 +17,13 @@ df.select(pl.col("name"), pl.col("age"))
**Pattern-based selection:**
```python
+import polars.selectors as cs
+
# All columns starting with "sales_"
df.select(pl.col("^sales_.*$"))
# All numeric columns
-df.select(pl.col(pl.NUMERIC_DTYPES))
+df.select(cs.numeric())
# All columns except specific ones
df.select(pl.all().exclude("id", "timestamp"))
@@ -384,19 +386,19 @@ df.sort(
# Basic conditional
df.with_columns(
status=pl.when(pl.col("age") >= 18)
- .then("adult")
- .otherwise("minor")
+ .then(pl.lit("adult"))
+ .otherwise(pl.lit("minor"))
)
# Multiple conditions
df.with_columns(
category=pl.when(pl.col("score") >= 90)
- .then("A")
+ .then(pl.lit("A"))
.when(pl.col("score") >= 80)
- .then("B")
+ .then(pl.lit("B"))
.when(pl.col("score") >= 70)
- .then("C")
- .otherwise("F")
+ .then(pl.lit("C"))
+ .otherwise(pl.lit("F"))
)
# Conditional computation
@@ -512,7 +514,7 @@ df.filter(pl.col("date").dt.month().is_in([6, 7, 8])) # Summer months
```python
# Create list column
df.with_columns(
- items_list=pl.col("item1", "item2", "item3").to_list()
+ items_list=pl.concat_list("item1", "item2", "item3")
)
# List operations
@@ -527,10 +529,8 @@ df.with_columns(
# Explode lists to rows
df.explode("items")
-# Filter list elements
-df.with_columns(
- filtered=pl.col("items").list.eval(pl.element() > 10)
-)
+# For element-wise list filtering, use Polars' native list-expression
+# methods with pl.element(); avoid Python callbacks in hot paths.
```
## Struct Operations
diff --git a/skills/polars/references/pandas_migration.md b/skills/polars/references/pandas_migration.md
index aa5fd240..9ab9d3c5 100644
--- a/skills/polars/references/pandas_migration.md
+++ b/skills/polars/references/pandas_migration.md
@@ -146,7 +146,7 @@ df.with_columns(
| Operation | Pandas | Polars |
|-----------|--------|--------|
-| Pivot | `df.pivot(index="a", columns="b", values="c")` | `df.pivot(values="c", index="a", columns="b")` |
+| Pivot | `df.pivot(index="a", columns="b", values="c")` | `df.pivot(on="b", values="c", index="a")` |
| Melt | `df.melt(id_vars="id")` | `df.unpivot(index="id")` |
### I/O Operations
@@ -258,10 +258,10 @@ df["category"] = np.where(
```python
df = df.with_columns(
category=pl.when(pl.col("value") > 100)
- .then("high")
+ .then(pl.lit("high"))
.when(pl.col("value") > 50)
- .then("medium")
- .otherwise("low")
+ .then(pl.lit("medium"))
+ .otherwise(pl.lit("low"))
)
```
diff --git a/skills/polars/references/transformations.md b/skills/polars/references/transformations.md
index af57f1ce..70d07b9e 100644
--- a/skills/polars/references/transformations.md
+++ b/skills/polars/references/transformations.md
@@ -20,10 +20,10 @@ result = df1.join(df2, on="id", how="inner")
result = df1.join(df2, on="id", how="left")
```
-**Outer Join (union):**
+**Full Join (union):**
```python
# Keep all rows from both DataFrames
-result = df1.join(df2, on="id", how="outer")
+result = df1.join(df2, on="id", how="full")
```
**Cross Join (Cartesian product):**
@@ -230,9 +230,9 @@ df = pl.DataFrame({
# Pivot: products become columns
pivoted = df.pivot(
+ on="product",
values="sales",
- index="date",
- columns="product"
+ index="date"
)
# Result:
# date | A | B
@@ -253,9 +253,9 @@ df = pl.DataFrame({
# Aggregate duplicates
pivoted = df.pivot(
+ on="product",
values="sales",
index="date",
- columns="product",
aggregate_function="sum" # or "mean", "max", "min", etc.
)
```
@@ -271,9 +271,9 @@ df = pl.DataFrame({
})
pivoted = df.pivot(
+ on="product",
values="sales",
- index=["region", "date"],
- columns="product"
+ index=["region", "date"]
)
```
@@ -405,7 +405,7 @@ wide = pl.DataFrame({
long = wide.unpivot(index="id", on=["A", "B"])
# Back to wide (maybe with transformations)
-wide_again = long.pivot(values="value", index="id", columns="variable")
+wide_again = long.pivot(on="variable", values="value", index="id")
```
### Pattern 2: Nested to Flat
@@ -442,7 +442,7 @@ result = (
sales
.group_by("date", "product")
.agg(pl.col("sales").sum())
- .pivot(values="sales", index="date", columns="product")
+ .pivot(on="product", values="sales", index="date")
)
```
@@ -470,7 +470,7 @@ result = (
metric=pl.col("variable").str.extract(r"Q[0-9]_(.*)", 1)
)
.drop("variable")
- .pivot(values="value", index=["id", "quarter"], columns="metric")
+ .pivot(on="metric", values="value", index=["id", "quarter"])
)
```
@@ -545,5 +545,5 @@ orders.join(customers, on="customer_id").join(products, on="product_id")
```python
# Pivot for reporting
-sales.pivot(values="amount", index="month", columns="product")
+sales.pivot(on="product", values="amount", index="month")
```
diff --git a/skills/pymc/SKILL.md b/skills/pymc/SKILL.md
index a6b57be6..432462bd 100644
--- a/skills/pymc/SKILL.md
+++ b/skills/pymc/SKILL.md
@@ -1,9 +1,11 @@
---
name: pymc
description: Bayesian modeling with PyMC. Build hierarchical models, MCMC (NUTS), variational inference, LOO/WAIC comparison, posterior checks, for probabilistic programming and inference.
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.12+ and PyMC 6.0.1-compatible dependencies. Install reproducible environments with `uv pip install "pymc[nutpie]==6.0.1"`; optional NumPyro or BlackJAX samplers require separately pinned JAX-compatible dependencies.
license: Apache License, Version 2.0
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -11,7 +13,17 @@ metadata:
## Overview
-PyMC is a Python library for Bayesian modeling and probabilistic programming. Build, fit, validate, and compare Bayesian models using PyMC's modern API (version 5.x+), including hierarchical models, MCMC sampling (NUTS), variational inference, and model comparison (LOO, WAIC).
+PyMC is a Python library for Bayesian modeling and probabilistic programming. Build, fit, validate, and compare Bayesian models using PyMC's modern API (version 6.x+), including hierarchical models, MCMC sampling (NUTS), variational inference, posterior predictive checks, and model comparison (LOO, WAIC).
+
+## Current Version and Setup
+
+PyMC 6.0.1 is the current stable release as of June 2026. It requires Python 3.12+, uses PyTensor 3 as the computational graph backend, and defaults to compiled backends such as Numba. For reproducible local environments, pin the version:
+
+```bash
+uv pip install "pymc[nutpie]==6.0.1"
+```
+
+The `nutpie` extra enables the faster Rust/Numba NUTS implementation. If using NumPyro or BlackJAX, install those optional sampler dependencies in the same environment and pin them in the project lockfile.
## When to Use This Skill
@@ -61,16 +73,19 @@ coords = {
}
with pm.Model(coords=coords) as model:
+ # Mutable data container so prediction data can be swapped later
+ X_data = pm.Data('X_scaled', X_scaled, dims=('obs_id', 'predictors'))
+
# Priors
alpha = pm.Normal('alpha', mu=0, sigma=1)
beta = pm.Normal('beta', mu=0, sigma=1, dims='predictors')
sigma = pm.HalfNormal('sigma', sigma=1)
# Linear predictor
- mu = alpha + pm.math.dot(X_scaled, beta)
+ mu = alpha + pm.math.dot(X_data, beta)
- # Likelihood
- y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, dims='obs_id')
+ # Tie the observed variable's shape to X_data for out-of-sample prediction
+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=X_data.shape[0], dims='obs_id')
```
**Key practices:**
@@ -85,7 +100,7 @@ with pm.Model(coords=coords) as model:
```python
with model:
- prior_pred = pm.sample_prior_predictive(samples=1000, random_seed=42)
+ prior_pred = pm.sample_prior_predictive(draws=1000, random_seed=42)
# Visualize
az.plot_ppc(prior_pred, group='prior')
@@ -120,6 +135,7 @@ with model:
- `chains=4`: Run 4 chains for convergence checking
- `target_accept=0.9`: Higher for difficult posteriors (0.95-0.99)
- Include `log_likelihood=True` for model comparison
+- If using PyMC 6 sampler-specific kwargs, avoid deprecated `nuts_sampler_kwargs`; pass explicit NUTS kwargs through `nuts={...}` when needed
### 5. Check Diagnostics
@@ -179,16 +195,17 @@ X_new = ... # New predictor values
X_new_scaled = (X_new - X_mean) / X_std
with model:
- pm.set_data({'X_scaled': X_new_scaled})
+ pm.set_data({'X_scaled': X_new_scaled}, coords={'obs_id': np.arange(len(X_new_scaled))})
post_pred = pm.sample_posterior_predictive(
- idata.posterior,
+ idata,
var_names=['y_obs'],
+ predictions=True,
random_seed=42
)
# Extract prediction intervals
-y_pred_mean = post_pred.posterior_predictive['y_obs'].mean(dim=['chain', 'draw'])
-y_pred_hdi = az.hdi(post_pred.posterior_predictive, var_names=['y_obs'])
+y_pred_mean = post_pred.predictions['y_obs'].mean(dim=['chain', 'draw'])
+y_pred_hdi = az.hdi(post_pred.predictions, var_names=['y_obs'])
```
## Common Model Patterns
@@ -339,7 +356,8 @@ averaged_pred, weights = model_averaging(models, var_name='y_obs')
- `pm.Uniform('p', lower=0, upper=1)` - Non-informative (use sparingly)
**Correlation matrices**:
-- `pm.LKJCorr('corr', n=n_vars, eta=2)` - eta=1 uniform, eta>1 prefers identity
+- `pm.LKJCholeskyCov('chol', n=n_vars, eta=2, sd_dist=pm.HalfNormal.dist(1))` - Preferred covariance prior
+- `pm.LKJCorr('corr', n=n_vars, eta=2)` - Correlation-only prior; eta=1 uniform, eta>1 prefers identity
### For Likelihoods
@@ -351,6 +369,7 @@ averaged_pred, weights = model_averaging(models, var_name='y_obs')
- `pm.Poisson('y', mu=lambda)` - Equidispersed counts
- `pm.NegativeBinomial('y', mu=mu, alpha=alpha)` - Overdispersed counts
- `pm.ZeroInflatedPoisson('y', psi=psi, mu=mu)` - Excess zeros
+- `pm.HurdleNegativeBinomial('y', psi=psi, mu=mu, alpha=alpha)` - Excess zeros plus overdispersion
**Binary outcomes**:
- `pm.Bernoulli('y', p=p)` or `pm.Bernoulli('y', logit_p=logit_p)`
@@ -390,8 +409,8 @@ with model:
approx = pm.fit(n=20000, method='advi')
# Use for initialization
- start = approx.sample(return_inferencedata=False)[0]
- idata = pm.sample(start=start)
+ initvals = approx.sample(return_inferencedata=False)[0]
+ idata = pm.sample(initvals=initvals)
```
**Trade-offs:**
@@ -557,13 +576,13 @@ compare_models({'m1': idata1, 'm2': idata2}, ic='loo')
### Predictions
```python
with model:
- pm.set_data({'X': X_new})
- pred = pm.sample_posterior_predictive(idata.posterior)
+ pm.set_data({'X_data': X_new})
+ pred = pm.sample_posterior_predictive(idata, predictions=True)
```
## Additional Notes
-- PyMC integrates with ArviZ for visualization and diagnostics
+- PyMC integrates with ArviZ for visualization and diagnostics; PyMC 6 / ArviZ 1 use xarray `DataTree` while retaining familiar groups such as `.posterior` and `.posterior_predictive`
- Use `pm.model_to_graphviz(model)` to visualize model structure
- Save results with `idata.to_netcdf('results.nc')`
- Load with `az.from_netcdf('results.nc')`
diff --git a/skills/pymc/assets/hierarchical_model_template.py b/skills/pymc/assets/hierarchical_model_template.py
index d6215de4..dfd277ac 100644
--- a/skills/pymc/assets/hierarchical_model_template.py
+++ b/skills/pymc/assets/hierarchical_model_template.py
@@ -86,8 +86,8 @@ with pm.Model(coords=coords) as hierarchical_model:
# Observation noise
sigma = pm.HalfNormal('sigma', sigma=5)
- # Likelihood
- y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, dims='obs')
+ # Likelihood; tie shape to X_data so prediction data can have a new row count
+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=X_data.shape[0], dims='obs')
print("Model built successfully!")
print(f"Groups: {n_groups}")
@@ -99,7 +99,7 @@ print(f"Observations: {n_obs}")
print("\nRunning prior predictive check...")
with hierarchical_model:
- prior_pred = pm.sample_prior_predictive(samples=500, random_seed=42)
+ prior_pred = pm.sample_prior_predictive(draws=500, random_seed=42)
# Visualize prior predictions
fig, ax = plt.subplots(figsize=(10, 6))
@@ -171,11 +171,9 @@ else:
print("\n✓ No divergences")
# Trace plots for hyperparameters
-fig, axes = plt.subplots(5, 2, figsize=(12, 12))
-az.plot_trace(
+az.plot_trace_dist(
idata,
var_names=['mu_alpha', 'sigma_alpha', 'mu_beta', 'sigma_beta', 'sigma'],
- axes=axes
)
plt.tight_layout()
plt.savefig('hierarchical_trace_plots.png', dpi=300, bbox_inches='tight')
@@ -282,15 +280,16 @@ new_X = np.array([-2, -1, 0, 1, 2])
new_groups = np.array([0, 2, 4, 6, 8]) # Select some groups
with hierarchical_model:
- pm.set_data({'X_data': new_X, 'groups_data': new_groups, 'obs': np.arange(len(new_X))})
+ pm.set_data({'X_data': new_X, 'groups_data': new_groups}, coords={'obs': np.arange(len(new_X))})
post_pred = pm.sample_posterior_predictive(
- idata.posterior,
+ idata,
var_names=['y_obs'],
+ predictions=True,
random_seed=42
)
-y_pred_samples = post_pred.posterior_predictive['y_obs']
+y_pred_samples = post_pred.predictions['y_obs']
y_pred_mean = y_pred_samples.mean(dim=['chain', 'draw']).values
y_pred_hdi = az.hdi(y_pred_samples, hdi_prob=0.95).values
diff --git a/skills/pymc/assets/linear_regression_template.py b/skills/pymc/assets/linear_regression_template.py
index 63d47e88..32a53647 100644
--- a/skills/pymc/assets/linear_regression_template.py
+++ b/skills/pymc/assets/linear_regression_template.py
@@ -51,6 +51,9 @@ coords = {
}
with pm.Model(coords=coords) as linear_model:
+ # Data container allows out-of-sample prediction with pm.set_data
+ X_data = pm.Data('X_scaled', X_scaled, dims=('obs_id', 'predictors'))
+
# Priors
# TODO: Adjust prior parameters based on your domain knowledge
alpha = pm.Normal('alpha', mu=0, sigma=1)
@@ -58,10 +61,10 @@ with pm.Model(coords=coords) as linear_model:
sigma = pm.HalfNormal('sigma', sigma=1)
# Linear predictor
- mu = alpha + pm.math.dot(X_scaled, beta)
+ mu = alpha + pm.math.dot(X_data, beta)
- # Likelihood
- y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, dims='obs_id')
+ # Tie observed shape to X_data so predictions can use a new row count
+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=X_data.shape[0], dims='obs_id')
# =============================================================================
# 3. PRIOR PREDICTIVE CHECK
@@ -69,7 +72,7 @@ with pm.Model(coords=coords) as linear_model:
print("Running prior predictive check...")
with linear_model:
- prior_pred = pm.sample_prior_predictive(samples=1000, random_seed=42)
+ prior_pred = pm.sample_prior_predictive(draws=1000, random_seed=42)
# Visualize prior predictions
fig, ax = plt.subplots(figsize=(10, 6))
@@ -138,8 +141,7 @@ else:
print("\n✓ No divergences")
# Trace plots
-fig, axes = plt.subplots(len(['alpha', 'beta', 'sigma']), 2, figsize=(12, 8))
-az.plot_trace(idata, var_names=['alpha', 'beta', 'sigma'], axes=axes)
+az.plot_trace_dist(idata, var_names=['alpha', 'beta', 'sigma'])
plt.tight_layout()
plt.savefig('trace_plots.png', dpi=300, bbox_inches='tight')
print("\nTrace plots saved to 'trace_plots.png'")
@@ -203,16 +205,17 @@ X_new_scaled = (X_new - X_mean) / X_std
# Update model data and predict
with linear_model:
- pm.set_data({'X_scaled': X_new_scaled, 'obs_id': np.arange(len(X_new))})
+ pm.set_data({'X_scaled': X_new_scaled}, coords={'obs_id': np.arange(len(X_new))})
post_pred = pm.sample_posterior_predictive(
- idata.posterior,
+ idata,
var_names=['y_obs'],
+ predictions=True,
random_seed=42
)
# Extract predictions
-y_pred_samples = post_pred.posterior_predictive['y_obs']
+y_pred_samples = post_pred.predictions['y_obs']
y_pred_mean = y_pred_samples.mean(dim=['chain', 'draw']).values
y_pred_hdi = az.hdi(y_pred_samples, hdi_prob=0.95).values
@@ -228,7 +231,7 @@ for i in range(len(X_new)):
# 9. SAVE RESULTS
# =============================================================================
-# Save InferenceData
+# Save posterior data tree
idata.to_netcdf('linear_regression_results.nc')
print("\nResults saved to 'linear_regression_results.nc'")
diff --git a/skills/pymc/references/distributions.md b/skills/pymc/references/distributions.md
index 2d9e314a..dffde660 100644
--- a/skills/pymc/references/distributions.md
+++ b/skills/pymc/references/distributions.md
@@ -62,6 +62,10 @@ Continuous distributions define probability densities over real-valued domains.
- Support: (-∞, ∞)
- Common uses: Heavy-tailed alternative to normal
+**`pm.HalfStudentT(name, nu, sigma)`**
+- Positive half-Student-t distribution
+- Common uses: Heavy-tailed prior for scale parameters
+
### Specialized Continuous Distributions
**`pm.Laplace(name, mu, b)`** - Laplace (double exponential) distribution
@@ -90,12 +94,16 @@ Continuous distributions define probability densities over real-valued domains.
**`pm.Gumbel(name, mu, beta)`** - Gumbel distribution for extreme values
+**`pm.PolyaGamma(name, h, z)`** - Polya-gamma distribution for data augmentation patterns
+
**`pm.Rice(name, nu, sigma)`** - Rice (Rician) distribution
**`pm.Moyal(name, mu, sigma)`** - Moyal distribution
**`pm.Kumaraswamy(name, a, b)`** - Kumaraswamy distribution (Beta alternative)
+**`pm.Wald(name, mu, lam)`** - Wald / inverse Gaussian distribution
+
**`pm.Interpolated(name, x_points, pdf_points)`** - Custom distribution from interpolation
## Discrete Distributions
@@ -180,6 +188,10 @@ Multivariate distributions define joint probability distributions over vector-va
- Parameters: `n` (number of trials), `p` (probability vector)
- Common uses: Count data across multiple categories
+**`pm.DirichletMultinomial(name, n, a)`**
+- Dirichlet-multinomial distribution
+- Common uses: Overdispersed categorical counts
+
**`pm.MvStudentT(name, nu, mu, cov)`**
- Multivariate Student's t-distribution
- Parameters: `nu` (degrees of freedom), `mu` (location), `cov` (scale matrix)
@@ -191,10 +203,18 @@ Multivariate distributions define joint probability distributions over vector-va
**`pm.LKJCholeskyCov(name, n, eta, sd_dist)`** - LKJ prior with Cholesky decomposition
-**`pm.Wishart(name, nu, V)`** - Wishart distribution (for covariance matrices)
+**`pm.OrderedMultinomial(name, eta, cutpoints, n)`** - Ordered multinomial outcomes
+
+**`pm.StickBreakingWeights(name, alpha, K)`** - Stick-breaking weights for mixture models
+
+**`pm.ZeroSumNormal(name, sigma)`** - Normal prior constrained to sum to zero
+
+**`pm.Wishart(name, nu, V)`** - Wishart distribution (for covariance matrices; prefer LKJ-based priors for most covariance models)
**`pm.InverseWishart(name, nu, V)`** - Inverse Wishart distribution
+**`pm.WishartBartlett(name, S, nu)`** - Wishart with Bartlett decomposition
+
**`pm.MatrixNormal(name, mu, rowcov, colcov)`** - Matrix normal distribution
**`pm.KroneckerNormal(name, mu, covs, sigma)`** - Kronecker-structured normal
@@ -226,6 +246,8 @@ Mixture distributions combine multiple component distributions.
**`pm.HurdlePoisson(name, psi, mu)`** - Hurdle Poisson (two-part model)
+**`pm.HurdleNegativeBinomial(name, psi, mu, alpha)`** - Hurdle negative binomial for overdispersed counts with structural zeros
+
**`pm.HurdleGamma(name, psi, alpha, beta)`** - Hurdle gamma
**`pm.HurdleLogNormal(name, psi, mu, sigma)`** - Hurdle log-normal
@@ -247,6 +269,9 @@ Distributions designed for temporal data and sequential modeling.
**`pm.MvGaussianRandomWalk(name, mu, cov, init_dist)`**
- Multivariate Gaussian random walk
+**`pm.MvStudentTRandomWalk(name, nu, mu, cov, init_dist)`**
+- Heavy-tailed multivariate random walk
+
**`pm.GARCH11(name, omega, alpha_1, beta_1)`**
- GARCH(1,1) volatility model
- Common uses: Financial time series, volatility modeling
@@ -295,7 +320,7 @@ Distributions designed for temporal data and sequential modeling.
2. **Probabilities**: Use `Beta` or `Uniform(0, 1)`
3. **Unbounded parameters**: Use `Normal` or `StudentT` (for robustness)
4. **Positive parameters**: Use `LogNormal`, `Gamma`, or `Exponential`
-5. **Correlation matrices**: Use `LKJCorr`
+5. **Correlation/covariance matrices**: Prefer `LKJCholeskyCov` for covariance models; use `LKJCorr` when only correlations are needed
6. **Count data**: Use `Poisson` or `NegativeBinomial` (for overdispersion)
### Shape Broadcasting
diff --git a/skills/pymc/references/sampling_inference.md b/skills/pymc/references/sampling_inference.md
index 53d6102a..f55aad91 100644
--- a/skills/pymc/references/sampling_inference.md
+++ b/skills/pymc/references/sampling_inference.md
@@ -17,10 +17,12 @@ The main interface for MCMC sampling in PyMC.
- `cores`: Number of CPU cores to use (default: all available)
- `target_accept`: Target acceptance rate for step size tuning (default: 0.8, increase to 0.9-0.95 for difficult posteriors)
- `random_seed`: Random seed for reproducibility
-- `return_inferencedata`: Return ArviZ InferenceData object (default: True)
-- `idata_kwargs`: Additional kwargs for InferenceData creation (e.g., `{"log_likelihood": True}` for model comparison)
+- `return_inferencedata`: Return an xarray `DataTree` object in PyMC 6 / ArviZ 1 (default: True)
+- `idata_kwargs`: Additional kwargs for data tree creation (e.g., `{"log_likelihood": True}` for model comparison)
+- `nuts_sampler`: Optional NUTS implementation: `"pymc"`, `"nutpie"`, `"blackjax"`, or `"numpyro"`
+- `backend`: Optional computational backend such as `"numba"`, `"c"`, or `"jax"`
-**Returns:** InferenceData object containing posterior samples, sampling statistics, and diagnostics
+**Returns:** ArviZ-compatible `DataTree` containing posterior samples, sampling statistics, and diagnostics
**Example:**
```python
@@ -29,6 +31,8 @@ with pm.Model() as model:
idata = pm.sample(draws=2000, tune=1000, chains=4, target_accept=0.9)
```
+For PyMC 6, avoid deprecated `nuts_sampler_kwargs`; pass sampler-specific settings through explicit sampler keyword dictionaries such as `nuts={"target_accept": 0.9}` when needed.
+
### Sampling Algorithms
PyMC automatically selects appropriate samplers based on model structure, but you can specify algorithms manually.
@@ -166,7 +170,8 @@ idata = pm.sample(cores=8, chains=8)
# Use variational inference for initialization
with model:
approx = pm.fit() # Run ADVI
- idata = pm.sample(start=approx.sample(return_inferencedata=False)[0])
+ initvals = approx.sample(return_inferencedata=False)[0]
+ idata = pm.sample(initvals=initvals)
```
#### High Autocorrelation
@@ -203,7 +208,7 @@ with model:
# Draw samples from approximation
idata = approx.sample(1000)
# Or sample for MCMC initialization
- start = approx.sample(return_inferencedata=False)[0]
+ initvals = approx.sample(return_inferencedata=False)[0]
```
**Trade-offs:**
@@ -238,7 +243,7 @@ Better captures multimodality but more computationally expensive.
Sample from the prior distribution (before seeing data).
-**`pm.sample_prior_predictive(samples=500, **kwargs)`**
+**`pm.sample_prior_predictive(draws=500, **kwargs)`**
**Purpose:**
- Validate priors are reasonable
@@ -248,7 +253,7 @@ Sample from the prior distribution (before seeing data).
**Example:**
```python
with model:
- prior_pred = pm.sample_prior_predictive(samples=1000)
+ prior_pred = pm.sample_prior_predictive(draws=1000)
# Visualize prior predictions
az.plot_ppc(prior_pred, group='prior')
@@ -288,15 +293,18 @@ with model:
idata = pm.sample()
# Update with new predictor values
- pm.set_data({'X': X_new})
+ pm.set_data({'X': X_new}, coords={'obs_id': np.arange(len(X_new))})
# Sample predictions
post_pred_new = pm.sample_posterior_predictive(
- idata.posterior,
- var_names=['y_pred']
+ idata,
+ var_names=['y_pred'],
+ predictions=True,
)
```
+In PyMC 6, `var_names` controls what appears in the output but does not force trace variables to be resampled. Use `sample_vars` to explicitly regenerate trace variables and `freeze_vars` to reuse trace variables when changed data would otherwise mark them volatile.
+
## Maximum A Posteriori (MAP) Estimation
Find posterior mode (point estimate).
@@ -410,15 +418,15 @@ Good for multimodal posteriors or when NUTS struggles.
Provide starting values:
```python
-start = {'mu': 0, 'sigma': 1}
+initvals = {'mu': 0, 'sigma': 1}
with model:
- idata = pm.sample(start=start)
+ idata = pm.sample(initvals=initvals)
```
Or use MAP estimate:
```python
with model:
- start = pm.find_MAP()
- idata = pm.sample(start=start)
+ initvals = pm.find_MAP()
+ idata = pm.sample(initvals=initvals)
```
diff --git a/skills/pymc/references/workflows.md b/skills/pymc/references/workflows.md
index 764d9b85..b01894ba 100644
--- a/skills/pymc/references/workflows.md
+++ b/skills/pymc/references/workflows.md
@@ -22,12 +22,13 @@ X_scaled = (X - X.mean(axis=0)) / X.std(axis=0)
# 2. BUILD MODEL
# ==============
-with pm.Model() as model:
- # Define coordinates for named dimensions
- coords = {
- 'predictors': ['var1', 'var2', 'var3'],
- 'obs_id': np.arange(len(y))
- }
+coords = {
+ 'predictors': ['var1', 'var2', 'var3'],
+ 'obs_id': np.arange(len(y))
+}
+
+with pm.Model(coords=coords) as model:
+ X_data = pm.Data('X_scaled', X_scaled, dims=('obs_id', 'predictors'))
# Priors
alpha = pm.Normal('alpha', mu=0, sigma=1)
@@ -35,15 +36,15 @@ with pm.Model() as model:
sigma = pm.HalfNormal('sigma', sigma=1)
# Linear predictor
- mu = alpha + pm.math.dot(X_scaled, beta)
+ mu = alpha + pm.math.dot(X_data, beta)
- # Likelihood
- y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, dims='obs_id')
+ # Tie observed shape to X_data so out-of-sample prediction can resize it
+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=X_data.shape[0], dims='obs_id')
# 3. PRIOR PREDICTIVE CHECK
# ==========================
with model:
- prior_pred = pm.sample_prior_predictive(samples=1000, random_seed=42)
+ prior_pred = pm.sample_prior_predictive(draws=1000, random_seed=42)
# Visualize prior predictions
az.plot_ppc(prior_pred, group='prior', num_pp_samples=100)
@@ -84,7 +85,7 @@ divergences = idata.sample_stats.diverging.sum().item()
print(f"Number of divergences: {divergences}")
# Trace plots
-az.plot_trace(idata, var_names=['alpha', 'beta', 'sigma'])
+az.plot_trace_dist(idata, var_names=['alpha', 'beta', 'sigma'])
plt.tight_layout()
plt.show()
@@ -117,18 +118,19 @@ X_new_scaled = (X_new - X.mean(axis=0)) / X.std(axis=0)
with model:
# Update data
- pm.set_data({'X': X_new_scaled})
+ pm.set_data({'X_scaled': X_new_scaled}, coords={'obs_id': np.arange(len(X_new_scaled))})
# Sample predictions
post_pred = pm.sample_posterior_predictive(
- idata.posterior,
+ idata,
var_names=['y_obs'],
+ predictions=True,
random_seed=42
)
# Prediction intervals
-y_pred_mean = post_pred.posterior_predictive['y_obs'].mean(dim=['chain', 'draw'])
-y_pred_hdi = az.hdi(post_pred.posterior_predictive, var_names=['y_obs'])
+y_pred_mean = post_pred.predictions['y_obs'].mean(dim=['chain', 'draw'])
+y_pred_hdi = az.hdi(post_pred.predictions, var_names=['y_obs'])
# 9. SAVE RESULTS
# ===============
@@ -337,7 +339,7 @@ Always validate priors:
```python
with model:
- prior_pred = pm.sample_prior_predictive(samples=1000)
+ prior_pred = pm.sample_prior_predictive(draws=1000)
# Check if predictions are reasonable
print(f"Prior predictive range: {prior_pred.prior_predictive['y'].min():.2f} to {prior_pred.prior_predictive['y'].max():.2f}")
@@ -403,7 +405,8 @@ for name, weight in zip(comparison.index, weights):
def weighted_predictions(idatas, weights):
preds = []
for (name, idata), weight in zip(idatas.items(), weights):
- pred = idata.posterior_predictive['y_obs'].mean(dim=['chain', 'draw'])
+ group = idata.predictions if hasattr(idata, 'predictions') else idata.posterior_predictive
+ pred = group['y_obs'].mean(dim=['chain', 'draw'])
preds.append(weight * pred)
return sum(preds)
@@ -506,13 +509,14 @@ group_A = idata.posterior['alpha'].sel(groups='A')
## Saving and Loading Results
```python
-# Save InferenceData
+# Save posterior data tree
idata.to_netcdf('results.nc')
-# Load InferenceData
+# Load saved posterior data
loaded_idata = az.from_netcdf('results.nc')
# Save model for later predictions
+# Only unpickle model files you created and trust; prefer NetCDF for sampled results.
import pickle
with open('model.pkl', 'wb') as f:
diff --git a/skills/pymc/scripts/model_comparison.py b/skills/pymc/scripts/model_comparison.py
index 5c4c537a..04a69894 100644
--- a/skills/pymc/scripts/model_comparison.py
+++ b/skills/pymc/scripts/model_comparison.py
@@ -21,10 +21,10 @@ import arviz as az
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
-from typing import Dict
+from typing import Any, Dict
-def compare_models(models_dict: Dict[str, az.InferenceData],
+def compare_models(models_dict: Dict[str, Any],
ic='loo',
scale='deviance',
verbose=True):
@@ -34,7 +34,7 @@ def compare_models(models_dict: Dict[str, az.InferenceData],
Parameters
----------
models_dict : dict
- Dictionary mapping model names to InferenceData objects.
+ Dictionary mapping model names to PyMC posterior objects.
All models must have log_likelihood computed.
ic : str
Information criterion to use: 'loo' (default) or 'waic'
@@ -117,7 +117,7 @@ def compare_models(models_dict: Dict[str, az.InferenceData],
return comparison
-def check_loo_reliability(models_dict: Dict[str, az.InferenceData],
+def check_loo_reliability(models_dict: Dict[str, Any],
threshold=0.7,
verbose=True):
"""
@@ -126,7 +126,7 @@ def check_loo_reliability(models_dict: Dict[str, az.InferenceData],
Parameters
----------
models_dict : dict
- Dictionary mapping model names to InferenceData objects
+ Dictionary mapping model names to PyMC posterior objects
threshold : float
Pareto-k threshold for flagging observations (default: 0.7)
verbose : bool
@@ -227,7 +227,7 @@ def plot_model_comparison(comparison, output_path=None, show=True):
return fig
-def model_averaging(models_dict: Dict[str, az.InferenceData],
+def model_averaging(models_dict: Dict[str, Any],
weights=None,
var_name='y_obs',
ic='loo'):
@@ -237,7 +237,7 @@ def model_averaging(models_dict: Dict[str, az.InferenceData],
Parameters
----------
models_dict : dict
- Dictionary mapping model names to InferenceData objects
+ Dictionary mapping model names to PyMC posterior objects
weights : array-like, optional
Model weights. If None, computed from IC (pseudo-BMA weights)
var_name : str
@@ -272,10 +272,12 @@ def model_averaging(models_dict: Dict[str, az.InferenceData],
predictions = []
for name in model_names:
idata = models_dict[name]
- if 'posterior_predictive' in idata:
+ if hasattr(idata, 'posterior_predictive') and var_name in idata.posterior_predictive:
pred = idata.posterior_predictive[var_name].values
+ elif hasattr(idata, 'predictions') and var_name in idata.predictions:
+ pred = idata.predictions[var_name].values
else:
- print(f"Warning: {name} missing posterior_predictive, skipping")
+ print(f"Warning: {name} missing posterior_predictive/predictions for {var_name}, skipping")
continue
predictions.append(pred)
@@ -288,7 +290,7 @@ def model_averaging(models_dict: Dict[str, az.InferenceData],
return averaged, weights
-def cross_validation_comparison(models_dict: Dict[str, az.InferenceData],
+def cross_validation_comparison(models_dict: Dict[str, Any],
k=10,
verbose=True):
"""
@@ -300,7 +302,7 @@ def cross_validation_comparison(models_dict: Dict[str, az.InferenceData],
Parameters
----------
models_dict : dict
- Dictionary of model names to InferenceData
+ Dictionary of model names to PyMC posterior objects
k : int
Number of folds (default: 10)
verbose : bool
diff --git a/skills/pymc/scripts/model_diagnostics.py b/skills/pymc/scripts/model_diagnostics.py
index 9064d1bf..960b57bc 100644
--- a/skills/pymc/scripts/model_diagnostics.py
+++ b/skills/pymc/scripts/model_diagnostics.py
@@ -26,8 +26,8 @@ def check_diagnostics(idata, var_names=None, ess_threshold=400, rhat_threshold=1
Parameters
----------
- idata : arviz.InferenceData
- InferenceData object from pm.sample()
+ idata : xarray.DataTree or arviz.InferenceData
+ Posterior object from pm.sample()
var_names : list, optional
Variables to check. If None, checks all model parameters
ess_threshold : int
@@ -174,8 +174,8 @@ def create_diagnostic_report(idata, var_names=None, output_dir='diagnostics/', s
Parameters
----------
- idata : arviz.InferenceData
- InferenceData object from pm.sample()
+ idata : xarray.DataTree or arviz.InferenceData
+ Posterior object from pm.sample()
var_names : list, optional
Variables to plot. If None, uses all model parameters
output_dir : str
@@ -198,12 +198,7 @@ def create_diagnostic_report(idata, var_names=None, output_dir='diagnostics/', s
print(f"\nGenerating diagnostic plots in '{output_dir}'...")
# 1. Trace plots
- fig, axes = plt.subplots(
- len(var_names) if var_names else 5,
- 2,
- figsize=(12, 10)
- )
- az.plot_trace(idata, var_names=var_names, axes=axes)
+ az.plot_trace_dist(idata, var_names=var_names)
plt.tight_layout()
plt.savefig(output_path / 'trace_plots.png', dpi=300, bbox_inches='tight')
print(f" ✓ Saved trace plots")
@@ -272,10 +267,10 @@ def compare_prior_posterior(idata, prior_idata, var_names=None, output_path=None
Parameters
----------
- idata : arviz.InferenceData
- InferenceData with posterior samples
- prior_idata : arviz.InferenceData
- InferenceData with prior samples
+ idata : xarray.DataTree or arviz.InferenceData
+ Posterior object with posterior samples
+ prior_idata : xarray.DataTree or arviz.InferenceData
+ Prior object with prior samples
var_names : list, optional
Variables to compare
output_path : str, optional
diff --git a/skills/rdkit/SKILL.md b/skills/rdkit/SKILL.md
index 84b02336..d5a2fabe 100644
--- a/skills/rdkit/SKILL.md
+++ b/skills/rdkit/SKILL.md
@@ -2,8 +2,14 @@
name: rdkit
description: Cheminformatics toolkit for fine-grained molecular control. SMILES/SDF parsing, descriptors (MW, LogP, TPSA), fingerprints, substructure search, 2D/3D generation, similarity, reactions. For standard workflows with simpler interface, use datamol (wrapper around RDKit). Use rdkit for advanced control, custom sanitization, specialized algorithms.
license: BSD-3-Clause license
+allowed-tools:
+ - Read
+ - Write
+ - Edit
+ - Bash
+compatibility: Examples target RDKit 2026.03.x. Use conda-forge for the broadest binary support or PyPI package `rdkit` for supported platform wheels; `rdkit-pypi` is the legacy PyPI name.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -13,6 +19,25 @@ metadata:
RDKit is a comprehensive cheminformatics library providing Python APIs for molecular analysis and manipulation. This skill provides guidance for reading/writing molecular structures, calculating descriptors, fingerprinting, substructure searching, chemical reactions, 2D/3D coordinate generation, and molecular visualization. Use this skill for drug discovery, computational chemistry, and cheminformatics research tasks.
+**Current baseline (checked 2026-06-07):** RDKit **2026.03.3** is the latest GitHub/PyPI release (`rdkit` 2026.3.3 on PyPI). Official installation docs continue to recommend conda-forge for most users, while cross-platform PyPI wheels are published under the `rdkit` package name. `rdkit-pypi` is the old PyPI package name and should only appear when maintaining legacy environments.
+
+## Installation and Setup
+
+Use `uv` when installing into an existing Python environment:
+
+```bash
+uv pip install rdkit
+```
+
+For reproducible chemistry environments, especially when mixing compiled scientific packages, conda-forge remains the upstream recommendation:
+
+```bash
+conda create -c conda-forge -n my-rdkit-env rdkit
+conda activate my-rdkit-env
+```
+
+Avoid installing both conda `rdkit` and PyPI `rdkit`/`rdkit-pypi` into the same environment unless you are deliberately debugging packaging behavior. Mixed installs can make it unclear which binary extension is being imported.
+
## Core Capabilities
### 1. Molecular I/O and Creation
@@ -110,7 +135,6 @@ for problem in problems:
print(problem.GetType(), problem.Message())
# Partial sanitization (skip specific steps)
-from rdkit.Chem import rdMolStandardize
Chem.SanitizeMol(mol, sanitizeOps=Chem.SANITIZE_ALL ^ Chem.SANITIZE_PROPERTIES)
```
@@ -509,10 +533,14 @@ mol # Shows molecule image
```python
# Show what molecular features a fingerprint bit represents
from rdkit.Chem import Draw
+from rdkit.Chem import rdFingerprintGenerator
# For Morgan fingerprints
-bit_info = {}
-fp = AllChem.GetMorganFingerprintAsBitVect(mol, radius=2, bitInfo=bit_info)
+additional_output = rdFingerprintGenerator.AdditionalOutput()
+additional_output.AllocateBitInfoMap()
+morgan_gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
+fp = morgan_gen.GetFingerprint(mol, additionalOutput=additional_output)
+bit_info = additional_output.GetBitInfoMap()
# Draw environment for specific bit
img = Draw.DrawMorganBit(mol, bit_id, bit_info)
@@ -645,18 +673,22 @@ def analyze_druglikeness(smiles):
```python
from rdkit import Chem
-from rdkit.Chem import AllChem
+from rdkit.Chem import rdFingerprintGenerator
from rdkit import DataStructs
def similarity_screen(query_smiles, database_smiles, threshold=0.7):
query_mol = Chem.MolFromSmiles(query_smiles)
- query_fp = AllChem.GetMorganFingerprintAsBitVect(query_mol, 2)
+ if query_mol is None:
+ return []
+
+ morgan_gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
+ query_fp = morgan_gen.GetFingerprint(query_mol)
hits = []
for idx, smiles in enumerate(database_smiles):
mol = Chem.MolFromSmiles(smiles)
if mol:
- fp = AllChem.GetMorganFingerprintAsBitVect(mol, 2)
+ fp = morgan_gen.GetFingerprint(mol)
sim = DataStructs.TanimotoSimilarity(query_fp, fp)
if sim >= threshold:
hits.append((idx, smiles, sim))
@@ -696,30 +728,49 @@ if mol is None:
### Performance Optimization
-**Use binary formats for storage:**
+**Use safe storage formats:**
```python
-import pickle
+import base64
+import json
+from pathlib import Path
+from rdkit import Chem
-# Pickle molecules for fast loading
-with open('molecules.pkl', 'wb') as f:
- pickle.dump(mols, f)
+# Portable exchange formats such as SMILES and SDF are safest for shared data.
+# For local caches, RDKit's binary molecule representation avoids generic pickle.
+payload = [base64.b64encode(mol.ToBinary()).decode("ascii") for mol in mols]
+Path("molecules.rdmol.json").write_text(json.dumps(payload))
-# Load pickled molecules (much faster than reparsing)
-with open('molecules.pkl', 'rb') as f:
- mols = pickle.load(f)
+cached = json.loads(Path("molecules.rdmol.json").read_text())
+mols = [Chem.Mol(base64.b64decode(item)) for item in cached]
```
+Do not load Python pickle files from untrusted sources. Pickle deserialization can execute arbitrary code; prefer SMILES/SDF for interchange and RDKit binary payloads for trusted local caches.
+
**Use bulk operations:**
```python
+from rdkit import DataStructs
+from rdkit.Chem import rdFingerprintGenerator
+
# Calculate fingerprints for all molecules at once
-fps = [AllChem.GetMorganFingerprintAsBitVect(mol, 2) for mol in mols]
+morgan_gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)
+fps = [morgan_gen.GetFingerprint(mol) for mol in mols]
# Use bulk similarity calculations
similarities = DataStructs.BulkTanimotoSimilarity(fps[0], fps[1:])
```
+### Version-Sensitive Behavior
+
+Pin RDKit versions when exact molecular identifiers or numeric features are part of a persisted dataset, model feature pipeline, or regulated report. Recent releases changed or documented behavior in several Python-facing areas:
+
+- **Canonical SMILES and stereo:** 2026.03 changed canonical double-bond handling to avoid stereo corruption, so some stereo-containing SMILES may differ from older releases.
+- **Descriptors and hashes:** 2024.09 corrected unbranched-alkane fragment descriptor SMARTS and changed some tautomer/protomer hash outputs.
+- **Drawing:** legacy `rdkit.Chem.Draw` canvas modules and functions such as `MolToImageFile`, `MolToMPL`, and `MolToQPixmap` were removed; use `Draw.MolToFile`, `Draw.MolToImage`, or `rdMolDraw2D`.
+- **MolStandardize:** use `rdkit.Chem.MolStandardize.rdMolStandardize`; the older Python MolStandardize implementation was removed.
+- **Similarity maps:** `GetSimilarityMapFromWeights()`, `GetSimilarityMapForFingerprint()`, and `GetSimilarityMapForModel()` now require an `rdMolDraw2D` drawing object.
+
### Thread Safety
RDKit operations are generally thread-safe for:
@@ -769,6 +820,8 @@ This skill includes detailed API reference documentation:
Load these references when needing specific API details, parameter information, or pattern examples.
+Only the files listed in `references/` and `scripts/` are bundled local resources. Names such as `rdkit`, `datamol`, `scipy`, and `sklearn` refer to installable Python packages, not local files in this skill.
+
### scripts/
Example scripts for common RDKit workflows:
diff --git a/skills/rdkit/references/api_reference.md b/skills/rdkit/references/api_reference.md
index 86fd4fce..5a980482 100644
--- a/skills/rdkit/references/api_reference.md
+++ b/skills/rdkit/references/api_reference.md
@@ -166,9 +166,10 @@ Extended chemistry functionality.
### Fingerprints
-- `AllChem.GetMorganFingerprint(mol, radius, useFeatures=False)` - Morgan fingerprint
-- `AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=2048)` - Morgan bit vector
-- `AllChem.GetHashedMorganFingerprint(mol, radius, nBits=2048)` - Hashed Morgan
+- Prefer `rdFingerprintGenerator.GetMorganGenerator()` for new Morgan fingerprint code
+- `AllChem.GetMorganFingerprint(mol, radius, useFeatures=False)` - Legacy Morgan fingerprint helper
+- `AllChem.GetMorganFingerprintAsBitVect(mol, radius, nBits=2048)` - Legacy Morgan bit vector helper
+- `AllChem.GetHashedMorganFingerprint(mol, radius, nBits=2048)` - Legacy hashed Morgan helper
- `AllChem.GetErGFingerprint(mol)` - ErG fingerprint
## rdkit.Chem.Descriptors
@@ -281,6 +282,12 @@ Molecular hashing and standardization.
Molecule standardization.
+Import the current standardization implementation from `rdkit.Chem.MolStandardize`:
+
+```python
+from rdkit.Chem.MolStandardize import rdMolStandardize
+```
+
- `rdMolStandardize.Normalize(mol)` - Normalize functional groups
- `rdMolStandardize.Reionize(mol)` - Fix ionization state
- `rdMolStandardize.RemoveFragments(mol)` - Remove small fragments
@@ -356,13 +363,15 @@ Clustering algorithms.
## rdkit.Chem.rdFingerprintGenerator
-Modern fingerprint generation API (RDKit 2020.09+).
+Modern fingerprint generation API. Prefer this over legacy `AllChem.GetMorganFingerprint*` helpers for new code.
- `rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048)` - Morgan generator
- `rdFingerprintGenerator.GetRDKitFPGenerator(minPath=1, maxPath=7, fpSize=2048)` - RDKit FP generator
- `rdFingerprintGenerator.GetAtomPairGenerator(minDistance=1, maxDistance=30)` - Atom pair generator
+- `rdFingerprintGenerator.GetTopologicalTorsionGenerator(fpSize=2048)` - Topological torsion generator
- `generator.GetFingerprint(mol)` - Generate fingerprint
- `generator.GetCountFingerprint(mol)` - Count-based fingerprint
+- `rdFingerprintGenerator.AdditionalOutput()` - Collect bit information for visualization and explanations
## Common Parameters
@@ -407,13 +416,15 @@ Modern fingerprint generation API (RDKit 2020.09+).
## Installation
```bash
-# Using conda (recommended)
-conda install -c conda-forge rdkit
+# Existing uv/pip environment
+uv pip install rdkit
-# Using pip
-pip install rdkit-pypi
+# Fresh conda-forge environment (upstream recommendation)
+conda create -c conda-forge -n my-rdkit-env rdkit
```
+The PyPI package is now `rdkit`; `rdkit-pypi` is the legacy name for older releases.
+
## Importing
```python
diff --git a/skills/rdkit/scripts/molecular_properties.py b/skills/rdkit/scripts/molecular_properties.py
index 4444a7d5..33fa02ce 100644
--- a/skills/rdkit/scripts/molecular_properties.py
+++ b/skills/rdkit/scripts/molecular_properties.py
@@ -18,7 +18,7 @@ try:
from rdkit import Chem
from rdkit.Chem import Descriptors, Lipinski
except ImportError:
- print("Error: RDKit not installed. Install with: conda install -c conda-forge rdkit")
+ print("Error: RDKit not installed. Install with: uv pip install rdkit")
sys.exit(1)
diff --git a/skills/rdkit/scripts/similarity_search.py b/skills/rdkit/scripts/similarity_search.py
index fa0e9c9c..8360be34 100644
--- a/skills/rdkit/scripts/similarity_search.py
+++ b/skills/rdkit/scripts/similarity_search.py
@@ -19,7 +19,7 @@ try:
from rdkit.Chem import AllChem, MACCSkeys, rdFingerprintGenerator
from rdkit import DataStructs
except ImportError:
- print("Error: RDKit not installed. Install with: conda install -c conda-forge rdkit")
+ print("Error: RDKit not installed. Install with: uv pip install rdkit")
sys.exit(1)
diff --git a/skills/rdkit/scripts/substructure_filter.py b/skills/rdkit/scripts/substructure_filter.py
index 596cfc3d..41da0c30 100644
--- a/skills/rdkit/scripts/substructure_filter.py
+++ b/skills/rdkit/scripts/substructure_filter.py
@@ -17,7 +17,7 @@ from pathlib import Path
try:
from rdkit import Chem
except ImportError:
- print("Error: RDKit not installed. Install with: conda install -c conda-forge rdkit")
+ print("Error: RDKit not installed. Install with: uv pip install rdkit")
sys.exit(1)
diff --git a/skills/seaborn/SKILL.md b/skills/seaborn/SKILL.md
index 1383bf68..c381df99 100644
--- a/skills/seaborn/SKILL.md
+++ b/skills/seaborn/SKILL.md
@@ -2,8 +2,10 @@
name: seaborn
description: Statistical visualization with pandas integration. Use for quick exploration of distributions, relationships, and categorical comparisons with attractive defaults. Best for box plots, violin plots, pair plots, heatmaps. Built on matplotlib. For interactive plots use plotly; for publication styling use scientific-visualization.
license: BSD-3-Clause license
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.8+ and seaborn 0.13.2-compatible dependencies. Install with uv pip install seaborn==0.13.2; use seaborn[stats]==0.13.2 when advanced regression or clustering examples need scipy/statsmodels.
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -13,6 +15,30 @@ metadata:
Seaborn is a Python visualization library for creating publication-quality statistical graphics. Use this skill for dataset-oriented plotting, multivariate analysis, automatic statistical estimation, and complex multi-panel figures with minimal code.
+## Environment and Installation
+
+Current upstream documentation is for seaborn 0.13.2. Official docs support Python 3.8+ with mandatory NumPy, pandas, and matplotlib dependencies; scipy, statsmodels, and fastcluster are optional for some advanced statistics and clustering workflows.
+
+```bash
+# Reproducible install for examples in this skill
+uv pip install "seaborn==0.13.2"
+
+# Include optional statistical dependencies when needed
+uv pip install "seaborn[stats]==0.13.2"
+```
+
+Recommended imports:
+
+```python
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+import seaborn as sns
+import seaborn.objects as so
+```
+
+`sns.load_dataset()` downloads public example data when it is not cached. For private, regulated, or offline work, load local files explicitly with pandas and pass the resulting DataFrame to seaborn.
+
## Design Philosophy
Seaborn follows these core principles:
@@ -51,7 +77,7 @@ The function interface provides specialized plotting functions organized by visu
### Objects Interface (Modern)
-The `seaborn.objects` interface provides a declarative, composable API similar to ggplot2. Build visualizations by chaining methods to specify data mappings, marks, transformations, and scales.
+The `seaborn.objects` interface provides a declarative, composable API similar to ggplot2. Build visualizations by chaining methods to specify data mappings, marks, transformations, and scales. Upstream still describes this interface as experimental and incomplete in 0.13.2, although stable enough for serious use; prefer the function interface for conservative production code unless the compositional API materially simplifies the plot.
**When to use:**
- Complex layered visualizations
@@ -70,6 +96,16 @@ from seaborn import objects as so
)
```
+## Current API Notes
+
+Seaborn 0.12 and 0.13 changed several common plotting patterns:
+
+- Most plotting functions now require keyword arguments for variables. Prefer `sns.scatterplot(data=df, x="x", y="y")` over positional `sns.scatterplot(df["x"], df["y"])`.
+- `errorbar` replaces the old `ci` parameter in `lineplot()`, `barplot()`, and `pointplot()`. Regression functions such as `regplot()` and `lmplot()` still use `ci`.
+- Categorical plots were rewritten in 0.13. Use `native_scale=True` when numeric or datetime categories should keep their original scale instead of ordinal positions.
+- Passing `palette` without assigning `hue` is deprecated for categorical functions. If each category should get its own color, assign a redundant hue such as `hue="day"` and set `legend=False`.
+- Prefer renamed parameters: `violinplot(density_norm=..., common_norm=...)` instead of `scale`/`scale_hue`, `boxenplot(width_method=...)` instead of `scale`, and `barplot(err_kws=...)` instead of `errcolor`/`errwidth`.
+
## Plotting Functions by Category
### Relational Plots (Relationships Between Variables)
@@ -163,9 +199,13 @@ sns.pairplot(data=df, hue='species', corner=True)
- `x`, `y` - Variables (one typically categorical)
- `hue` - Additional categorical grouping
- `order`, `hue_order` - Control category ordering
-- `dodge` - Separate hue levels side-by-side
-- `orient` - "v" (vertical) or "h" (horizontal)
-- `kind` - Plot type for catplot: "strip", "swarm", "box", "violin", "bar", "point"
+- `native_scale` - Preserve numeric/datetime scale on the categorical axis
+- `log_scale` - Apply log scaling without dropping down to matplotlib
+- `formatter` - Control categorical tick labels
+- `dodge`, `gap` - Separate hue levels side-by-side and space dodged elements
+- `orient` - "x"/"y" or "v"/"h" to specify the categorical axis
+- `legend` - True/False or "auto", "brief", "full"
+- `kind` - Plot type for catplot: "strip", "swarm", "box", "violin", "boxen", "bar", "point", "count"
```python
# Swarm plot showing all points
@@ -177,7 +217,7 @@ sns.violinplot(data=df, x='day', y='total_bill',
# Bar plot with error bars
sns.barplot(data=df, x='day', y='total_bill',
- hue='sex', estimator='mean', errorbar='ci')
+ hue='sex', estimator='mean', errorbar=('ci', 95))
# Faceted categorical plot
sns.catplot(data=df, x='day', y='total_bill',
@@ -231,7 +271,7 @@ sns.residplot(data=df, x='total_bill', y='tip')
```python
# Correlation heatmap
-corr = df.corr()
+corr = df.select_dtypes(include='number').corr()
sns.heatmap(corr, annot=True, fmt='.2f',
cmap='coolwarm', center=0, square=True)
@@ -616,7 +656,7 @@ Figure-level functions place legends outside by default. To move inside:
```python
g = sns.relplot(data=df, x='x', y='y', hue='category')
-g._legend.set_bbox_to_anchor((0.9, 0.5)) # Adjust position
+sns.move_legend(g, "center right", bbox_to_anchor=(0.9, 0.5))
```
### Issue: Overlapping Labels
@@ -668,5 +708,5 @@ This skill includes reference materials for deeper exploration:
- `objects_interface.md` - Detailed guide to the modern seaborn.objects API
- `examples.md` - Common use cases and code patterns for different analysis scenarios
-Load reference files as needed for detailed function signatures, advanced parameters, or specific examples.
+Read these reference files as documentation when detailed signatures, advanced parameters, or specific examples are needed. Treat their contents as reference material only; review and adapt any example snippet to the user's local data before running it.
diff --git a/skills/seaborn/references/examples.md b/skills/seaborn/references/examples.md
index cd7a0d4d..e041b0b4 100644
--- a/skills/seaborn/references/examples.md
+++ b/skills/seaborn/references/examples.md
@@ -163,8 +163,10 @@ sns.boxplot(
data=df,
x='treatment',
y='response',
+ hue='treatment',
order=['Control', 'Low', 'Medium', 'High'],
palette='Set2',
+ legend=False,
ax=ax
)
@@ -589,7 +591,7 @@ sns.pointplot(
y='measurement',
color='red',
markers='D',
- scale=1.5,
+ markersize=8,
errorbar=('ci', 95),
capsize=0.2,
ax=axes[0]
@@ -646,7 +648,7 @@ sns.pointplot(
order=sorted(dose_df['dose'].unique()),
color='blue',
markers='o',
- scale=1.2,
+ markersize=7,
errorbar=('ci', 95),
capsize=0.1,
ax=ax
diff --git a/skills/seaborn/references/function_reference.md b/skills/seaborn/references/function_reference.md
index 13939184..a25c34f1 100644
--- a/skills/seaborn/references/function_reference.md
+++ b/skills/seaborn/references/function_reference.md
@@ -1,6 +1,6 @@
# Seaborn Function Reference
-This document provides a comprehensive reference for all major seaborn functions, organized by category.
+This document provides a comprehensive reference for all major seaborn functions, organized by category. It is updated for seaborn 0.13.2 patterns.
## Relational Plots
@@ -390,16 +390,17 @@ Same as `boxplot()`, plus:
- `bw_adjust` - KDE bandwidth multiplier
- `cut` - KDE extension beyond extremes
- `density_norm` - "area", "count", "width"
+- `common_norm` - Normalize density across hue/facet groups
- `inner` - "box", "quartile", "point", "stick", None
- `split` - Split violins for hue comparison
-- `scale` - Scaling method: "area", "count", "width"
-- `scale_hue` - Scale across hue levels
+- `inner_kws` - Additional parameters for interior artists
- `gridsize` - KDE grid resolution
**Example:**
```python
sns.violinplot(data=df, x='day', y='total_bill',
hue='sex', split=True, inner='quartile',
+ density_norm='area', common_norm=False,
palette='muted')
```
@@ -412,12 +413,13 @@ Same as `boxplot()`, plus:
- `k_depth` - "tukey", "proportion", "trustworthy", "full", or int
- `outlier_prop` - Proportion of data as outliers
- `trust_alpha` - Alpha for trustworthy depth
+- `width_method` - How box widths represent distribution: "exponential", "linear", "area"
- `showfliers` - Show outlier points
**Example:**
```python
sns.boxenplot(data=df, x='day', y='total_bill',
- hue='time', palette='Set2')
+ hue='time', width_method='area', palette='Set2')
```
### barplot()
@@ -442,8 +444,7 @@ sns.boxenplot(data=df, x='day', y='total_bill',
- `saturation` - Color saturation
- `width` - Bar width
- `dodge` - Separate hue levels side-by-side
-- `errcolor` - Error bar color
-- `errwidth` - Error bar line width
+- `err_kws` - Matplotlib keyword arguments for error bars
- `capsize` - Error bar cap width
- `native_scale` - Use numeric scale
- `formatter` - Formatter for categorical axis
@@ -454,7 +455,8 @@ sns.boxenplot(data=df, x='day', y='total_bill',
```python
sns.barplot(data=df, x='day', y='total_bill',
hue='sex', estimator='median',
- errorbar=('ci', 95), capsize=0.1)
+ errorbar=('ci', 95), capsize=0.1,
+ err_kws={'linewidth': 1.5})
```
### countplot()
diff --git a/skills/seaborn/references/objects_interface.md b/skills/seaborn/references/objects_interface.md
index 3cd1be56..dc18eb72 100644
--- a/skills/seaborn/references/objects_interface.md
+++ b/skills/seaborn/references/objects_interface.md
@@ -1,6 +1,6 @@
# Seaborn Objects Interface
-The `seaborn.objects` interface provides a modern, declarative API for building visualizations through composition. This guide covers the complete objects interface introduced in seaborn 0.12+.
+The `seaborn.objects` interface provides a modern, declarative API for building visualizations through composition. This guide covers the objects interface introduced in seaborn 0.12+ and checked against seaborn 0.13.2. Upstream still labels this interface experimental and incomplete, so prefer it when composition helps and keep conservative production workflows on the function API when needed.
## Core Concept
@@ -14,7 +14,7 @@ The objects interface separates **what you want to show** (data and mappings) fr
## Basic Usage
```python
-from seaborn import objects as so
+import seaborn.objects as so
import pandas as pd
# Create plot with data and mappings
@@ -36,7 +36,8 @@ The `Plot` class is the foundation of the objects interface.
```python
so.Plot(data=None, x=None, y=None, color=None, alpha=None,
fill=None, fillalpha=None, fillcolor=None, marker=None,
- pointsize=None, stroke=None, text=None, **variables)
+ pointsize=None, stroke=None, linewidth=None, linestyle=None,
+ edgewidth=None, edgecolor=None, text=None, group=None)
```
**Parameters:**
@@ -47,8 +48,10 @@ so.Plot(data=None, x=None, y=None, color=None, alpha=None,
- `marker` - Variable for marker shape
- `pointsize` - Variable for point size
- `stroke` - Variable for line width
+- `linewidth`, `linestyle` - Variables for line appearance
+- `edgewidth`, `edgecolor` - Variables for mark edge appearance
- `text` - Variable for text labels
-- `**variables` - Additional mappings using property names
+- `group` - Variable for grouping observations
**Examples:**
```python
@@ -214,12 +217,11 @@ p.label(
Apply matplotlib style settings.
```python
-Plot.theme(config, **kwargs)
+Plot.theme(config, /)
```
**Parameters:**
-- `config` - Dict of rcParams or seaborn theme dict
-- `**kwargs` - Individual rcParams
+- `config` - Dict of matplotlib rcParams, passed positionally
**Example:**
```python
@@ -228,9 +230,6 @@ p.theme({**sns.axes_style('whitegrid'), **sns.plotting_context('talk')})
# Custom rcParams
p.theme({'axes.facecolor': 'white', 'axes.grid': True})
-
-# Individual parameters
-p.theme(axes_facecolor='white', font_scale=1.2)
```
#### layout()
diff --git a/skills/statsmodels/SKILL.md b/skills/statsmodels/SKILL.md
index f2edf5da..bb57f585 100644
--- a/skills/statsmodels/SKILL.md
+++ b/skills/statsmodels/SKILL.md
@@ -1,9 +1,11 @@
---
name: statsmodels
description: Statistical models library for Python. Use when you need specific model classes (OLS, GLM, mixed models, ARIMA) with detailed diagnostics, residuals, and inference. Best for econometrics, time series, rigorous inference with coefficient tables. For guided statistical test selection with APA reporting use statistical-analysis.
+allowed-tools: Read Write Edit Bash
+compatibility: Requires Python 3.9+ and statsmodels 0.14.6-compatible dependencies. Use `uv pip install statsmodels==0.14.6`; optional predictive-metric examples also need scikit-learn.
license: BSD-3-Clause license
metadata:
- version: "1.0"
+ version: "1.1"
skill-author: K-Dense Inc.
---
@@ -13,6 +15,16 @@ metadata:
Statsmodels is Python's premier library for statistical modeling, providing tools for estimation, inference, and diagnostics across a wide range of statistical methods. Apply this skill for rigorous statistical analysis, from simple linear regression to complex time series models and econometric analyses.
+## Current Compatibility
+
+Examples target statsmodels 0.14.6, released Dec 5, 2025. For reproducible environments, pin the primary package:
+
+```bash
+uv pip install statsmodels==0.14.6
+```
+
+Use `statsmodels.api` and `statsmodels.formula.api` for stable high-level imports, and direct module imports when examples require newer or specialized classes such as `HurdleCountModel`.
+
## When to Use This Skill
This skill should be used when:
@@ -119,16 +131,20 @@ print(f"ADF p-value: {adf_result[1]:.4f}")
if adf_result[1] > 0.05:
# Series is non-stationary, difference it
- y_diff = y_series.diff().dropna()
+ y_for_acf = y_series.diff().dropna()
+ d = 1
+else:
+ y_for_acf = y_series.dropna()
+ d = 0
# Plot ACF/PACF to identify p, q
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
-plot_acf(y_diff, lags=40, ax=ax1)
-plot_pacf(y_diff, lags=40, ax=ax2)
+plot_acf(y_for_acf, lags=40, ax=ax1)
+plot_pacf(y_for_acf, lags=40, ax=ax2)
plt.show()
# Fit ARIMA(p,d,q)
-model = ARIMA(y_series, order=(1, 1, 1))
+model = ARIMA(y_series, order=(1, d, 1))
results = model.fit()
print(results.summary())
@@ -167,7 +183,7 @@ print(f"Overdispersion: {overdispersion:.2f}")
if overdispersion > 1.5:
# Use Negative Binomial instead
- from statsmodels.discrete.count_model import NegativeBinomial
+ from statsmodels.discrete.discrete_model import NegativeBinomial
nb_model = NegativeBinomial(y_counts, X)
nb_results = nb_model.fit()
print(nb_results.summary())
@@ -576,13 +592,13 @@ Comprehensive statistical testing and diagnostics:
**Search patterns:**
```bash
# Find information about specific models
-grep -r "Quantile Regression" references/
+rg "Quantile Regression" references/
# Find diagnostic tests
-grep -r "Breusch-Pagan" references/stats_diagnostics.md
+rg "Breusch-Pagan" references/stats_diagnostics.md
# Find time series guidance
-grep -r "SARIMAX" references/time_series.md
+rg "SARIMAX" references/time_series.md
```
## Common Pitfalls to Avoid
diff --git a/skills/statsmodels/references/discrete_choice.md b/skills/statsmodels/references/discrete_choice.md
index 6d51bee6..9bdfdf3e 100644
--- a/skills/statsmodels/references/discrete_choice.md
+++ b/skills/statsmodels/references/discrete_choice.md
@@ -226,7 +226,7 @@ Standard model for count data.
**Model**: P(Y=k|X) = exp(-λ) λᵏ / k!, where log(λ) = Xβ
```python
-from statsmodels.discrete.count_model import Poisson
+from statsmodels.discrete.discrete_model import Poisson
model = Poisson(y_counts, X)
results = model.fit()
@@ -282,7 +282,7 @@ For overdispersed count data (variance > mean).
**Model**: Adds dispersion parameter α to account for overdispersion
```python
-from statsmodels.discrete.count_model import NegativeBinomial
+from statsmodels.discrete.discrete_model import NegativeBinomial
model = NegativeBinomial(y_counts, X)
results = model.fit()
@@ -361,12 +361,12 @@ Two-stage model: whether any counts, then how many.
- Zeros structurally different from positive values
```python
-from statsmodels.discrete.count_model import HurdleCountModel
+from statsmodels.discrete.truncated_model import HurdleCountModel
-# Specify count distribution and zero inflation
+# Poisson-Poisson hurdle model; use `zerodist` for the zero hurdle process
model = HurdleCountModel(y_counts, X,
- exog_infl=X_hurdle,
- dist='poisson') # or 'negbin'
+ dist='poisson',
+ zerodist='poisson')
results = model.fit()
print(results.summary())
diff --git a/skills/statsmodels/references/glm.md b/skills/statsmodels/references/glm.md
index e8ab8e7f..a1ea409c 100644
--- a/skills/statsmodels/references/glm.md
+++ b/skills/statsmodels/references/glm.md
@@ -117,11 +117,11 @@ For overdispersed count data.
- Poisson model shows overdispersion
```python
-# Negative Binomial GLM
-model = sm.GLM(y, X, family=sm.families.NegativeBinomial())
+# Negative Binomial GLM with fixed alpha
+model = sm.GLM(y, X, family=sm.families.NegativeBinomial(alpha=1.0))
results = model.fit()
-# Alternative: use discrete choice model with alpha estimation
+# Use the discrete count model when alpha should be estimated
from statsmodels.discrete.discrete_model import NegativeBinomial
nb_model = NegativeBinomial(y, X)
nb_results = nb_model.fit()
diff --git a/skills/statsmodels/references/time_series.md b/skills/statsmodels/references/time_series.md
index 1e7cb2f5..9c83dc63 100644
--- a/skills/statsmodels/references/time_series.md
+++ b/skills/statsmodels/references/time_series.md
@@ -142,7 +142,7 @@ for p in range(5):
if results.aic < best_aic:
best_aic = results.aic
best_order = (p, d, q)
- except:
+ except (ValueError, np.linalg.LinAlgError):
continue
print(f"Best order: {best_order} with AIC: {best_aic:.2f}")
@@ -545,6 +545,13 @@ stl_result = stl.fit()
fig = stl_result.plot()
plt.show()
+
+# Multiple seasonalities, e.g., hourly data with daily and weekly patterns
+from statsmodels.tsa.seasonal import MSTL
+
+mstl_result = MSTL(hourly_series, periods=(24, 24 * 7)).fit()
+fig = mstl_result.plot()
+plt.show()
```
## Model Evaluation
@@ -653,7 +660,7 @@ from statsmodels.tsa.ardl import ARDL
# ARDL(p, q) model
# y depends on its own lags and lags of X
-model = ARDL(y, lags=2, exog=X, exog_lags=2)
+model = ARDL(y, lags=2, exog=X, order=2)
results = model.fit()
```