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.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
refactor: enhance medchem and esm documentation and functionality
Timothy Kassisa257aa95cf67
diff --git a/docs/scientific-skills.md b/docs/scientific-skills.mdindex 72f6417b..27bf5549 100644--- a/docs/scientific-skills.md+++ b/docs/scientific-skills.md@@ -66,7 +66,7 @@- **Datamol** - Python library for molecular manipulation and featurization built on RDKit with enhanced workflows and performance optimizations. Provides utilities for molecular I/O (reading/writing SMILES, SDF, MOL files), molecular standardization and sanitization, molecular transformations (tautomer enumeration, stereoisomer generation), molecular featurization (descriptors, fingerprints, graph representations), parallel processing for large datasets, and integration with machine learning pipelines. Features include: optimized RDKit operations, caching for repeated computations, molecular filtering and preprocessing, and seamless integration with pandas DataFrames. Designed for drug discovery and cheminformatics workflows requiring efficient processing of large compound libraries. Use cases: molecular preprocessing for ML models, compound library management, molecular similarity searches, and cheminformatics data pipelines- **DeepChem** - Deep learning framework for molecular machine learning and drug discovery built on TensorFlow and PyTorch. Provides implementations of graph neural networks (GCN, GAT, MPNN, AttentiveFP) for molecular property prediction, molecular featurization (molecular graphs, fingerprints, descriptors), pre-trained models, and MoleculeNet benchmark suite (50+ datasets for molecular property prediction, toxicity, ADMET). Key features include: support for both TensorFlow and PyTorch backends, distributed training, hyperparameter optimization, model interpretation tools, and integration with RDKit. Includes datasets for quantum chemistry, toxicity prediction, ADMET properties, and binding affinity prediction. Use cases: molecular property prediction, drug discovery, ADMET prediction, toxicity screening, and molecular machine learning research- **DiffDock** - State-of-the-art diffusion-based molecular docking method for predicting protein-ligand binding poses and binding affinities. Uses diffusion models to generate diverse, high-quality binding poses without requiring exhaustive search. Key features include: fast inference compared to traditional docking methods, generation of multiple diverse poses, confidence scoring for predictions, and support for flexible ligand docking. Provides pre-trained models and Python API for integration into drug discovery pipelines. Achieves superior performance on standard benchmarks (PDBbind, CASF) compared to traditional docking methods. Use cases: virtual screening, lead optimization, binding pose prediction, structure-based drug design, and initial pose generation for refinement with more expensive methods-- **MedChem** - Python library for medicinal chemistry analysis and drug-likeness assessment. Provides tools for calculating molecular descriptors, ADMET (Absorption, Distribution, Metabolism, Excretion, Toxicity) property prediction, drug-likeness filters (Lipinski's Rule of Five, Veber rules, Egan rules, Muegge rules), molecular complexity metrics, and synthetic accessibility scoring. Features include: integration with RDKit, parallel processing for large datasets, and comprehensive property calculators. Supports filtering compound libraries based on drug-like properties, identifying potential ADMET issues early in drug discovery, and prioritizing compounds for further development. Use cases: lead optimization, compound library filtering, ADMET prediction, drug-likeness assessment, and medicinal chemistry analysis in drug discovery workflows+- **MedChem** - Python library for molecular filtering and prioritization in drug discovery (datamol-io). Apply literature-derived drug-likeness rules (Lipinski, Veber, CNS, lead-like), named structural alert catalogs (PAINS, Brenk, NIBR), complexity thresholds against ZINC-derived percentiles, chemical group detection, and a custom query language for multi-criteria filtering. Returns pandas DataFrames from rule/structural filters and boolean masks from the functional API. Integrates with datamol/RDKit and supports parallel processing. Use cases: compound library triage, hit-to-lead filtering, PAINS deprioritization, screening-deck curation, and lead optimization workflows- **Molfeat** - Comprehensive Python library providing 100+ molecular featurizers for converting molecules into numerical representations suitable for machine learning. Includes molecular fingerprints (ECFP, MACCS, RDKit, Pharmacophore), molecular descriptors (2D/3D descriptors, constitutional, topological, electronic), graph-based representations (molecular graphs, line graphs), and pre-trained models (MolBERT, ChemBERTa, Uni-Mol embeddings). Features unified API across different featurizer types, caching for performance, parallel processing, and integration with popular ML frameworks (scikit-learn, PyTorch, TensorFlow). Supports both traditional cheminformatics descriptors and modern learned representations. Use cases: molecular property prediction, virtual screening, molecular similarity searches, and preparing molecular data for machine learning models- **PyTDC** - Python library providing access to Therapeutics Data Commons (TDC), a collection of curated datasets and benchmarks for drug discovery and development. Includes datasets for ADMET prediction (absorption, distribution, metabolism, excretion, toxicity), drug-target interactions, drug-drug interactions, drug response prediction, molecular generation, and retrosynthesis. Features standardized data formats, data loaders with automatic preprocessing, benchmark tasks with evaluation metrics, leaderboards for model comparison, and integration with popular ML frameworks. Provides both single-molecule and drug-pair datasets, covering various stages of drug discovery from target identification to clinical outcomes. Use cases: benchmarking ML models for drug discovery, ADMET prediction model development, drug-target interaction prediction, and drug discovery research- **RDKit** - Open-source cheminformatics toolkit for molecular informatics and drug discovery. Provides comprehensive functionality for molecular I/O (reading/writing SMILES, SDF, MOL, PDB files), molecular descriptors (200+ 2D and 3D descriptors), molecular fingerprints (Morgan, RDKit, MACCS, topological torsions), SMARTS pattern matching for substructure searches, molecular alignment and 3D coordinate generation, pharmacophore perception, reaction handling, and molecular drawing. Features high-performance C++ core with Python bindings, support for large molecule sets, and extensive documentation. Widely used in pharmaceutical industry and academic research. Use cases: molecular property calculation, virtual screening, molecular similarity searches, substructure matching, molecular visualization, and general cheminformatics workflows@@ -97,7 +97,7 @@### Protein Engineering & Design- **Adaptyv** - Cloud laboratory platform for automated protein testing and validation. Submit protein sequences via API or web interface and receive experimental results in approximately 21 days. Supports multiple assay types including binding assays (biolayer interferometry for protein-target interactions, KD/kon/koff measurements), expression testing (quantify protein expression levels in E. coli, mammalian, yeast, or insect cells), thermostability measurements (DSF and CD for Tm determination and thermal stability profiling), and enzyme activity assays (kinetic parameters, substrate specificity, inhibitor testing). Includes computational optimization tools for pre-screening sequences: NetSolP/SoluProt for solubility prediction, SolubleMPNN for sequence redesign to improve expression, ESM for sequence likelihood scoring, ipTM (AlphaFold-Multimer) for interface stability assessment, and pSAE for aggregation risk quantification. Platform features automated workflows from expression through purification to assay execution with quality control, webhook notifications for experiment completion, batch submission support for high-throughput screening, and comprehensive results with kinetic parameters, confidence metrics, and raw data access. Use cases: antibody affinity maturation, therapeutic protein developability assessment, enzyme engineering and optimization, protein stability improvement, AI-driven protein design validation, library screening for expression and function, lead optimization with experimental feedback, and integration of computational design with wet-lab validation in iterative design-build-test-learn cycles-- **ESM (Evolutionary Scale Modeling)** - State-of-the-art protein language models from EvolutionaryScale for protein design, structure prediction, and representation learning. Includes ESM3 (1.4B-98B parameter multimodal generative models for simultaneous reasoning across sequence, structure, and function with chain-of-thought generation, inverse folding, and function-conditioned design) and ESM C (300M-6B parameter efficient embedding models 3x faster than ESM2 for similarity analysis, classification, and feature extraction). Supports local inference with open weights and cloud-based Forge API for scalable batch processing. Use cases: novel protein design, structure prediction from sequence, sequence design from structure, protein embeddings, function annotation, variant generation, and directed evolution workflows+- **ESM (Evolutionary Scale Modeling)** - State-of-the-art protein language models from EvolutionaryScale for protein design, structure prediction, and representation learning. Includes ESM3 (1.4B-98B parameter multimodal generative models for simultaneous reasoning across sequence, structure, and function with chain-of-thought generation, inverse folding, and function-conditioned design) and ESM C (300M-6B parameter efficient embedding models 3x faster than ESM2 for similarity analysis, classification, and feature extraction). Supports local inference with open weights, Forge API (`ESM_API_KEY`) for scalable ESM3/ESM C inference, and Biohub-hosted ESMFold2 for all-atom structure prediction. Use cases: novel protein design, structure prediction from sequence, sequence design from structure, protein embeddings, function annotation, variant generation, and directed evolution workflows- **Glycoengineering** - Analyze and engineer protein glycosylation. Scan sequences for N-glycosylation sequons (N-X-S/T), predict O-glycosylation hotspots, and access curated glycoengineering tools (NetOGlyc, GlycoShield, GlycoWorkbench). Use for glycoprotein engineering, therapeutic antibody optimization, and vaccine design- **Molecular Dynamics** - Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free energy surfaces). Use for structural biology, drug binding studies, and biophysics research@@ -200,7 +200,7 @@- **Scientific Critical Thinking** - Tools and approaches for rigorous scientific reasoning and evaluation- **Scientific Visualization** - Best practices and templates for creating publication-quality scientific figures with matplotlib and seaborn, including statistical plots with automatic confidence intervals, colorblind-safe palettes, multi-panel figures, heatmaps, and journal-specific formatting- **Scientific Writing** - Comprehensive toolkit for writing, structuring, and formatting scientific research papers using IMRAD format, multiple citation styles (APA, AMA, Vancouver, Chicago, IEEE), reporting guidelines (CONSORT, STROBE, PRISMA), effective figures and tables, field-specific terminology, venue-specific structure expectations, and core writing principles for clarity, conciseness, and accuracy across all scientific disciplines-- **Statistical Analysis** - Comprehensive statistical testing, power analysis, and experimental design+- **Statistical Analysis** - Guided hypothesis testing, assumption checks, effect sizes, power analysis, and APA reporting (Pingouin, SciPy, statsmodels, PyMC). For dedicated model APIs see statsmodels and pymc skills### Decision & Scenario Analysis- **Consciousness Council** - Run a multi-perspective Mind Council deliberation on any question, decision, or creative challenge. Use for diverse viewpoints, tough decisions, devil's advocate analysis, exploring problems from multiple angles, or when facing dilemmas, trade-offs, and complex choices with no obvious answerdiff --git a/scientific-skills/esm/SKILL.md b/scientific-skills/esm/SKILL.mdindex ce7e39ce..011709d5 100644--- a/scientific-skills/esm/SKILL.md+++ b/scientific-skills/esm/SKILL.md@@ -1,6 +1,6 @@---name: esm-description: Comprehensive toolkit for protein language models including ESM3 (generative multimodal protein design across sequence, structure, and function) and ESM C (efficient protein embeddings and representations). Use this skill when working with protein sequences, structures, or function prediction; designing novel proteins; generating protein embeddings; performing inverse folding; or conducting protein engineering tasks. Supports both local model usage and cloud-based Forge API for scalable inference.+description: Comprehensive toolkit for EvolutionaryScale protein language models including ESM3 (generative multimodal design across sequence, structure, and function) and ESM C (efficient embeddings). Use for protein sequence/structure/function tasks, inverse folding, embeddings, variant design, and ESMFold2 structure prediction via Biohub. Supports local open weights (Python 3.12, esm on PyPI) and cloud Forge/Biohub APIs with ESM_API_KEY authentication.license: MIT licensemetadata:skill-author: K-Dense Inc.@@ -44,11 +44,12 @@ print(protein.sequence)**For remote/cloud usage via Forge API:**```python-from esm.sdk.forge import ESM3ForgeInferenceClient+import os+import esmfrom esm.sdk.api import ESMProtein, GenerationConfig-# Connect to Forge-model = ESM3ForgeInferenceClient(model="esm3-medium-2024-08", url="https://forge.evolutionaryscale.ai", token="<token>")+# Same interface as local ESM3 — token from ESM_API_KEY (see Authentication)+model = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])# Generateprotein = model.generate(protein, GenerationConfig(track="sequence", num_steps=8))@@ -185,10 +186,11 @@ protein = model.generate(protein, config)Process multiple proteins efficiently using Forge's async executor.```python-from esm.sdk.forge import ESM3ForgeInferenceClient+import osimport asyncio+import esm-client = ESM3ForgeInferenceClient(model="esm3-medium-2024-08", token="<token>")+client = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])# Async batch processingasync def batch_generate(proteins_list):@@ -213,39 +215,53 @@ See `references/forge-api.md` for detailed Forge API documentation, authenticati- `esm3-large-2024-03` (98B) - Highest quality, slower (Forge only)**ESM C Models (Embeddings):**-- `esmc-300m` (30 layers) - Lightweight, fast inference-- `esmc-600m` (36 layers) - Balanced performance-- `esmc-6b` (80 layers) - Maximum representation quality+- `esmc-300m` (30 layers) - Lightweight, fast inference (open weights, local)+- `esmc-600m` (36 layers) - Balanced performance (open weights, local)+- `esmc-6b-2024-12` (80 layers) - Maximum quality (Forge API; local 6B weights require Forge or SageMaker)**Selection criteria:**- **Local development/testing:** Use `esm3-sm-open-v1` or `esmc-300m`- **Production quality:** Use `esm3-medium-2024-08` via Forge-- **Maximum accuracy:** Use `esm3-large-2024-03` or `esmc-6b`+- **Maximum accuracy:** Use `esm3-large-2024-03` or `esmc-6b-2024-12` via Forge- **High throughput:** Use Forge API with batch executor- **Cost optimization:** Use smaller models, implement caching strategies## Installation+Install from PyPI ([`esm` on PyPI](https://pypi.org/project/esm/) by EvolutionaryScale). Requires **Python 3.12** (`>=3.12,<3.13` for current releases).+**Basic installation:**```bash-uv pip install esm+uv pip install "esm==3.2.3"```-**With Flash Attention (recommended for faster inference):**+**With Flash Attention (recommended for faster inference on NVIDIA GPUs):**```bash-uv pip install esm+uv pip install "esm==3.2.3"uv pip install flash-attn --no-build-isolation```-**For Forge API access:**+The Forge client ships with the `esm` package — no extra install for cloud inference.-```bash-uv pip install esm # SDK includes Forge client+## Authentication++Forge API access requires an API key. Never hardcode tokens in scripts or commit them to version control.++1. Check whether `ESM_API_KEY` is already set in the environment.+2. If not, check a local `.env` for `ESM_API_KEY` only (do not load unrelated secrets).+3. If still missing, create a key at [Forge](https://forge.evolutionaryscale.ai) (or [Biohub developer console](https://biohub.ai/developer-console/api-keys) for newer ESMFold2 endpoints).++```python+import os++token = os.environ["ESM_API_KEY"] # raises KeyError if unset```-No additional dependencies needed. Obtain Forge API token at https://forge.evolutionaryscale.ai+`esm.sdk.client()` reads `ESM_API_KEY` automatically when `token` is omitted.++**Biohub platform:** EvolutionaryScale is migrating some services (including ESMFold2 structure prediction) to [biohub.ai](https://biohub.ai). SDK class names may still reference "Forge". See `references/biohub-platform.md` for ESMFold2 and Biohub-specific setup.## Common Workflows@@ -263,6 +279,7 @@ This skill includes comprehensive reference documentation:- `references/esm3-api.md` - ESM3 model architecture, API reference, generation parameters, and multimodal prompting- `references/esm-c-api.md` - ESM C model details, embedding strategies, and performance optimization- `references/forge-api.md` - Forge platform documentation, authentication, batch processing, and deployment+- `references/biohub-platform.md` - Biohub API migration, ESMFold2 structure prediction, and developer-console auth- `references/workflows.md` - Complete examples and common workflow patternsThese references contain detailed API specifications, parameter descriptions, and advanced usage patterns. Load them as needed for specific tasks.@@ -289,8 +306,9 @@ These references contain detailed API specifications, parameter descriptions, an## Resources and Documentation-- **GitHub Repository:** https://github.com/evolutionaryscale/esm+- **GitHub Repository:** https://github.com/evolutionaryscale/esm (releases through v3.2.x; see also [Biohub/esm](https://github.com/Biohub/esm) for ESMFold2)- **Forge Platform:** https://forge.evolutionaryscale.ai+- **Biohub Platform:** https://biohub.ai- **Scientific Paper:** Hayes et al., Science (2025) - https://www.science.org/doi/10.1126/science.ads0018- **Blog Posts:**- ESM3 Release: https://www.evolutionaryscale.ai/blog/esm3-releasediff --git a/scientific-skills/esm/references/biohub-platform.md b/scientific-skills/esm/references/biohub-platform.mdnew file mode 100644index 00000000..986b524c--- /dev/null+++ b/scientific-skills/esm/references/biohub-platform.md@@ -0,0 +1,82 @@+# Biohub Platform and ESMFold2++## Overview++EvolutionaryScale is migrating hosted inference from [Forge](https://forge.evolutionaryscale.ai) to the [Biohub platform](https://biohub.ai). The Python SDK still uses `esm.sdk.forge` client classes and "Forge" naming in many places, but newer structure-prediction APIs (ESMFold2) run on Biohub endpoints.++Use this reference when you need **all-atom structure prediction** (ESMFold2) or when upstream docs point to `biohub.ai` instead of `forge.evolutionaryscale.ai`.++## Authentication++Create API keys in the [Biohub developer console](https://biohub.ai/developer-console/api-keys). Store the key in `ESM_API_KEY` (same env var used by `esm.sdk.client()` on Forge).++```python+import os++token = os.environ["ESM_API_KEY"]+```++Never commit API keys or paste them into notebooks checked into git.++## Installation++For ESMFold2 and latest Biohub SDK features, upstream may recommend installing from the Biohub GitHub repo (pin a specific commit for reproducibility):++```bash+uv pip install "esm@git+https://github.com/Biohub/esm.git@c94ed8d"+```++For ESM3/ESM C workflows on PyPI, `uv pip install "esm==3.2.3"` remains the standard path. Confirm which install source your task requires before mixing both in one environment.++## ESMFold2 Structure Prediction++ESMFold2 is a structure prediction model built on ESMC 6B, available through `SequenceStructureForgeInferenceClient` with Biohub as the API host.++```python+import os+from esm.sdk.forge import SequenceStructureForgeInferenceClient+from esm.sdk.api import FoldingConfig+from esm.utils.structure.input_builder import ProteinInput, StructurePredictionInput++client = SequenceStructureForgeInferenceClient(+ model="esmfold2-fast-2026-05",+ url="https://biohub.ai",+ token=os.environ["ESM_API_KEY"],+)++sequence = "MSKGEELFTGVVPILVELDGDVNGHKFSVSGEGEGDATYGKLTLKFICTTGKLPVPWPTLVTTFSYGVQCFSRYPDHMKQHDFFKSAMPEGYVQERTIFFKDDGNYKTRAEVKFEGDTLVNRIELKGIDFKEDGNILGHKLEYNYNSHNVYIMADKQKNGIKVNFKIRHNIEDGSVQLADHYQQNTPIGDGPVLLPDNHYLSTQSALSKDPNEKRDHMVLLEFVTAAGITLGMDELYK"++fold_input = StructurePredictionInput(+ sequences=[ProteinInput(id="A", sequence=sequence)]+)++config = FoldingConfig(num_loops=3, num_sampling_steps=32)+result = client.fold_all_atom(fold_input, config=config)++with open("result.cif", "w") as f:+ f.write(result.complex.to_mmcif())+```++### Model IDs++| Model ID | Use case |+|----------|----------|+| `esmfold2-fast-2026-05` | Fast single-sequence folding |+| Check Biohub docs for additional variants | MSA-augmented or higher-accuracy modes |++## Relationship to Forge (ESM3 / ESM C)++| Capability | Typical endpoint | Client |+|------------|------------------|--------|+| ESM3 generation | `https://forge.evolutionaryscale.ai` | `esm.sdk.client()` or `ESM3ForgeInferenceClient` |+| ESM C 6B embeddings (hosted) | Forge | `ESM3ForgeInferenceClient` with `esmc-6b-2024-12` |+| ESMFold2 structure prediction | `https://biohub.ai` | `SequenceStructureForgeInferenceClient` |++For ESM3 and ESM C cloud usage patterns, see `forge-api.md`. For local open-weight models, see `esm3-api.md` and `esm-c-api.md`.++## Additional Resources++- **Biohub:** https://biohub.ai+- **Biohub/esm repository:** https://github.com/Biohub/esm+- **Tutorials:** https://github.com/Biohub/esm/tree/main/cookbook/tutorials+- **ESMC & ESMFold2 preprint:** https://biohub.ai/papers/esm_protein.pdfdiff --git a/scientific-skills/esm/references/esm-c-api.md b/scientific-skills/esm/references/esm-c-api.mdindex ff9aabc5..d717f029 100644--- a/scientific-skills/esm/references/esm-c-api.md+++ b/scientific-skills/esm/references/esm-c-api.md@@ -12,7 +12,7 @@ ESM C (Cambrian) is a family of protein language models optimized for representa|----------|-----------|--------|----------|| `esmc-300m` | 300M | 30 | Fast inference, lightweight applications || `esmc-600m` | 600M | 36 | Balanced performance and quality |-| `esmc-6b` | 6B | 80 | Maximum representation quality |+| `esmc-6b-2024-12` | 6B | 80 | Maximum quality (Forge API; not open weights) |**Key Features:**- 3x faster inference than ESM2@@ -45,15 +45,16 @@ model = ESMC.from_pretrained("esmc-300m").to("cuda")# Or specify device explicitlymodel = ESMC.from_pretrained("esmc-600m").to("cpu")-# For maximum quality-model = ESMC.from_pretrained("esmc-6b").to("cuda")+# For maximum quality (local open weights: esmc-300m or esmc-600m)+# For 6B hosted inference, use Forge with esmc-6b-2024-12 (see forge-api.md)+model = ESMC.from_pretrained("esmc-600m").to("cuda")```**Model Selection Criteria:**- **esmc-300m**: Development, real-time applications, batch processing of many sequences- **esmc-600m**: Production deployments, good quality/speed balance-- **esmc-6b**: Research, maximum accuracy for downstream tasks+- **esmc-6b-2024-12** (Forge): Research, maximum accuracy when 6B open weights are unavailable locally### Basic Embedding Generation@@ -335,7 +336,7 @@ class ProteinPropertyPredictor(nn.Module):# Use ESM C as frozen feature extractoresm_model = ESMC.from_pretrained("esmc-600m").to("cuda")-esm_model.eval() # Freeze+esm_model.train(False) # Inference mode (disables dropout; not Python eval)# Create task-specific modelpredictor = ProteinPropertyPredictor(@@ -512,6 +513,29 @@ Key differences:- Better support for long sequences- More efficient memory usage+### Hosted 6B Embeddings via Forge++The 6B model is available through Forge (not as open local weights). Use `LogitsConfig` to return embeddings:++```python+import os+from esm.sdk.forge import ESM3ForgeInferenceClient+from esm.sdk.api import ESMProtein, LogitsConfig++client = ESM3ForgeInferenceClient(+ model="esmc-6b-2024-12",+ url="https://forge.evolutionaryscale.ai",+ token=os.environ["ESM_API_KEY"],+)++protein = ESMProtein(sequence="MPRTKEINDAGLIVHSPQWFYK")+protein_tensor = client.encode(protein)+output = client.logits(protein_tensor, LogitsConfig(sequence=True, return_embeddings=True))+embeddings = output.embeddings+```++SDK v3.2+ also supports `mean_hidden_state` on forward passes for pooled representations.+## Advanced Topics### Fine-tuning ESM Cdiff --git a/scientific-skills/esm/references/esm3-api.md b/scientific-skills/esm/references/esm3-api.mdindex b9799420..16aff41c 100644--- a/scientific-skills/esm/references/esm3-api.md+++ b/scientific-skills/esm/references/esm3-api.md@@ -135,6 +135,16 @@ model = ESM3.from_pretrained("esm3-sm-open-v1").to("cuda")model = ESM3.from_pretrained("esm3-sm-open-v1").to("cpu")```+**Forge API (same interface as local):**++```python+import os+import esm++# Drop-in replacement for ESM3.from_pretrained() — reads ESM_API_KEY by default+model = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])+```+**Generation Method:**```pythondiff --git a/scientific-skills/esm/references/forge-api.md b/scientific-skills/esm/references/forge-api.mdindex ba4e0cad..9fa7973e 100644--- a/scientific-skills/esm/references/forge-api.md+++ b/scientific-skills/esm/references/forge-api.md@@ -21,22 +21,44 @@ Sign up and get your API token at: https://forge.evolutionaryscale.ai### 2. Install ESM SDK```bash-pip install esm+uv pip install "esm==3.2.3"```-The Forge client is included in the standard ESM package.+Requires Python 3.12. The Forge client is included in the standard PyPI package.-### 3. Basic Connection+### 3. Set API Key++Export your Forge API key (never hardcode in source files):++```bash+export ESM_API_KEY="your-key-from-forge-console"+```++`esm.sdk.client()` reads `ESM_API_KEY` by default when `token` is omitted.++### 4. Basic Connection++**Recommended (unified client):**```python+import os+import esm+from esm.sdk.api import ESMProtein, GenerationConfig++client = esm.sdk.client("esm3-medium-2024-08", token=os.environ["ESM_API_KEY"])+```++**Explicit Forge client (equivalent):**++```python+import osfrom esm.sdk.forge import ESM3ForgeInferenceClientfrom esm.sdk.api import ESMProtein, GenerationConfig-# Initialize clientclient = ESM3ForgeInferenceClient(model="esm3-medium-2024-08",url="https://forge.evolutionaryscale.ai",- token="<your-token-here>"+ token=os.environ["ESM_API_KEY"],)# Test connection@@ -66,27 +88,24 @@ print(result.sequence)### Initialization```python+import os+import esmfrom esm.sdk.forge import ESM3ForgeInferenceClient-# Basic initialization-client = ESM3ForgeInferenceClient(- model="esm3-medium-2024-08",- token="<your-token>"-)+token = os.environ["ESM_API_KEY"]-# With custom URL (for enterprise deployments)+# Recommended shorthand+client = esm.sdk.client("esm3-medium-2024-08", token=token)++# With custom URL (enterprise deployments)client = ESM3ForgeInferenceClient(model="esm3-medium-2024-08",url="https://custom.forge.instance.com",- token="<your-token>"+ token=token,)-# With timeout configuration-client = ESM3ForgeInferenceClient(- model="esm3-medium-2024-08",- token="<your-token>",- timeout=300 # 5 minutes-)+# With request timeout (seconds)+client = esm.sdk.client("esm3-medium-2024-08", token=token, request_timeout=300)```### Synchronous Generation@@ -605,7 +624,7 @@ For dedicated infrastructure and enterprise use:## Best Practices Summary-1. **Authentication**: Store tokens securely (environment variables, secrets manager)+1. **Authentication**: Use `ESM_API_KEY` environment variable or a secrets manager — never hardcode tokens2. **Rate Limiting**: Implement exponential backoff and respect limits3. **Error Handling**: Always handle network errors and retries4. **Caching**: Cache results for repeated queries@@ -649,9 +668,14 @@ def validate_token(token):raise```+## Biohub Migration++Some newer APIs (notably ESMFold2 structure prediction) run on [biohub.ai](https://biohub.ai) while SDK modules still use `esm.sdk.forge` naming. See `biohub-platform.md` for ESMFold2 setup and Biohub developer-console authentication.+## Additional Resources- **Forge Platform**: https://forge.evolutionaryscale.ai-- **API Documentation**: Check Forge dashboard for latest API specs+- **Biohub Platform**: https://biohub.ai+- **API Documentation**: Check Forge or Biohub dashboard for latest API specs- **Community Support**: Slack community at https://bit.ly/3FKwcWd- **Enterprise Contact**: Contact EvolutionaryScale for custom deploymentsdiff --git a/scientific-skills/medchem/SKILL.md b/scientific-skills/medchem/SKILL.mdindex 06f558bc..5ae974a0 100644--- a/scientific-skills/medchem/SKILL.md+++ b/scientific-skills/medchem/SKILL.md@@ -1,7 +1,9 @@---name: medchem-description: Medicinal chemistry filters. Apply drug-likeness rules (Lipinski, Veber), PAINS filters, structural alerts, complexity metrics, for compound prioritization and library filtering.+description: Medicinal chemistry filters for compound triage. Apply drug-likeness rules (Lipinski, Veber, CNS), structural alert catalogs (PAINS, NIBR, ChEMBL), complexity metrics, and the medchem query language for library filtering.license: Apache-2.0 license+allowed-tools: [Read, Write, Edit, Bash]+compatibility: Requires Python 3.9+ and datamol (installed with medchem). Optional Lilly demerit filter requires separate `lilly-medchem-rules` conda package.metadata:skill-author: K-Dense Inc.---@@ -10,395 +12,309 @@ metadata:## Overview-Medchem is a Python library for molecular filtering and prioritization in drug discovery workflows. Apply hundreds of well-established and novel molecular filters, structural alerts, and medicinal chemistry rules to efficiently triage and prioritize compound libraries at scale. Rules and filters are context-specific—use as guidelines combined with domain expertise.+Medchem is a Python library from [datamol-io](https://github.com/datamol-io/medchem) for molecular filtering and prioritization in drug discovery. Apply literature-derived drug-likeness rules, named alert catalogs, complexity thresholds, chemical-group detection, and a custom query language to triage compound libraries at scale. Filters are context-specific guidelines — combine with domain expertise and target knowledge.++**Version note:** Examples target **medchem 2.0.5** (PyPI stable, Nov 2024). Requires **Python ≥3.9**. Depends on **datamol** and **RDKit** (installed automatically). `RuleFilters` and structural filter classes return **pandas DataFrames**. Lilly demerits require optional native binaries (`mamba install lilly-medchem-rules`).## When to Use This SkillThis skill should be used when:-- Applying drug-likeness rules (Lipinski, Veber, etc.) to compound libraries-- Filtering molecules by structural alerts or PAINS patterns-- Prioritizing compounds for lead optimization-- Assessing compound quality and medicinal chemistry properties-- Detecting reactive or problematic functional groups-- Calculating molecular complexity metrics+- Applying drug-likeness rules (Lipinski, Veber, CNS, lead-like) to compound libraries+- Filtering molecules by structural alerts, PAINS, or NIBR screening-deck rules+- Prioritizing compounds for hit-to-lead or lead optimization+- Calculating complexity metrics against ZINC-derived thresholds+- Detecting functional groups or named substructure catalogs+- Building multi-criteria filters with the medchem query language## Installation```bash-uv pip install medchem+uv pip install medchem datamol+```++Optional — Eli Lilly demerit filter (requires conda-forge native binaries):++```bash+mamba install -c conda-forge lilly-medchem-rules```## Core Capabilities### 1. Medicinal Chemistry Rules-Apply established drug-likeness rules to molecules using the `medchem.rules` module.+Apply established drug-likeness rules via `medchem.rules`.-**Available Rules:**-- Rule of Five (Lipinski)-- Rule of Oprea-- Rule of CNS-- Rule of leadlike (soft and strict)-- Rule of three-- Rule of Reos-- Rule of drug-- Rule of Veber-- Golden triangle-- PAINS filters--**Single Rule Application:**+**List available rules:**```pythonimport medchem as mc-# Apply Rule of Five to a SMILES string-smiles = "CC(=O)OC1=CC=CC=C1C(=O)O" # Aspirin-passes = mc.rules.basic_rules.rule_of_five(smiles)-# Returns: True+mc.rules.RuleFilters.list_available_rules_names()+# ['rule_of_five', 'rule_of_five_beyond', 'rule_of_four', 'rule_of_three', ...]+```++**Single rule on one molecule:**-# Check specific rules-passes_oprea = mc.rules.basic_rules.rule_of_oprea(smiles)-passes_cns = mc.rules.basic_rules.rule_of_cns(smiles)+```python+import datamol as dm+import medchem as mc++smiles = "CC(=O)OC1=CC=CC=C1C(=O)O" # aspirin+mc.rules.basic_rules.rule_of_five(smiles) # True+mc.rules.basic_rules.rule_of_cns(smiles) # True+mc.rules.basic_rules.rule_of_veber(smiles) # True```-**Multiple Rules with RuleFilters:**+**Multiple rules with `RuleFilters` (returns a DataFrame):**```pythonimport datamol as dmimport medchem as mc-# Load molecules-mols = [dm.to_mol(smiles) for smiles in smiles_list]+mols = [dm.to_mol(s) for s in smiles_list]-# Create filter with multiple rulesrfilter = mc.rules.RuleFilters(- rule_list=[- "rule_of_five",- "rule_of_oprea",- "rule_of_cns",- "rule_of_leadlike_soft"- ]+ rule_list=["rule_of_five", "rule_of_oprea", "rule_of_cns", "rule_of_leadlike_soft"])+df = rfilter(mols=mols, n_jobs=-1, progress=True, keep_props=False)-# Apply filters with parallelization-results = rfilter(- mols=mols,- n_jobs=-1, # Use all CPU cores- progress=True-)+# Columns: mol, pass_all, pass_any, rule_of_five, rule_of_oprea, ...+passing = df[df["pass_all"]]```-**Result Format:**-Results are returned as dictionaries with pass/fail status and detailed information for each rule.+Use `keep_props=True` to include computed descriptors (`mw`, `clogp`, `tpsa`, etc.) in the result.### 2. Structural Alert Filters-Detect potentially problematic structural patterns using the `medchem.structural` module.--**Available Filters:**--1. **Common Alerts** - General structural alerts derived from ChEMBL curation and literature-2. **NIBR Filters** - Novartis Institutes for BioMedical Research filter set-3. **Lilly Demerits** - Eli Lilly's demerit-based system (275 rules, molecules rejected at >100 demerits)+Detect problematic patterns with `medchem.structural`. Both classes return **DataFrames** with `pass_filter`, `status`, and `reasons` columns.-**Common Alerts:**+**Common alerts (ChEMBL-derived rule sets):**```pythonimport medchem as mc-# Create filteralert_filter = mc.structural.CommonAlertsFilters()+df = alert_filter(mols=mol_list, n_jobs=-1, progress=True)+# df columns: mol, pass_filter, status, reasons-# Check single molecule-mol = dm.to_mol("c1ccccc1")-has_alerts, details = alert_filter.check_mol(mol)--# Batch filtering with parallelization-results = alert_filter(- mols=mol_list,- n_jobs=-1,- progress=True-)+clean = df[df["pass_filter"]]```-**NIBR Filters:**+**NIBR filters (Novartis screening-deck curation):**```python-import medchem as mc--# Apply NIBR filtersnibr_filter = mc.structural.NIBRFilters()-results = nibr_filter(mols=mol_list, n_jobs=-1)-```--**Lilly Demerits:**--```python-import medchem as mc--# Calculate Lilly demerits-lilly = mc.structural.LillyDemeritsFilters()-results = lilly(mols=mol_list, n_jobs=-1)--# Each result includes demerit score and whether it passes (≤100 demerits)+df = nibr_filter(mols=mol_list, n_jobs=-1, progress=True)+# df columns: mol, pass_filter, status, severity, reasons, n_covalent_motif, special_mol```-### 3. Functional API for High-Level Operations+Compounds with `severity >= 10` are excluded by default (see NIBR paper).-The `medchem.functional` module provides convenient functions for common workflows.+### 3. Named Catalog Filters (PAINS, Brenk, etc.)-**Quick Filtering:**+Use `medchem.catalogs.NamedCatalogs` for RDKit `FilterCatalog` instances, or the functional API:```pythonimport medchem as mc-# Apply NIBR filters to a list-filter_ok = mc.functional.nibr_filter(- mols=mol_list,- n_jobs=-1-)+# List available named catalogs+mc.catalogs.list_named_catalogs()+# ['tox', 'pains', 'pains_a', 'brenk', 'nibr', 'zinc', ...]++# Functional API — True means molecule passes (no alert match)+passes = mc.functional.alert_filter(mols=mol_list, alerts=["pains"], n_jobs=-1)-# Apply common alerts-alert_results = mc.functional.common_alerts_filter(+# Or via catalog objects+passes = mc.functional.catalog_filter(mols=mol_list,- n_jobs=-1+ catalogs=[mc.catalogs.NamedCatalogs.pains()],+ n_jobs=-1,)```-### 4. Chemical Groups Detection--Identify specific chemical groups and functional groups using `medchem.groups`.+### 4. Functional API-**Available Groups:**-- Hinge binders-- Phosphate binders-- Michael acceptors-- Reactive groups-- Custom SMARTS patterns--**Usage:**+`medchem.functional` provides one-call wrappers that return boolean masks (True = passes):```pythonimport medchem as mc-# Create group detector-group = mc.groups.ChemicalGroup(groups=["hinge_binders"])--# Check for matches-has_matches = group.has_match(mol_list)--# Get detailed match information-matches = group.get_matches(mol)+mc.functional.rules_filter(mols=mol_list, rules=["rule_of_five", "rule_of_cns"], n_jobs=-1)+mc.functional.nibr_filter(mols=mol_list, max_severity=10, n_jobs=-1)+mc.functional.alert_filter(mols=mol_list, alerts=["pains", "brenk"], n_jobs=-1)+mc.functional.complexity_filter(mols=mol_list, complexity_metric="bertz", limit="99", n_jobs=-1)```-### 5. Named Catalogs--Access curated collections of chemical structures through `medchem.catalogs`.+Other helpers: `catalog_filter`, `chemical_group_filter`, `lilly_demerit_filter` (requires optional binaries), `macrocycle_filter`, `bredt_filter`, `protecting_groups_filter`, and more.-**Available Catalogs:**-- Functional groups-- Protecting groups-- Common reagents-- Standard fragments+### 5. Chemical Groups-**Usage:**+Detect functional groups and curated pattern collections via `medchem.groups`:```pythonimport medchem as mc-# Access named catalogs-catalogs = mc.catalogs.NamedCatalogs+# Browse available group collections+mc.groups.list_default_chemical_groups()+# ['privileged_scaffolds', 'common_warhead_covalent_inhibitors', 'rings_in_drugs', ...]-# Use catalog for matching-catalog = catalogs.get("functional_groups")-matches = catalog.get_matches(mol)-```+group = mc.groups.ChemicalGroup(groups=["privileged_scaffolds"])+group.has_match(mol) # bool+group.get_matches(mol) # dict of group → atom indices+group.filter(mols) # molecules matching the group-### 6. Molecular Complexity+# Returns molecules that do NOT match the group+mc.functional.chemical_group_filter(mols=mol_list, chemical_group=group, n_jobs=-1)+```-Calculate complexity metrics that approximate synthetic accessibility using `medchem.complexity`.+Custom groups can be loaded from a file via `groups_db` (CSV with `smiles`/`smarts`, `name`, `group` columns).-**Common Metrics:**-- Bertz complexity-- Whitlock complexity-- Barone complexity+### 6. Molecular Complexity-**Usage:**+Compare complexity metrics to precomputed ZINC-15 percentile thresholds:```pythonimport medchem as mc-# Calculate complexity-complexity_score = mc.complexity.calculate_complexity(mol)--# Filter by complexity threshold-complex_filter = mc.complexity.ComplexityFilter(max_complexity=500)-results = complex_filter(mols=mol_list)-```+# Single molecule+cf = mc.complexity.ComplexityFilter(limit="99", complexity_metric="bertz")+cf(mol) # True if below 99th-percentile threshold-### 7. Constraints Filtering+# Batch via functional API+mc.functional.complexity_filter(+ mols=mol_list,+ complexity_metric="bertz", # also: sas, qed, whitlock, barone, smcm, twc+ limit="99",+ n_jobs=-1,+)-Apply custom property-based constraints using `medchem.constraints`.+# Direct metric functions+mc.complexity.WhitlockCT(mol)+mc.complexity.BaroneCT(mol)+```-**Example Constraints:**-- Molecular weight ranges-- LogP bounds-- TPSA limits-- Rotatable bond counts+### 7. Scaffold Constraints-**Usage:**+`medchem.constraints.Constraints` matches a core scaffold and applies per-atom constraint functions — not simple MW/LogP ranges. For property bounds, use `RuleFilters`, descriptors via `mc.rules.list_descriptors()`, or the query language.```python+import datamol as dmimport medchem as mc-# Define constraints+core = dm.to_mol("c1ccccc1")constraints = mc.constraints.Constraints(- mw_range=(200, 500),- logp_range=(-2, 5),- tpsa_max=140,- rotatable_bonds_max=10+ core=core,+ constraint_fns={"query": lambda mol, atom_idx, query: ...},)--# Apply constraints-results = constraints(mols=mol_list, n_jobs=-1)+constraints(mol)```### 8. Medchem Query Language-Use a specialized query language for complex filtering criteria.+Build multi-criteria filters with `medchem.query.QueryFilter`:-**Query Examples:**-```-# Molecules passing Ro5 AND not having common alerts-"rule_of_five AND NOT common_alerts"+```python+import medchem as mc-# CNS-like molecules with low complexity-"rule_of_cns AND complexity < 400"+# Rule + alert combination+qf = mc.query.QueryFilter('MATCHRULE("rule_of_five") AND NOT HASALERT("pains")')+mask = qf(mols=mol_list, n_jobs=-1) # list[bool]-# Leadlike molecules without Lilly demerits-"rule_of_leadlike AND lilly_demerits == 0"+# CNS-like with property bounds+qf = mc.query.QueryFilter('MATCHRULE("rule_of_cns") AND HASPROP("tpsa", <=, 90)')+mask = qf(mols=mol_list, n_jobs=-1)```-**Usage:**+**Query syntax:**+- `MATCHRULE("rule_of_five")` — apply a named rule+- `HASALERT("pains")` — match a named catalog (`pains`, `brenk`, `nibr`, `tox`, …)+- `HASPROP("mw", <, 500)` — compare a descriptor (unquoted comparator)+- `HASGROUP("privileged_scaffolds")` — match a chemical group+- `HASSUBSTRUCTURE("c1ccccc1")` — substructure match+- Operators: `AND`, `OR`, `NOT`-```python-import medchem as mc--# Parse and apply query-query = mc.query.parse("rule_of_five AND NOT common_alerts")-results = query.apply(mols=mol_list, n_jobs=-1)-```+List available descriptors: `mc.rules.list_descriptors()`## Workflow Patterns-### Pattern 1: Initial Triage of Compound Library--Filter a large compound collection to identify drug-like candidates.+### Pattern 1: Initial Triage of a Compound Library```pythonimport datamol as dmimport medchem as mcimport pandas as pd-# Load compound librarydf = pd.read_csv("compounds.csv")-mols = [dm.to_mol(smi) for smi in df["smiles"]]--# Apply primary filters-rule_filter = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_veber"])-rule_results = rule_filter(mols=mols, n_jobs=-1, progress=True)+mols = [dm.to_mol(s) for s in df["smiles"]]-# Apply structural alerts-alert_filter = mc.structural.CommonAlertsFilters()-alert_results = alert_filter(mols=mols, n_jobs=-1, progress=True)+# Drug-likeness rules+rules_df = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_veber"])(mols=mols, n_jobs=-1)-# Combine results-df["passes_rules"] = rule_results["pass"]-df["has_alerts"] = alert_results["has_alerts"]-df["drug_like"] = df["passes_rules"] & ~df["has_alerts"]+# PAINS + common alerts via query+qf = mc.query.QueryFilter('MATCHRULE("rule_of_five") AND NOT HASALERT("pains")')+pass_mask = qf(mols=mols, n_jobs=-1)-# Save filtered compounds+df["passes_rules"] = rules_df["pass_all"].values+df["drug_like"] = pass_maskfiltered_df = df[df["drug_like"]]filtered_df.to_csv("filtered_compounds.csv", index=False)```### Pattern 2: Lead Optimization Filtering-Apply stricter criteria during lead optimization.-```pythonimport medchem as mc-# Create comprehensive filter-filters = {- "rules": mc.rules.RuleFilters(rule_list=["rule_of_leadlike_strict"]),- "alerts": mc.structural.NIBRFilters(),- "lilly": mc.structural.LillyDemeritsFilters(),- "complexity": mc.complexity.ComplexityFilter(max_complexity=400)-}--# Apply all filters-results = {}-for name, filt in filters.items():- results[name] = filt(mols=candidate_mols, n_jobs=-1)--# Identify compounds passing all filters-passes_all = all(r["pass"] for r in results.values())-```+rules_df = mc.rules.RuleFilters(rule_list=["rule_of_leadlike_soft"])(mols=candidates, n_jobs=-1)+nibr_df = mc.structural.NIBRFilters()(mols=candidates, n_jobs=-1)+complex_mask = mc.functional.complexity_filter(+ mols=candidates, complexity_metric="bertz", limit="95", n_jobs=-1+)-### Pattern 3: Identify Specific Chemical Groups+passes = (+ rules_df["pass_all"]+ & nibr_df["pass_filter"]+ & complex_mask+)+```-Find molecules containing specific functional groups or scaffolds.+### Pattern 3: Detect Functional Groups```pythonimport medchem as mc-# Create group detector for multiple groups-group_detector = mc.groups.ChemicalGroup(- groups=["hinge_binders", "phosphate_binders"]-)--# Screen library-matches = group_detector.get_all_matches(mol_list)--# Filter molecules with desired groups-mol_with_groups = [mol for mol, match in zip(mol_list, matches) if match]+group = mc.groups.ChemicalGroup(groups=["common_warhead_covalent_inhibitors"])+matches = [group.has_match(mol) for mol in mol_list]+warhead_mols = [mol for mol, m in zip(mol_list, matches) if m]```## Best Practices-1. **Context Matters**: Don't blindly apply filters. Understand the biological target and chemical space.--2. **Combine Multiple Filters**: Use rules, structural alerts, and domain knowledge together for better decisions.--3. **Use Parallelization**: For large datasets (>1000 molecules), always use `n_jobs=-1` for parallel processing.--4. **Iterative Refinement**: Start with broad filters (Ro5), then apply more specific criteria (CNS, leadlike) as needed.--5. **Document Filtering Decisions**: Track which molecules were filtered out and why for reproducibility.--6. **Validate Results**: Remember that marketed drugs often fail standard filters—use these as guidelines, not absolute rules.--7. **Consider Prodrugs**: Molecules designed as prodrugs may intentionally violate standard medicinal chemistry rules.+1. **Context matters** — marketed drugs often violate Ro5; prodrugs and natural products are common exceptions.+2. **Combine filters** — rules, alert catalogs, and complexity thresholds work best together.+3. **Use parallelization** — pass `n_jobs=-1` for libraries >1000 molecules.+4. **Check return types** — `RuleFilters` and structural classes return DataFrames; functional helpers return boolean arrays.+5. **Lilly demerits are optional** — install `lilly-medchem-rules` separately; default max demerits is 160 in the functional API.+6. **Document decisions** — retain `status`, `reasons`, and `severity` columns for audit trails.## Resources### references/api_guide.md-Comprehensive API reference covering all medchem modules with detailed function signatures, parameters, and return types.+Module-by-module API reference with signatures, return types, and patterns.### references/rules_catalog.md-Complete catalog of available rules, filters, and alerts with descriptions, thresholds, and literature references.+Catalog of available rules, alert sets, complexity metrics, and filter selection guidelines.### scripts/filter_molecules.py-Production-ready script for batch filtering workflows. Supports multiple input formats (CSV, SDF, SMILES), configurable filter combinations, and detailed reporting.+Batch filtering script for CSV/TSV/SDF/SMILES inputs with configurable rules, alerts, and complexity thresholds.-**Usage:**```bash-python scripts/filter_molecules.py input.csv --rules rule_of_five,rule_of_cns --alerts nibr --output filtered.csv+uv run python scripts/filter_molecules.py input.csv \+ --rules rule_of_five,rule_of_cns --pains --nibr --output filtered.csv```## Documentation-Official documentation: https://medchem-docs.datamol.io/-GitHub repository: https://github.com/datamol-io/medchem-+- Official docs: https://medchem-docs.datamol.io/+- GitHub: https://github.com/datamol-io/medchem+- PyPI: https://pypi.org/project/medchem/ (2.0.5)diff --git a/scientific-skills/medchem/references/api_guide.md b/scientific-skills/medchem/references/api_guide.mdindex b67214f1..a6c386fd 100644--- a/scientific-skills/medchem/references/api_guide.md+++ b/scientific-skills/medchem/references/api_guide.md@@ -1,412 +1,241 @@# Medchem API Reference-Comprehensive reference for all medchem modules and functions.+Reference for **medchem 2.0.5**. Official docs: https://medchem-docs.datamol.io/stable/api/## Module: medchem.rules### Class: RuleFilters-Filter molecules based on multiple medicinal chemistry rules.+Filter molecules by multiple medicinal chemistry rules. Returns a **pandas DataFrame**.**Constructor:**-```python-RuleFilters(rule_list: List[str])-```--**Parameters:**-- `rule_list`: List of rule names to apply. See available rules below.--**Methods:**--```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1, progress: bool = False) -> Dict-```-- `mols`: List of RDKit molecule objects-- `n_jobs`: Number of parallel jobs (-1 uses all cores)-- `progress`: Show progress bar-- **Returns**: Dictionary with results for each rule--**Example:**-```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_cns"])-results = rfilter(mols=mol_list, n_jobs=-1, progress=True)-```--### Module: medchem.rules.basic_rules--Individual rule functions that can be applied to single molecules.--#### rule_of_five()--```python-rule_of_five(mol: Union[str, Chem.Mol]) -> bool-```--Lipinski's Rule of Five for oral bioavailability.--**Criteria:**-- Molecular weight ≤ 500 Da-- LogP ≤ 5-- H-bond donors ≤ 5-- H-bond acceptors ≤ 10--**Parameters:**-- `mol`: SMILES string or RDKit molecule object--**Returns:** True if molecule passes all criteria--#### rule_of_three()--```python-rule_of_three(mol: Union[str, Chem.Mol]) -> bool-```--Rule of Three for fragment screening libraries.--**Criteria:**-- Molecular weight ≤ 300 Da-- LogP ≤ 3-- H-bond donors ≤ 3-- H-bond acceptors ≤ 3-- Rotatable bonds ≤ 3-- Polar surface area ≤ 60 Ų--#### rule_of_oprea()--```python-rule_of_oprea(mol: Union[str, Chem.Mol]) -> bool-```--Oprea's lead-like criteria for hit-to-lead optimization.--**Criteria:**-- Molecular weight: 200-350 Da-- LogP: -2 to 4-- Rotatable bonds ≤ 7-- Rings ≤ 4--#### rule_of_cns()--```python-rule_of_cns(mol: Union[str, Chem.Mol]) -> bool-```--CNS drug-likeness rules.--**Criteria:**-- Molecular weight ≤ 450 Da-- LogP: -1 to 5-- H-bond donors ≤ 2-- TPSA ≤ 90 Ų--#### rule_of_leadlike_soft()--```python-rule_of_leadlike_soft(mol: Union[str, Chem.Mol]) -> bool-```--Soft lead-like criteria (more permissive).--**Criteria:**-- Molecular weight: 250-450 Da-- LogP: -3 to 4-- Rotatable bonds ≤ 10--#### rule_of_leadlike_strict()```python-rule_of_leadlike_strict(mol: Union[str, Chem.Mol]) -> bool+RuleFilters(rule_list: List[Union[str, Callable]], rule_list_names: Optional[List[str]] = None)```-Strict lead-like criteria (more restrictive).--**Criteria:**-- Molecular weight: 200-350 Da-- LogP: -2 to 3.5-- Rotatable bonds ≤ 7-- Rings: 1-3--#### rule_of_veber()+**Call signature:**```python-rule_of_veber(mol: Union[str, Chem.Mol]) -> bool+__call__(+ mols: Sequence[Union[str, Mol]],+ n_jobs: int = -1,+ progress: bool = False,+ progress_leave: bool = False,+ scheduler: str = "auto",+ keep_props: bool = False,+ fail_if_invalid: bool = True,+) -> pd.DataFrame```-Veber's rules for oral bioavailability.+**Return columns:** `mol`, `pass_all`, `pass_any`, plus one boolean column per rule. With `keep_props=True`, descriptor columns (`mw`, `clogp`, `tpsa`, etc.) are included.-**Criteria:**-- Rotatable bonds ≤ 10-- TPSA ≤ 140 Ų--#### rule_of_reos()+**Class methods:**```python-rule_of_reos(mol: Union[str, Chem.Mol]) -> bool+RuleFilters.list_available_rules_names() # list of 22 rule names+RuleFilters.list_available_rules() # rules with property metadata```-Rapid Elimination Of Swill (REOS) filter.--**Criteria:**-- Molecular weight: 200-500 Da-- LogP: -5 to 5-- H-bond donors: 0-5-- H-bond acceptors: 0-10--#### rule_of_drug()--```python-rule_of_drug(mol: Union[str, Chem.Mol]) -> bool-```--Combined drug-likeness criteria.--**Criteria:**-- Passes Rule of Five-- Passes Veber rules-- No PAINS substructures--#### golden_triangle()+**Example:**```python-golden_triangle(mol: Union[str, Chem.Mol]) -> bool+rfilter = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_cns"])+df = rfilter(mols=mol_list, n_jobs=-1, progress=True)+passing = df[df["pass_all"]]```-Golden Triangle for drug-likeness balance.--**Criteria:**-- 200 ≤ MW ≤ 50×LogP + 400-- LogP: -2 to 5--#### pains_filter()+### Module: medchem.rules.basic_rules-```python-pains_filter(mol: Union[str, Chem.Mol]) -> bool+Individual rule functions for single molecules. Each returns `bool` (True = passes).++| Function | Description |+|----------|-------------|+| `rule_of_five(mol)` | Lipinski Rule of Five |+| `rule_of_five_beyond(mol)` | Beyond Ro5 (large binding sites) |+| `rule_of_four(mol)` | Rule of Four |+| `rule_of_three(mol)` | Fragment library Rule of Three |+| `rule_of_three_extended(mol)` | Extended Ro3 |+| `rule_of_two(mol)` | Rule of Two |+| `rule_of_ghose(mol)` | Ghose filter |+| `rule_of_veber(mol)` | Veber oral bioavailability |+| `rule_of_reos(mol)` | REOS filter |+| `rule_of_chemaxon_druglikeness(mol)` | ChemAxon drug-likeness |+| `rule_of_egan(mol)` | Egan permeability |+| `rule_of_pfizer_3_75(mol)` | Pfizer 3/75 filter |+| `rule_of_gsk_4_400(mol)` | GSK 4/400 filter |+| `rule_of_oprea(mol)` | Oprea lead-like |+| `rule_of_xu(mol)` | Xu filter |+| `rule_of_cns(mol)` | CNS drug-likeness |+| `rule_of_respiratory(mol)` | Respiratory drug-likeness |+| `rule_of_zinc(mol)` | ZINC-like |+| `rule_of_leadlike_soft(mol)` | Soft lead-like |+| `rule_of_druglike_soft(mol)` | Soft drug-like |+| `rule_of_generative_design(mol)` | Generative design space |+| `rule_of_generative_design_strict(mol)` | Strict generative design |++### Descriptor helpers++```python+mc.rules.list_descriptors() # property names for query language```-Pan Assay INterference compoundS (PAINS) filter.--**Returns:** True if molecule does NOT contain PAINS substructures----## Module: medchem.structural### Class: CommonAlertsFilters-Filter for common structural alerts derived from ChEMBL and literature.+ChEMBL-derived structural alert filter sets (Glaxo, Dundee, BMS, etc.).-**Constructor:**```pythonCommonAlertsFilters()```-**Methods:**--```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1, progress: bool = False) -> List[Dict]-```+**Returns DataFrame columns:** `mol`, `pass_filter`, `status`, `reasons`-Apply common alerts filter to a list of molecules.+- `status`: one of `"exclude"`, `"flag"`, `"annotations"`, `"ok"`+- `pass_filter`: bool — True if compound passes-**Returns:** List of dictionaries with keys:-- `has_alerts`: Boolean indicating if molecule has alerts-- `alert_details`: List of matched alert patterns-- `num_alerts`: Number of alerts found+**Methods:**```python-check_mol(mol: Chem.Mol) -> Tuple[bool, List[str]]+list_default_available_alerts() # DataFrame of alert definitions+__call__(mols, n_jobs=-1, progress=False, ...) -> pd.DataFrame```-Check a single molecule for structural alerts.--**Returns:** Tuple of (has_alerts, list_of_alert_names)-### Class: NIBRFilters-Novartis NIBR medicinal chemistry filters.+Novartis screening-deck curation filters ([Schuffenhauer et al., J. Med. Chem. 2020](https://dx.doi.org/10.1021/acs.jmedchem.0c01332)).-**Constructor:**```pythonNIBRFilters()```-**Methods:**+**Returns DataFrame columns:** `mol`, `pass_filter`, `status`, `severity`, `reasons`, `n_covalent_motif`, `special_mol`-```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1, progress: bool = False) -> List[bool]-```+- `severity`: 0 = clean; 1–9 = flags; ≥10 = excluded by default-Apply NIBR filters to molecules.+### Lilly demerits (optional)-**Returns:** List of booleans (True if molecule passes)+Requires `mamba install lilly-medchem-rules`. Access via:-### Class: LillyDemeritsFilters--Eli Lilly's demerit-based structural alert system (275 rules).--**Constructor:**```python-LillyDemeritsFilters()+mc.functional.lilly_demerit_filter(mols, max_demerits=160, n_jobs=-1)+# or+from medchem.structural.lilly_demerits import LillyDemeritsFilters```-**Methods:**--```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1, progress: bool = False) -> List[Dict]-```--Calculate Lilly demerits for molecules.--**Returns:** List of dictionaries with keys:-- `demerits`: Total demerit score-- `passes`: Boolean (True if demerits ≤ 100)-- `matched_patterns`: List of matched patterns with scores----## Module: medchem.functional-High-level functional API for common operations.--### nibr_filter()+High-level boolean-mask API. **True = passes** (no alert / passes all rules).++| Function | Description |+|----------|-------------|+| `rules_filter(mols, rules, n_jobs=None, ...)` | Apply rule list |+| `nibr_filter(mols, max_severity=10, n_jobs=None, ...)` | NIBR filter |+| `alert_filter(mols, alerts, alerts_db=None, n_jobs=1, ...)` | Named alert catalogs |+| `catalog_filter(mols, catalogs, n_jobs=-1, ...)` | RDKit FilterCatalog list |+| `complexity_filter(mols, complexity_metric="bertz", limit="99", ...)` | Complexity threshold |+| `lilly_demerit_filter(mols, max_demerits=160, ...)` | Lilly demerits (optional) |+| `chemical_group_filter(mols, chemical_group, ...)` | Exclude group matches |+| `catalog_filter(mols, catalogs, ...)` | Custom catalog list |+| `bredt_filter(mols, ...)` | Bredt instability filter |+| `macrocycle_filter(mols, ...)` | Macrocycle filter |+| `protecting_groups_filter(mols, ...)` | Protecting group filter |+| `ring_infraction_filter(mols, ...)` | Ring infraction filter |+| `symmetry_filter(mols, ...)` | Symmetry filter |-```python-nibr_filter(mols: List[Chem.Mol], n_jobs: int = 1) -> List[bool]-```--Apply NIBR filters using functional API.+----**Parameters:**-- `mols`: List of molecules-- `n_jobs`: Parallelization level+## Module: medchem.catalogs-**Returns:** List of pass/fail booleans+### NamedCatalogs-### common_alerts_filter()+Static methods returning RDKit `FilterCatalog` objects:```python-common_alerts_filter(mols: List[Chem.Mol], n_jobs: int = 1) -> List[Dict]-```+mc.catalogs.list_named_catalogs()+# tox, pains, pains_a, pains_b, pains_c, nih, zinc, brenk, dundee, bms,+# glaxo, schembl, mlsmr, inpharmatica, lint, nibr, bredt, toxicophore, ...-Apply common alerts filter using functional API.--**Returns:** List of results dictionaries+mc.catalogs.NamedCatalogs.pains()+mc.catalogs.NamedCatalogs.brenk()+mc.catalogs.NamedCatalogs.nibr()+mc.catalogs.NamedCatalogs.bredt()+```-### lilly_demerits_filter()+**Helpers:**```python-lilly_demerits_filter(mols: List[Chem.Mol], n_jobs: int = 1) -> List[Dict]+catalog_from_smarts(smarts_list)+merge_catalogs(catalogs)+list_named_catalogs()```-Calculate Lilly demerits using functional API.----## Module: medchem.groups-### Class: ChemicalGroup+### ChemicalGroup-Detect specific chemical groups in molecules.+Detect functional groups from the global-chem curated library.-**Constructor:**```python-ChemicalGroup(groups: List[str], custom_smarts: Optional[Dict[str, str]] = None)+ChemicalGroup(groups=None, n_jobs=None, groups_db=None)```-**Parameters:**-- `groups`: List of predefined group names-- `custom_smarts`: Dictionary mapping custom group names to SMARTS patterns--**Predefined Groups:**-- `"hinge_binders"`: Kinase hinge binding motifs-- `"phosphate_binders"`: Phosphate binding groups-- `"michael_acceptors"`: Michael acceptor electrophiles-- `"reactive_groups"`: General reactive functionalities-**Methods:**```python-has_match(mols: List[Chem.Mol]) -> List[bool]-```--Check if molecules contain any of the specified groups.--```python-get_matches(mol: Chem.Mol) -> Dict[str, List[Tuple]]-```--Get detailed match information for a single molecule.--**Returns:** Dictionary mapping group names to lists of atom indices--```python-get_all_matches(mols: List[Chem.Mol]) -> List[Dict]-```--Get match information for all molecules.--**Example:**-```python-group = mc.groups.ChemicalGroup(groups=["hinge_binders", "phosphate_binders"])-matches = group.get_all_matches(mol_list)+has_match(mol, exact_match=False, terminal_only=False) -> bool+get_matches(mol, use_smiles=True, exact_match=False, terminal_only=False) -> dict+filter(mols) -> list[Mol]+get_catalog() -> FilterCatalog+list_groups() -> list+list_hierarchy_groups() -> list```------## Module: medchem.catalogs--### Class: NamedCatalogs--Access to curated chemical catalogs.--**Available Catalogs:**-- `"functional_groups"`: Common functional groups-- `"protecting_groups"`: Protecting group structures-- `"reagents"`: Common reagents-- `"fragments"`: Standard fragments+**Listing helpers:**-**Usage:**```python-catalog = mc.catalogs.NamedCatalogs.get("functional_groups")-matches = catalog.get_matches(mol)+mc.groups.list_default_chemical_groups(hierarchy=False)+mc.groups.list_functional_group_names(unique=True)+mc.groups.get_functional_group_map() # name → SMARTS```---## Module: medchem.complexity-Calculate molecular complexity metrics.--### calculate_complexity()--```python-calculate_complexity(mol: Chem.Mol, method: str = "bertz") -> float-```--Calculate complexity score for a molecule.--**Parameters:**-- `mol`: RDKit molecule-- `method`: Complexity metric ("bertz", "whitlock", "barone")--**Returns:** Complexity score (higher = more complex)-### Class: ComplexityFilter-Filter molecules by complexity threshold.+Compare a metric to ZINC-15 percentile thresholds. Operates on **single molecules**.-**Constructor:**```python-ComplexityFilter(max_complexity: float, method: str = "bertz")+ComplexityFilter(+ limit="99",+ complexity_metric="bertz",+ threshold_stats_file="zinc_15_available",+)+cf(mol) # -> bool```-**Methods:**+**Available metrics** (`ComplexityFilter.list_default_available_filters()`):+`bertz`, `sas`, `qed`, `clogp`, `whitlock`, `barone`, `smcm`, `twc`++**Direct metric functions:**```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1) -> List[bool]+mc.complexity.WhitlockCT(mol)+mc.complexity.BaroneCT(mol)+mc.complexity.SMCM(mol)+mc.complexity.TWC(mol)```-Filter molecules exceeding complexity threshold.+For batch filtering, use `mc.functional.complexity_filter()`.---@@ -414,187 +243,89 @@ Filter molecules exceeding complexity threshold.### Class: Constraints-Apply custom property-based constraints.+Scaffold-based substructure matching with per-atom constraint functions — **not** simple property-range filters.-**Constructor:**```python-Constraints(- mw_range: Optional[Tuple[float, float]] = None,- logp_range: Optional[Tuple[float, float]] = None,- tpsa_max: Optional[float] = None,- tpsa_range: Optional[Tuple[float, float]] = None,- hbd_max: Optional[int] = None,- hba_max: Optional[int] = None,- rotatable_bonds_max: Optional[int] = None,- rings_range: Optional[Tuple[int, int]] = None,- aromatic_rings_max: Optional[int] = None,-)+Constraints(core: Mol, constraint_fns: Dict[str, Callable], prop_name: str = "query")+constraints(mol) # -> bool or match details```-**Parameters:** All parameters are optional. Specify only the constraints needed.--**Methods:**--```python-__call__(mols: List[Chem.Mol], n_jobs: int = 1) -> List[Dict]-```--Apply constraints to molecules.--**Returns:** List of dictionaries with keys:-- `passes`: Boolean indicating if all constraints pass-- `violations`: List of constraint names that failed--**Example:**-```python-constraints = mc.constraints.Constraints(- mw_range=(200, 500),- logp_range=(-2, 5),- tpsa_max=140-)-results = constraints(mols=mol_list, n_jobs=-1)-```+Use `RuleFilters` or the query language for MW/LogP/TPSA bounds.---## Module: medchem.query-Query language for complex filtering.+### Class: QueryFilter-### parse()+Parse and evaluate the medchem query language.```python-parse(query: str) -> Query+QueryFilter(query: str, grammar: Optional[str] = None, parser: str = "lalr")+qf(mols, n_jobs=-1, progress=True, scheduler="processes") -> list[bool]```-Parse a medchem query string into a Query object.+**Grammar constructs:**-**Query Syntax:**-- Operators: `AND`, `OR`, `NOT`-- Comparisons: `<`, `>`, `<=`, `>=`, `==`, `!=`-- Properties: `complexity`, `lilly_demerits`, `mw`, `logp`, `tpsa`-- Rules: `rule_of_five`, `rule_of_cns`, etc.-- Filters: `common_alerts`, `nibr_filter`, `pains_filter`+| Construct | Example |+|-----------|---------|+| Rule match | `MATCHRULE("rule_of_five")` |+| Alert catalog | `HASALERT("pains")` |+| Property compare | `HASPROP("mw", <, 500)` |+| Chemical group | `HASGROUP("privileged_scaffolds")` |+| Substructure | `HASSUBSTRUCTURE("c1ccccc1")` |+| Superstructure | `HASSUPERSTRUCTURE("CCO")` |+| Boolean | `true`, `false` |+| Logic | `AND`, `OR`, `NOT` |-**Example Queries:**-```python-"rule_of_five AND NOT common_alerts"-"rule_of_cns AND complexity < 400"-"mw > 200 AND mw < 500 AND logp < 5"-"(rule_of_five OR rule_of_oprea) AND NOT pains_filter"-```--### Class: Query--**Methods:**+**Example queries:**```python-apply(mols: List[Chem.Mol], n_jobs: int = 1) -> List[bool]+'MATCHRULE("rule_of_five") AND NOT HASALERT("pains")'+'MATCHRULE("rule_of_cns") AND HASPROP("tpsa", <=, 90)'+'NOT HASALERT("brenk") AND HASPROP("mw", >=, 200)'```-Apply parsed query to molecules.+### Class: QueryOperator-**Example:**-```python-query = mc.query.parse("rule_of_five AND NOT common_alerts")-results = query.apply(mols=mol_list, n_jobs=-1)-passing_mols = [mol for mol, passes in zip(mol_list, results) if passes]-```-------## Module: medchem.utils--Utility functions for working with molecules.--### batch_process()--```python-batch_process(- mols: List[Chem.Mol],- func: Callable,- n_jobs: int = 1,- progress: bool = False,- batch_size: Optional[int] = None-) -> List-```--Process molecules in parallel batches.--**Parameters:**-- `mols`: List of molecules-- `func`: Function to apply to each molecule-- `n_jobs`: Number of parallel workers-- `progress`: Show progress bar-- `batch_size`: Size of processing batches--### standardize_mol()--```python-standardize_mol(mol: Chem.Mol) -> Chem.Mol-```--Standardize molecule representation (sanitize, neutralize charges, etc.).+Holds available properties, catalogs, rules, and functional groups used by the parser.---## Common Patterns-### Pattern: Parallel Processing--All filters support parallelization:+### Parallel processing```python-# Use all CPU cores-results = filter_object(mols=mol_list, n_jobs=-1, progress=True)--# Use specific number of cores-results = filter_object(mols=mol_list, n_jobs=4, progress=True)+df = mc.rules.RuleFilters(rule_list=["rule_of_five"])(mols=mol_list, n_jobs=-1, progress=True)+mask = mc.functional.nibr_filter(mols=mol_list, n_jobs=-1)```-### Pattern: Combining Multiple Filters+### Combining filters```python-import medchem as mc--# Apply multiple filters-rule_filter = mc.rules.RuleFilters(rule_list=["rule_of_five"])-alert_filter = mc.structural.CommonAlertsFilters()-lilly_filter = mc.structural.LillyDemeritsFilters()+rules_df = mc.rules.RuleFilters(rule_list=["rule_of_five"])(mols=mol_list, n_jobs=-1)+alerts_df = mc.structural.CommonAlertsFilters()(mols=mol_list, n_jobs=-1)-# Get results-rule_results = rule_filter(mols=mol_list, n_jobs=-1)-alert_results = alert_filter(mols=mol_list, n_jobs=-1)-lilly_results = lilly_filter(mols=mol_list, n_jobs=-1)--# Combine criteria-passing_mols = [+passing = [mol for i, mol in enumerate(mol_list)- if rule_results[i]["passes"]- and not alert_results[i]["has_alerts"]- and lilly_results[i]["passes"]+ if rules_df.iloc[i]["pass_all"] and alerts_df.iloc[i]["pass_filter"]]```-### Pattern: Working with DataFrames+### Working with DataFrames```pythonimport pandas as pdimport datamol as dmimport medchem as mc-# Load datadf = pd.read_csv("molecules.csv")df["mol"] = df["smiles"].apply(dm.to_mol)-# Apply filters-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_cns"])-results = rfilter(mols=df["mol"].tolist(), n_jobs=-1)--# Add results to dataframe-df["passes_ro5"] = [r["rule_of_five"] for r in results]-df["passes_cns"] = [r["rule_of_cns"] for r in results]--# Filter dataframe-filtered_df = df[df["passes_ro5"] & df["passes_cns"]]+results = mc.rules.RuleFilters(rule_list=["rule_of_five", "rule_of_cns"])(+ mols=df["mol"].tolist(), n_jobs=-1+)+df = pd.concat([df, results.drop(columns=["mol"])], axis=1)+filtered = df[df["pass_all"]]```diff --git a/scientific-skills/medchem/references/rules_catalog.md b/scientific-skills/medchem/references/rules_catalog.mdindex a7754c60..163b8b09 100644--- a/scientific-skills/medchem/references/rules_catalog.md+++ b/scientific-skills/medchem/references/rules_catalog.md@@ -1,15 +1,18 @@# Medchem Rules and Filters Catalog-Comprehensive catalog of all available medicinal chemistry rules, structural alerts, and filters in medchem.+Catalog of medicinal chemistry rules, alert sets, and filters in **medchem 2.0.5**.## Table of Contents1. [Drug-Likeness Rules](#drug-likeness-rules)2. [Lead-Likeness Rules](#lead-likeness-rules)3. [Fragment Rules](#fragment-rules)-4. [CNS Rules](#cns-rules)+4. [CNS and Target-Class Rules](#cns-and-target-class-rules)5. [Structural Alert Filters](#structural-alert-filters)-6. [Chemical Group Patterns](#chemical-group-patterns)+6. [Named Catalogs](#named-catalogs)+7. [Complexity Metrics](#complexity-metrics)+8. [Chemical Group Collections](#chemical-group-collections)+9. [Filter Selection Guidelines](#filter-selection-guidelines)---@@ -17,588 +20,309 @@ Comprehensive catalog of all available medicinal chemistry rules, structural ale### Rule of Five (Lipinski)-**Reference:** Lipinski et al., Adv Drug Deliv Rev (1997) 23:3-25+**Reference:** Lipinski et al., *Adv Drug Deliv Rev* (1997) 23:3–25-**Purpose:** Predict oral bioavailability+**Criteria:** MW ≤ 500, LogP ≤ 5, HBD ≤ 5, HBA ≤ 10-**Criteria:**-- Molecular Weight ≤ 500 Da-- LogP ≤ 5-- Hydrogen Bond Donors ≤ 5-- Hydrogen Bond Acceptors ≤ 10--**Usage:**```pythonmc.rules.basic_rules.rule_of_five(mol)+# or+mc.rules.RuleFilters(rule_list=["rule_of_five"])```-**Notes:**-- One of the most widely used filters in drug discovery-- About 90% of orally active drugs comply with these rules-- Exceptions exist, especially for natural products and antibiotics-----+### Rule of Five Beyond-### Rule of Veber+**Reference:** Doak et al., (2015) — compounds beyond Ro5 for large binding sites-**Reference:** Veber et al., J Med Chem (2002) 45:2615-2623+**Criteria:** MW ≤ 1000, LogP ∈ [-2, 10], HBD ≤ 6, HBA ≤ 15, TPSA ≤ 250, rotatable bonds ≤ 20-**Purpose:** Additional criteria for oral bioavailability--**Criteria:**-- Rotatable Bonds ≤ 10-- Topological Polar Surface Area (TPSA) ≤ 140 Ų--**Usage:**```python-mc.rules.basic_rules.rule_of_veber(mol)+mc.rules.basic_rules.rule_of_five_beyond(mol)```-**Notes:**-- Complements Rule of Five-- TPSA correlates with cell permeability-- Rotatable bonds affect molecular flexibility-------### Rule of Drug+### Rule of Veber-**Purpose:** Combined drug-likeness assessment+**Reference:** Veber et al., *J Med Chem* (2002) 45:2615–2623-**Criteria:**-- Passes Rule of Five-- Passes Veber rules-- Does not contain PAINS substructures+**Criteria:** Rotatable bonds ≤ 10, TPSA ≤ 140 Ų-**Usage:**```python-mc.rules.basic_rules.rule_of_drug(mol)+mc.rules.basic_rules.rule_of_veber(mol)```-----### REOS (Rapid Elimination Of Swill)-**Reference:** Walters & Murcko, Adv Drug Deliv Rev (2002) 54:255-271+**Reference:** Walters & Murcko, *Adv Drug Deliv Rev* (2002) 54:255–271-**Purpose:** Filter out compounds unlikely to be drugs+**Criteria:** MW 200–500, LogP −5 to 5, HBD 0–5, HBA 0–10-**Criteria:**-- Molecular Weight: 200-500 Da-- LogP: -5 to 5-- Hydrogen Bond Donors: 0-5-- Hydrogen Bond Acceptors: 0-10--**Usage:**```pythonmc.rules.basic_rules.rule_of_reos(mol)```------### Golden Triangle+### Egan, Ghose, Pfizer, GSK, Xu-**Reference:** Johnson et al., J Med Chem (2009) 52:5487-5500+Additional literature filters available as `rule_of_egan`, `rule_of_ghose`, `rule_of_pfizer_3_75`, `rule_of_gsk_4_400`, `rule_of_xu`.-**Purpose:** Balance lipophilicity and molecular weight+### Rule of Druglike (Soft)-**Criteria:**-- 200 ≤ MW ≤ 50 × LogP + 400-- LogP: -2 to 5+Combined soft drug-likeness criteria:-**Usage:**```python-mc.rules.basic_rules.golden_triangle(mol)+mc.rules.basic_rules.rule_of_druglike_soft(mol)```-**Notes:**-- Defines optimal physicochemical space-- Visual representation resembles a triangle on MW vs LogP plot----## Lead-Likeness Rules### Rule of Oprea-**Reference:** Oprea et al., J Chem Inf Comput Sci (2001) 41:1308-1315+**Reference:** Oprea et al., *J Chem Inf Comput Sci* (2001) 41:1308–1315-**Purpose:** Identify lead-like compounds for optimization+**Criteria:** MW 200–350, LogP −2 to 4, rotatable bonds ≤ 7, rings ≤ 4-**Criteria:**-- Molecular Weight: 200-350 Da-- LogP: -2 to 4-- Rotatable Bonds ≤ 7-- Number of Rings ≤ 4--**Usage:**```pythonmc.rules.basic_rules.rule_of_oprea(mol)```-**Rationale:** Lead compounds should have "room to grow" during optimization------### Rule of Leadlike (Soft)-**Purpose:** Permissive lead-like criteria--**Criteria:**-- Molecular Weight: 250-450 Da-- LogP: -3 to 4-- Rotatable Bonds ≤ 10+**Criteria:** MW 250–450, LogP −3 to 4, rotatable bonds ≤ 10-**Usage:**```pythonmc.rules.basic_rules.rule_of_leadlike_soft(mol)```----### Rule of Leadlike (Strict)--**Purpose:** Restrictive lead-like criteria--**Criteria:**-- Molecular Weight: 200-350 Da-- LogP: -2 to 3.5-- Rotatable Bonds ≤ 7-- Number of Rings: 1-3--**Usage:**-```python-mc.rules.basic_rules.rule_of_leadlike_strict(mol)-```------## Fragment Rules### Rule of Three-**Reference:** Congreve et al., Drug Discov Today (2003) 8:876-877+**Reference:** Congreve et al., *Drug Discov Today* (2003) 8:876–877-**Purpose:** Screen fragment libraries for fragment-based drug discovery+**Criteria:** MW ≤ 300, LogP ≤ 3, HBD ≤ 3, HBA ≤ 3, rotatable bonds ≤ 3, PSA ≤ 60 Ų-**Criteria:**-- Molecular Weight ≤ 300 Da-- LogP ≤ 3-- Hydrogen Bond Donors ≤ 3-- Hydrogen Bond Acceptors ≤ 3-- Rotatable Bonds ≤ 3-- Polar Surface Area ≤ 60 Ų--**Usage:**```pythonmc.rules.basic_rules.rule_of_three(mol)```-**Notes:**-- Fragments are grown into leads during optimization-- Lower complexity allows more starting points+Also available: `rule_of_three_extended`, `rule_of_two`, `rule_of_four`.----## CNS Rules+## CNS and Target-Class Rules### Rule of CNS-**Purpose:** Central nervous system drug-likeness--**Criteria:**-- Molecular Weight ≤ 450 Da-- LogP: -1 to 5-- Hydrogen Bond Donors ≤ 2-- TPSA ≤ 90 Ų+**Criteria:** MW ≤ 450, LogP −1 to 5, HBD ≤ 2, TPSA ≤ 90 Ų-**Usage:**```pythonmc.rules.basic_rules.rule_of_cns(mol)```-**Rationale:**-- Blood-brain barrier penetration requires specific properties-- Lower TPSA and HBD count improve BBB permeability-- Tight constraints reflect CNS challenges-------## Structural Alert Filters--### PAINS (Pan Assay INterference compoundS)--**Reference:** Baell & Holloway, J Med Chem (2010) 53:2719-2740--**Purpose:** Identify compounds that interfere with assays+### Rule of Respiratory-**Categories:**-- Catechols-- Quinones-- Rhodanines-- Hydroxyphenylhydrazones-- Alkyl/aryl aldehydes-- Michael acceptors (specific patterns)+Target-class filter for respiratory drugs:-**Usage:**```python-mc.rules.basic_rules.pains_filter(mol)-# Returns True if NO PAINS found+mc.rules.basic_rules.rule_of_respiratory(mol)```-**Notes:**-- PAINS compounds show activity in multiple assays through non-specific mechanisms-- Common false positives in screening campaigns-- Should be deprioritized in lead selection+### Generative Design Rules------### Common Alerts Filters--**Source:** Derived from ChEMBL curation and medicinal chemistry literature--**Purpose:** Flag common problematic structural patterns--**Alert Categories:**-1. **Reactive Groups**- - Epoxides- - Aziridines- - Acid halides- - Isocyanates--2. **Metabolic Liabilities**- - Hydrazines- - Thioureas- - Anilines (certain patterns)--3. **Aggregators**- - Polyaromatic systems- - Long aliphatic chains--4. **Toxicophores**- - Nitro aromatics- - Aromatic N-oxides- - Certain heterocycles--**Usage:**-```python-alert_filter = mc.structural.CommonAlertsFilters()-has_alerts, details = alert_filter.check_mol(mol)-```+For ML-generated molecules:-**Return Format:**```python-{- "has_alerts": True,- "alert_details": ["reactive_epoxide", "metabolic_hydrazine"],- "num_alerts": 2-}+mc.rules.basic_rules.rule_of_generative_design(mol)+mc.rules.basic_rules.rule_of_generative_design_strict(mol)```----### NIBR Filters+## Structural Alert Filters-**Source:** Novartis Institutes for BioMedical Research+### PAINS (Pan Assay INterference compoundS)-**Purpose:** Industrial medicinal chemistry filtering rules+**Reference:** Baell & Holloway, *J Med Chem* (2010) 53:2719–2740-**Features:**-- Proprietary filter set developed from Novartis experience-- Balances drug-likeness with practical medicinal chemistry-- Includes both structural alerts and property filters+Apply via named catalog — not a `basic_rules` function:-**Usage:**```python-nibr_filter = mc.structural.NIBRFilters()-results = nibr_filter(mols=mol_list, n_jobs=-1)+mc.functional.alert_filter(mols, alerts=["pains"], n_jobs=-1)+# or query: NOT HASALERT("pains")```-**Return Format:** Boolean list (True = passes)-------### Lilly Demerits Filter+Sub-catalogs: `pains_a`, `pains_b`, `pains_c`.-**Reference:** Based on Eli Lilly medicinal chemistry rules--**Source:** 275 structural patterns accumulated over 18 years--**Purpose:** Identify assay interference and problematic functionalities--**Mechanism:**-- Each matched pattern adds demerits-- Molecules with >100 demerits are rejected-- Some patterns add 10-50 demerits, others add 100+ (instant rejection)--**Demerit Categories:**--1. **High Demerits (>50):**- - Known toxic groups- - Highly reactive functionalities- - Strong metal chelators--2. **Medium Demerits (20-50):**- - Metabolic liabilities- - Aggregation-prone structures- - Frequent hitters+### Common Alerts Filters-3. **Low Demerits (5-20):**- - Minor concerns- - Context-dependent issues+ChEMBL-curated rule sets (Glaxo, Dundee, BMS, MLSMR, etc.):-**Usage:**```python-lilly_filter = mc.structural.LillyDemeritsFilters()-results = lilly_filter(mols=mol_list, n_jobs=-1)+alert_filter = mc.structural.CommonAlertsFilters()+df = alert_filter(mols=mol_list, n_jobs=-1)+# status: exclude | flag | annotations | ok```-**Return Format:**-```python-{- "demerits": 35,- "passes": True, # (demerits ≤ 100)- "matched_patterns": [- {"pattern": "phenolic_ester", "demerits": 20},- {"pattern": "aniline_derivative", "demerits": 15}- ]-}-```+### NIBR Filters----+Novartis screening-deck curation ([Schuffenhauer et al., 2020](https://dx.doi.org/10.1021/acs.jmedchem.0c01332)):-## Chemical Group Patterns+```python+nibr_filter = mc.structural.NIBRFilters()+df = nibr_filter(mols=mol_list, n_jobs=-1)+# severity >= 10 → excluded by default+```-### Hinge Binders+Or via functional API with `max_severity=10`.-**Purpose:** Identify kinase hinge-binding motifs+### Lilly Demerits (optional)-**Common Patterns:**-- Aminopyridines-- Aminopyrimidines-- Indazoles-- Benzimidazoles+Requires `mamba install lilly-medchem-rules`. 275 structural patterns; default exclusion at >160 demerits:-**Usage:**```python-group = mc.groups.ChemicalGroup(groups=["hinge_binders"])-has_hinge = group.has_match(mol_list)+mc.functional.lilly_demerit_filter(mols, max_demerits=160, n_jobs=-1)```-**Application:** Kinase inhibitor design-----### Phosphate Binders+## Named Catalogs-**Purpose:** Identify phosphate-binding groups+Available via `mc.catalogs.list_named_catalogs()` and `NamedCatalogs` static methods:-**Common Patterns:**-- Basic amines in specific geometries-- Guanidinium groups-- Arginine mimetics+| Catalog | Purpose |+|---------|---------|+| `pains`, `pains_a/b/c` | PAINS substructure filters |+| `brenk` | Unwanted functional groups |+| `nih` | NIH screening filters |+| `zinc` | ZINC structural filters |+| `glaxo`, `dundee`, `bms` | Pharma-derived alert sets |+| `mlsmr`, `inpharmatica`, `lint` | Additional screening sets |+| `nibr` | NIBR catalog (substructure) |+| `bredt` | Bredt rule violations (unstable structures) |+| `tox`, `toxicophore`, `carcinogen` | Toxicity patterns |+| `reactive_unstable_toxic` | Reactive/unstable groups |+| `unstable_graph` | Unstable molecular graphs |-**Usage:**```python-group = mc.groups.ChemicalGroup(groups=["phosphate_binders"])+cat = mc.catalogs.NamedCatalogs.brenk()+passes = mc.functional.catalog_filter(mols, catalogs=[cat], n_jobs=-1)```-**Application:** Kinase inhibitors, phosphatase inhibitors-----### Michael Acceptors+## Complexity Metrics-**Purpose:** Identify electrophilic Michael acceptor groups+Compared to ZINC-15 percentile thresholds via `ComplexityFilter` or `complexity_filter()`:-**Common Patterns:**-- α,β-Unsaturated carbonyls-- α,β-Unsaturated nitriles-- Vinyl sulfones-- Acrylamides+| Metric | Description |+|--------|-------------|+| `bertz` | Bertz molecular complexity |+| `sas` | Synthetic accessibility score |+| `qed` | Quantitative Estimate of Drug-likeness |+| `clogp` | Calculated LogP |+| `whitlock` | Whitlock CT (rings, unsaturation, heteroatoms, chirality) |+| `barone` | Barone complexity |+| `smcm` | Synthetic complexity metric |+| `twc` | Total walk count |-**Usage:**```python-group = mc.groups.ChemicalGroup(groups=["michael_acceptors"])+mc.functional.complexity_filter(mols, complexity_metric="bertz", limit="99", n_jobs=-1)```-**Notes:**-- Can be desirable for covalent inhibitors-- Often flagged as reactive alerts in screening+`limit="99"` keeps compounds below the 99th percentile on ZINC-15.----### Reactive Groups+## Chemical Group Collections-**Purpose:** Identify generally reactive functionalities+Browse with `mc.groups.list_default_chemical_groups()`:-**Common Patterns:**-- Epoxides-- Aziridines-- Acyl halides-- Isocyanates-- Sulfonyl chlorides+| Group | Application |+|-------|-------------|+| `privileged_scaffolds` | Common drug scaffolds |+| `common_warhead_covalent_inhibitors` | Covalent warhead patterns |+| `electrophilic_warheads_for_kinases` | Kinase covalent motifs |+| `rings_in_drugs` | Ring systems in approved drugs |+| `phase_2_hetereocyclic_rings` | Phase 2 heterocycles |+| `common_monomer_repeating_units` | Polymer/repeating units |+| `emerging_perfluoroalkyls` | PFAS-related patterns |-**Usage:**```python-group = mc.groups.ChemicalGroup(groups=["reactive_groups"])+group = mc.groups.ChemicalGroup(groups=["privileged_scaffolds"])+group.has_match(mol)```------## Custom SMARTS Patterns--Define custom structural patterns using SMARTS:--```python-custom_patterns = {- "my_warhead": "[C;H0](=O)C(F)(F)F", # Trifluoromethyl ketone- "my_scaffold": "c1ccc2c(c1)ncc(n2)N", # Aminobenzimidazole-}--group = mc.groups.ChemicalGroup(- groups=["hinge_binders"],- custom_smarts=custom_patterns-)-```+Custom groups: provide a CSV via `groups_db` with columns `smiles`/`smarts`, `name`, `group`.---## Filter Selection Guidelines-### Initial Screening (High-Throughput)--Recommended filters:-- Rule of Five-- PAINS filter-- Common Alerts (permissive settings)+### Initial Screening (HTS deck)```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_five", "pains_filter"])-alert_filter = mc.structural.CommonAlertsFilters()+qf = mc.query.QueryFilter('MATCHRULE("rule_of_five") AND NOT HASALERT("pains")')+mask = qf(mols=mol_list, n_jobs=-1)```-----### Hit-to-Lead-Recommended filters:-- Rule of Oprea or Leadlike (soft)-- NIBR filters-- Lilly Demerits-```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_oprea"])-nibr_filter = mc.structural.NIBRFilters()-lilly_filter = mc.structural.LillyDemeritsFilters()+rules = mc.rules.RuleFilters(rule_list=["rule_of_oprea"])(mols, n_jobs=-1)+nibr = mc.structural.NIBRFilters()(mols, n_jobs=-1)```-----### Lead Optimization-Recommended filters:-- Rule of Drug-- Leadlike (strict)-- Full structural alert analysis-- Complexity filters-```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_drug", "rule_of_leadlike_strict"])-alert_filter = mc.structural.CommonAlertsFilters()-complexity_filter = mc.complexity.ComplexityFilter(max_complexity=400)+rules = mc.rules.RuleFilters(rule_list=["rule_of_druglike_soft"])(mols, n_jobs=-1)+alerts = mc.structural.CommonAlertsFilters()(mols, n_jobs=-1)+complexity = mc.functional.complexity_filter(mols, complexity_metric="bertz", limit="95", n_jobs=-1)```-----### CNS Targets-Recommended filters:-- Rule of CNS-- Reduced PAINS criteria (CNS-focused)-- BBB permeability constraints-```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_cns"])-constraints = mc.constraints.Constraints(- tpsa_max=90,- hbd_max=2,- mw_range=(300, 450)-)+qf = mc.query.QueryFilter('MATCHRULE("rule_of_cns") AND HASPROP("tpsa", <=, 90)')+mask = qf(mols, n_jobs=-1)```------### Fragment-Based Drug Discovery--Recommended filters:-- Rule of Three-- Minimal complexity-- Basic reactive group check+### Fragment-Based Discovery```python-rfilter = mc.rules.RuleFilters(rule_list=["rule_of_three"])-complexity_filter = mc.complexity.ComplexityFilter(max_complexity=250)+rules = mc.rules.RuleFilters(rule_list=["rule_of_three"])(mols, n_jobs=-1)+complexity = mc.functional.complexity_filter(mols, complexity_metric="bertz", limit="90", n_jobs=-1)```---## Important Considerations-### False Positives and False Negatives-**Filters are guidelines, not absolutes:**+- ~10% of marketed oral drugs violate Ro5+- Natural products and prodrugs often fail standard rules+- Passing filters does not guarantee clinical success-1. **False Positives** (good drugs flagged):- - ~10% of marketed drugs fail Rule of Five- - Natural products often violate standard rules- - Prodrugs intentionally break rules- - Antibiotics and antivirals frequently non-compliant--2. **False Negatives** (bad compounds passing):- - Passing filters doesn't guarantee success- - Target-specific issues not captured- - In vivo properties not fully predicted--### Context-Specific Application--**Different contexts require different criteria:**--- **Target Class:** Kinases vs GPCRs vs ion channels have different optimal spaces-- **Modality:** Small molecules vs PROTACs vs molecular glues-- **Administration Route:** Oral vs IV vs topical-- **Disease Area:** CNS vs oncology vs infectious disease-- **Stage:** Screening vs hit-to-lead vs lead optimization--### Complementing with Machine Learning--Modern approaches combine rules with ML:+**Combine with ML when appropriate:**```python-# Rule-based pre-filtering-rule_results = mc.rules.RuleFilters(rule_list=["rule_of_five"])(mols)-filtered_mols = [mol for mol, r in zip(mols, rule_results) if r["passes"]]--# ML model scoring on filtered set-ml_scores = ml_model.predict(filtered_mols)--# Combined decision-final_candidates = [- mol for mol, score in zip(filtered_mols, ml_scores)- if score > threshold-]+rules_df = mc.rules.RuleFilters(rule_list=["rule_of_five"])(mols, n_jobs=-1)+filtered_mols = [m for m, ok in zip(mols, rules_df["pass_all"]) if ok]+# score filtered_mols with downstream ML model```---## References-1. Lipinski CA et al. Adv Drug Deliv Rev (1997) 23:3-25-2. Veber DF et al. J Med Chem (2002) 45:2615-2623-3. Oprea TI et al. J Chem Inf Comput Sci (2001) 41:1308-1315-4. Congreve M et al. Drug Discov Today (2003) 8:876-877-5. Baell JB & Holloway GA. J Med Chem (2010) 53:2719-2740-6. Johnson TW et al. J Med Chem (2009) 52:5487-5500-7. Walters WP & Murcko MA. Adv Drug Deliv Rev (2002) 54:255-271-8. Hann MM & Oprea TI. Curr Opin Chem Biol (2004) 8:255-263-9. Rishton GM. Drug Discov Today (1997) 2:382-384+1. Lipinski CA et al. *Adv Drug Deliv Rev* (1997) 23:3–25+2. Veber DF et al. *J Med Chem* (2002) 45:2615–2623+3. Oprea TI et al. *J Chem Inf Comput Sci* (2001) 41:1308–1315+4. Congreve M et al. *Drug Discov Today* (2003) 8:876–877+5. Baell JB & Holloway GA. *J Med Chem* (2010) 53:2719–2740+6. Walters WP & Murcko MA. *Adv Drug Deliv Rev* (2002) 54:255–271+7. Schuffenhauer A et al. *J Med Chem* (2020) — NIBR screening deck+8. Doak BC et al. (2015) — Beyond Rule of Fivediff --git a/scientific-skills/medchem/scripts/filter_molecules.py b/scientific-skills/medchem/scripts/filter_molecules.pyindex e9423cde..b020d681 100644--- a/scientific-skills/medchem/scripts/filter_molecules.py+++ b/scientific-skills/medchem/scripts/filter_molecules.py@@ -1,21 +1,17 @@#!/usr/bin/env python3"""-Batch molecular filtering using medchem library.--This script provides a production-ready workflow for filtering compound libraries-using medchem rules, structural alerts, and custom constraints.+Batch molecular filtering using the medchem library.Usage:- python filter_molecules.py input.csv --rules rule_of_five,rule_of_cns --alerts nibr --output filtered.csv- python filter_molecules.py input.sdf --rules rule_of_drug --lilly --complexity 400 --output results.csv- python filter_molecules.py smiles.txt --nibr --pains --n-jobs -1 --output clean.csv+ uv run python filter_molecules.py input.csv --rules rule_of_five,rule_of_cns --pains --output filtered.csv+ uv run python filter_molecules.py input.sdf --rules rule_of_veber --nibr --complexity 99 --output results.csv+ uv run python filter_molecules.py smiles.txt --query 'MATCHRULE("rule_of_five") AND NOT HASALERT("pains")' --output clean.csv"""import argparseimport sysfrom pathlib import Path-from typing import List, Dict, Optional, Tuple-import json+from typing import List, Optional, Tupletry:import pandas as pd@@ -25,30 +21,20 @@ try:from tqdm import tqdmexcept ImportError as e:print(f"Error: Missing required package: {e}")- print("Install dependencies: pip install medchem datamol pandas tqdm")+ print("Install dependencies: uv pip install medchem datamol pandas tqdm")sys.exit(1)-def load_molecules(input_file: Path, smiles_column: str = "smiles") -> Tuple[pd.DataFrame, List[Chem.Mol]]:- """- Load molecules from various file formats.-- Supports:- - CSV/TSV with SMILES column- - SDF files- - Plain text files with one SMILES per line-- Returns:- Tuple of (DataFrame with metadata, list of RDKit molecules)- """+def load_molecules(+ input_file: Path, smiles_column: str = "smiles"+) -> Tuple[pd.DataFrame, List[Chem.Mol]]:+ """Load molecules from CSV/TSV, SDF, or plain SMILES text files."""suffix = input_file.suffix.lower()if suffix == ".sdf":print(f"Loading SDF file: {input_file}")supplier = Chem.SDMolSupplier(str(input_file))mols = [mol for mol in supplier if mol is not None]-- # Create DataFrame from SDF propertiesdata = []for mol in mols:props = mol.GetPropsAsDict()@@ -60,22 +46,19 @@ def load_molecules(input_file: Path, smiles_column: str = "smiles") -> Tuple[pd.print(f"Loading CSV/TSV file: {input_file}")sep = "\t" if suffix == ".tsv" else ","df = pd.read_csv(input_file, sep=sep)-if smiles_column not in df.columns:- print(f"Error: Column '{smiles_column}' not found in file")+ print(f"Error: Column '{smiles_column}' not found")print(f"Available columns: {', '.join(df.columns)}")sys.exit(1)-- print(f"Converting SMILES to molecules...")+ print("Converting SMILES to molecules...")mols = [dm.to_mol(smi) for smi in tqdm(df[smiles_column], desc="Parsing")]elif suffix == ".txt":print(f"Loading text file: {input_file}")with open(input_file) as f:smiles_list = [line.strip() for line in f if line.strip()]-df = pd.DataFrame({"smiles": smiles_list})- print(f"Converting SMILES to molecules...")+ print("Converting SMILES to molecules...")mols = [dm.to_mol(smi) for smi in tqdm(smiles_list, desc="Parsing")]else:@@ -83,7 +66,6 @@ def load_molecules(input_file: Path, smiles_column: str = "smiles") -> Tuple[pd.print("Supported formats: .csv, .tsv, .sdf, .txt")sys.exit(1)- # Filter out invalid moleculesvalid_indices = [i for i, mol in enumerate(mols) if mol is not None]if len(valid_indices) < len(mols):n_invalid = len(mols) - len(valid_indices)@@ -95,319 +77,221 @@ def load_molecules(input_file: Path, smiles_column: str = "smiles") -> Tuple[pd.return df, mols-def apply_rule_filters(mols: List[Chem.Mol], rules: List[str], n_jobs: int) -> pd.DataFrame:- """Apply medicinal chemistry rule filters."""+def apply_rule_filters(+ mols: List[Chem.Mol], rules: List[str], n_jobs: int+) -> pd.DataFrame:+ """Apply medicinal chemistry rule filters. Returns rule result columns."""print(f"\nApplying rule filters: {', '.join(rules)}")-rfilter = mc.rules.RuleFilters(rule_list=rules)results = rfilter(mols=mols, n_jobs=n_jobs, progress=True)-- # Convert to DataFrame- df_results = pd.DataFrame(results)-- # Add summary column- df_results["passes_all_rules"] = df_results.all(axis=1)-- return df_results---def apply_structural_alerts(mols: List[Chem.Mol], alert_type: str, n_jobs: int) -> pd.DataFrame:- """Apply structural alert filters."""- print(f"\nApplying {alert_type} structural alerts...")-- if alert_type == "common":- alert_filter = mc.structural.CommonAlertsFilters()- results = alert_filter(mols=mols, n_jobs=n_jobs, progress=True)-- df_results = pd.DataFrame({- "has_common_alerts": [r["has_alerts"] for r in results],- "num_common_alerts": [r["num_alerts"] for r in results],- "common_alert_details": [", ".join(r["alert_details"]) if r["alert_details"] else "" for r in results]- })-- elif alert_type == "nibr":- nibr_filter = mc.structural.NIBRFilters()- results = nibr_filter(mols=mols, n_jobs=n_jobs, progress=True)-- df_results = pd.DataFrame({- "passes_nibr": results- })-- elif alert_type == "lilly":- lilly_filter = mc.structural.LillyDemeritsFilters()- results = lilly_filter(mols=mols, n_jobs=n_jobs, progress=True)-- df_results = pd.DataFrame({- "lilly_demerits": [r["demerits"] for r in results],- "passes_lilly": [r["passes"] for r in results],- "lilly_patterns": [", ".join([p["pattern"] for p in r["matched_patterns"]]) for r in results]- })-- elif alert_type == "pains":- results = [mc.rules.basic_rules.pains_filter(mol) for mol in tqdm(mols, desc="PAINS")]-- df_results = pd.DataFrame({- "passes_pains": results- })-- else:- raise ValueError(f"Unknown alert type: {alert_type}")-- return df_results+ return results.drop(columns=["mol"], errors="ignore")-def apply_complexity_filter(mols: List[Chem.Mol], max_complexity: float, method: str = "bertz") -> pd.DataFrame:- """Calculate molecular complexity."""- print(f"\nCalculating molecular complexity (method={method}, max={max_complexity})...")-- complexity_scores = [- mc.complexity.calculate_complexity(mol, method=method)- for mol in tqdm(mols, desc="Complexity")- ]-- df_results = pd.DataFrame({- "complexity_score": complexity_scores,- "passes_complexity": [score <= max_complexity for score in complexity_scores]- })+def apply_common_alerts(mols: List[Chem.Mol], n_jobs: int) -> pd.DataFrame:+ """Apply ChEMBL-derived common structural alerts."""+ print("\nApplying common structural alerts...")+ alert_filter = mc.structural.CommonAlertsFilters()+ results = alert_filter(mols=mols, n_jobs=n_jobs, progress=True)+ return results.drop(columns=["mol"], errors="ignore").rename(+ columns={"pass_filter": "passes_common_alerts", "status": "common_alert_status"}+ )- return df_results+def apply_nibr(mols: List[Chem.Mol], n_jobs: int) -> pd.DataFrame:+ """Apply NIBR screening-deck filters."""+ print("\nApplying NIBR filters...")+ nibr_filter = mc.structural.NIBRFilters()+ results = nibr_filter(mols=mols, n_jobs=n_jobs, progress=True)+ return results.drop(columns=["mol"], errors="ignore").rename(+ columns={"pass_filter": "passes_nibr", "status": "nibr_status"}+ )-def apply_constraints(mols: List[Chem.Mol], constraints: Dict, n_jobs: int) -> pd.DataFrame:- """Apply custom property constraints."""- print(f"\nApplying constraints: {constraints}")- constraint_filter = mc.constraints.Constraints(**constraints)- results = constraint_filter(mols=mols, n_jobs=n_jobs, progress=True)+def apply_alert_catalog(+ mols: List[Chem.Mol], alerts: List[str], n_jobs: int+) -> pd.DataFrame:+ """Apply named alert catalogs (pains, brenk, etc.)."""+ print(f"\nApplying alert catalogs: {', '.join(alerts)}")+ for alert in alerts:+ passes = mc.functional.alert_filter(+ mols=mols, alerts=[alert], n_jobs=n_jobs, progress=True+ )+ yield alert, passes+++def apply_lilly(mols: List[Chem.Mol], max_demerits: int, n_jobs: int) -> pd.DataFrame:+ """Apply Lilly demerit filter (requires lilly-medchem-rules)."""+ print(f"\nApplying Lilly demerits filter (max={max_demerits})...")+ try:+ passes = mc.functional.lilly_demerit_filter(+ mols=mols, max_demerits=max_demerits, n_jobs=n_jobs, progress=True+ )+ except ImportError as e:+ print(f"Warning: Lilly filter unavailable: {e}")+ print("Install with: mamba install -c conda-forge lilly-medchem-rules")+ return pd.DataFrame({"passes_lilly": [None] * len(mols)})+ return pd.DataFrame({"passes_lilly": passes})+++def apply_complexity(+ mols: List[Chem.Mol], limit: str, method: str, n_jobs: int+) -> pd.DataFrame:+ """Filter by complexity percentile threshold."""+ print(f"\nApplying complexity filter (metric={method}, limit={limit} percentile)...")+ passes = mc.functional.complexity_filter(+ mols=mols,+ complexity_metric=method,+ limit=limit,+ n_jobs=n_jobs,+ progress=True,+ )+ return pd.DataFrame({f"passes_complexity_{method}": passes})- df_results = pd.DataFrame({- "passes_constraints": [r["passes"] for r in results],- "constraint_violations": [", ".join(r["violations"]) if r["violations"] else "" for r in results]- })- return df_results+def apply_query(mols: List[Chem.Mol], query: str, n_jobs: int) -> pd.DataFrame:+ """Apply medchem query language filter."""+ print(f"\nApplying query: {query}")+ qf = mc.query.QueryFilter(query)+ passes = qf(mols=mols, n_jobs=n_jobs, progress=True)+ return pd.DataFrame({"passes_query": passes})-def apply_chemical_groups(mols: List[Chem.Mol], groups: List[str]) -> pd.DataFrame:- """Detect chemical groups."""+def apply_groups(mols: List[Chem.Mol], groups: List[str]) -> pd.DataFrame:+ """Detect chemical group matches."""print(f"\nDetecting chemical groups: {', '.join(groups)}")-- group_detector = mc.groups.ChemicalGroup(groups=groups)- results = group_detector.get_all_matches(mols)-- df_results = pd.DataFrame()- for group in groups:- df_results[f"has_{group}"] = [bool(r.get(group)) for r in results]-- return df_results+ detector = mc.groups.ChemicalGroup(groups=groups)+ return pd.DataFrame(+ {f"has_{g}": [detector.has_match(mol) for mol in mols] for g in groups}+ )-def generate_summary(df: pd.DataFrame, output_file: Path):- """Generate filtering summary report."""+def generate_summary(df: pd.DataFrame, output_file: Path) -> None:+ """Write a text summary of filtering results."""summary_file = output_file.parent / f"{output_file.stem}_summary.txt"+ pass_cols = [c for c in df.columns if c.startswith("passes_") or c == "pass_all"]with open(summary_file, "w") as f:- f.write("=" * 80 + "\n")- f.write("MEDCHEM FILTERING SUMMARY\n")- f.write("=" * 80 + "\n\n")-+ f.write("=" * 80 + "\nMEDCHEM FILTERING SUMMARY\n" + "=" * 80 + "\n\n")f.write(f"Total molecules processed: {len(df)}\n\n")- # Rule results- rule_cols = [col for col in df.columns if col.startswith("rule_") or col == "passes_all_rules"]- if rule_cols:- f.write("RULE FILTERS:\n")- f.write("-" * 40 + "\n")- for col in rule_cols:- if col in df.columns and df[col].dtype == bool:- n_pass = df[col].sum()- pct = 100 * n_pass / len(df)- f.write(f" {col}: {n_pass} passed ({pct:.1f}%)\n")- f.write("\n")-- # Structural alerts- alert_cols = [col for col in df.columns if "alert" in col.lower() or "nibr" in col.lower() or "lilly" in col.lower() or "pains" in col.lower()]- if alert_cols:- f.write("STRUCTURAL ALERTS:\n")- f.write("-" * 40 + "\n")- if "has_common_alerts" in df.columns:- n_clean = (~df["has_common_alerts"]).sum()- pct = 100 * n_clean / len(df)- f.write(f" No common alerts: {n_clean} ({pct:.1f}%)\n")- if "passes_nibr" in df.columns:- n_pass = df["passes_nibr"].sum()- pct = 100 * n_pass / len(df)- f.write(f" Passes NIBR: {n_pass} ({pct:.1f}%)\n")- if "passes_lilly" in df.columns:- n_pass = df["passes_lilly"].sum()- pct = 100 * n_pass / len(df)- f.write(f" Passes Lilly: {n_pass} ({pct:.1f}%)\n")- avg_demerits = df["lilly_demerits"].mean()- f.write(f" Average Lilly demerits: {avg_demerits:.1f}\n")- if "passes_pains" in df.columns:- n_pass = df["passes_pains"].sum()- pct = 100 * n_pass / len(df)- f.write(f" Passes PAINS: {n_pass} ({pct:.1f}%)\n")- f.write("\n")-- # Complexity- if "complexity_score" in df.columns:- f.write("COMPLEXITY:\n")- f.write("-" * 40 + "\n")- avg_complexity = df["complexity_score"].mean()- f.write(f" Average complexity: {avg_complexity:.1f}\n")- if "passes_complexity" in df.columns:- n_pass = df["passes_complexity"].sum()- pct = 100 * n_pass / len(df)- f.write(f" Within threshold: {n_pass} ({pct:.1f}%)\n")- f.write("\n")-- # Constraints- if "passes_constraints" in df.columns:- f.write("CONSTRAINTS:\n")- f.write("-" * 40 + "\n")- n_pass = df["passes_constraints"].sum()- pct = 100 * n_pass / len(df)- f.write(f" Passes all constraints: {n_pass} ({pct:.1f}%)\n")- f.write("\n")-- # Overall pass rate- pass_cols = [col for col in df.columns if col.startswith("passes_")]+ for col in pass_cols:+ if col in df.columns and df[col].dtype == bool:+ n_pass = df[col].sum()+ pct = 100 * n_pass / len(df) if len(df) else 0+ f.write(f" {col}: {n_pass} passed ({pct:.1f}%)\n")+if pass_cols:- df["passes_all_filters"] = df[pass_cols].all(axis=1)- n_pass = df["passes_all_filters"].sum()- pct = 100 * n_pass / len(df)- f.write("OVERALL:\n")- f.write("-" * 40 + "\n")- f.write(f" Molecules passing all filters: {n_pass} ({pct:.1f}%)\n")+ bool_cols = [c for c in pass_cols if c in df.columns and df[c].dtype == bool]+ if bool_cols:+ df["_passes_all"] = df[bool_cols].all(axis=1)+ n_all = df["_passes_all"].sum()+ pct = 100 * n_all / len(df) if len(df) else 0+ f.write(f"\n All filters passed: {n_all} ({pct:.1f}%)\n")f.write("\n" + "=" * 80 + "\n")print(f"\nSummary report saved to: {summary_file}")-def main():+def main() -> None:parser = argparse.ArgumentParser(description="Batch molecular filtering using medchem",formatter_class=argparse.RawDescriptionHelpFormatter,- epilog=__doc__+ epilog=__doc__,)-- # Input/Outputparser.add_argument("input", type=Path, help="Input file (CSV, TSV, SDF, or TXT)")parser.add_argument("--output", "-o", type=Path, required=True, help="Output CSV file")- parser.add_argument("--smiles-column", default="smiles", help="Name of SMILES column (default: smiles)")+ parser.add_argument("--smiles-column", default="smiles", help="SMILES column name (default: smiles)")- # Rule filters- parser.add_argument("--rules", help="Comma-separated list of rules (e.g., rule_of_five,rule_of_cns)")-- # Structural alerts+ parser.add_argument("--rules", help="Comma-separated rules (e.g. rule_of_five,rule_of_cns)")+ parser.add_argument("--query", help='Medchem query string (e.g. MATCHRULE("rule_of_five") AND NOT HASALERT("pains"))')parser.add_argument("--common-alerts", action="store_true", help="Apply common structural alerts")parser.add_argument("--nibr", action="store_true", help="Apply NIBR filters")- parser.add_argument("--lilly", action="store_true", help="Apply Lilly demerits filter")- parser.add_argument("--pains", action="store_true", help="Apply PAINS filter")-- # Complexity- parser.add_argument("--complexity", type=float, help="Maximum complexity threshold")- parser.add_argument("--complexity-method", default="bertz", choices=["bertz", "whitlock", "barone"],- help="Complexity calculation method")-- # Constraints- parser.add_argument("--mw-range", help="Molecular weight range (e.g., 200,500)")- parser.add_argument("--logp-range", help="LogP range (e.g., -2,5)")- parser.add_argument("--tpsa-max", type=float, help="Maximum TPSA")- parser.add_argument("--hbd-max", type=int, help="Maximum H-bond donors")- parser.add_argument("--hba-max", type=int, help="Maximum H-bond acceptors")- parser.add_argument("--rotatable-bonds-max", type=int, help="Maximum rotatable bonds")-- # Chemical groups- parser.add_argument("--groups", help="Comma-separated chemical groups to detect")+ parser.add_argument("--lilly", action="store_true", help="Apply Lilly demerits (requires lilly-medchem-rules)")+ parser.add_argument("--lilly-max", type=int, default=160, help="Max Lilly demerits (default: 160)")+ parser.add_argument(+ "--alerts",+ help="Comma-separated alert catalogs (e.g. pains,brenk). Shorthand for --pains when set to pains",+ )+ parser.add_argument("--pains", action="store_true", help="Apply PAINS filter (alias for --alerts pains)")- # Processing options- parser.add_argument("--n-jobs", type=int, default=-1, help="Number of parallel jobs (-1 = all cores)")- parser.add_argument("--no-summary", action="store_true", help="Don't generate summary report")+ parser.add_argument(+ "--complexity",+ help="Complexity percentile limit (e.g. 99 keeps below 99th percentile on ZINC-15)",+ )+ parser.add_argument(+ "--complexity-method",+ default="bertz",+ choices=["bertz", "sas", "qed", "clogp", "whitlock", "barone", "smcm", "twc"],+ help="Complexity metric (default: bertz)",+ )+ parser.add_argument("--groups", help="Comma-separated chemical groups to detect")+ parser.add_argument("--n-jobs", type=int, default=-1, help="Parallel jobs (-1 = all cores)")+ parser.add_argument("--no-summary", action="store_true", help="Skip summary report")parser.add_argument("--filter-output", action="store_true", help="Only output molecules passing all filters")args = parser.parse_args()- # Load molecules- df, mols = load_molecules(args.input, args.smiles_column)+ if not any([args.rules, args.query, args.common_alerts, args.nibr, args.lilly,+ args.pains, args.alerts, args.complexity, args.groups]):+ print("Error: Specify at least one filter (--rules, --query, --pains, --nibr, etc.)")+ sys.exit(1)- # Apply filters- result_dfs = [df]+ df, mols = load_molecules(args.input, args.smiles_column)+ result_parts = [df.reset_index(drop=True)]- # Rulesif args.rules:rule_list = [r.strip() for r in args.rules.split(",")]- df_rules = apply_rule_filters(mols, rule_list, args.n_jobs)- result_dfs.append(df_rules)+ unknown = set(rule_list) - set(mc.rules.RuleFilters.list_available_rules_names())+ if unknown:+ print(f"Warning: Unknown rules (will error at runtime): {', '.join(sorted(unknown))}")+ result_parts.append(apply_rule_filters(mols, rule_list, args.n_jobs))++ if args.query:+ result_parts.append(apply_query(mols, args.query, args.n_jobs))- # Structural alertsif args.common_alerts:- df_alerts = apply_structural_alerts(mols, "common", args.n_jobs)- result_dfs.append(df_alerts)+ result_parts.append(apply_common_alerts(mols, args.n_jobs))if args.nibr:- df_nibr = apply_structural_alerts(mols, "nibr", args.n_jobs)- result_dfs.append(df_nibr)+ result_parts.append(apply_nibr(mols, args.n_jobs))if args.lilly:- df_lilly = apply_structural_alerts(mols, "lilly", args.n_jobs)- result_dfs.append(df_lilly)+ result_parts.append(apply_lilly(mols, args.lilly_max, args.n_jobs))+ alert_list = []if args.pains:- df_pains = apply_structural_alerts(mols, "pains", args.n_jobs)- result_dfs.append(df_pains)+ alert_list.append("pains")+ if args.alerts:+ alert_list.extend(a.strip() for a in args.alerts.split(","))+ for alert in dict.fromkeys(alert_list):+ col_name = f"passes_{alert}"+ _, passes = next(apply_alert_catalog(mols, [alert], args.n_jobs))+ result_parts.append(pd.DataFrame({col_name: passes}))- # Complexityif args.complexity:- df_complexity = apply_complexity_filter(mols, args.complexity, args.complexity_method)- result_dfs.append(df_complexity)-- # Constraints- constraints = {}- if args.mw_range:- mw_min, mw_max = map(float, args.mw_range.split(","))- constraints["mw_range"] = (mw_min, mw_max)- if args.logp_range:- logp_min, logp_max = map(float, args.logp_range.split(","))- constraints["logp_range"] = (logp_min, logp_max)- if args.tpsa_max:- constraints["tpsa_max"] = args.tpsa_max- if args.hbd_max:- constraints["hbd_max"] = args.hbd_max- if args.hba_max:- constraints["hba_max"] = args.hba_max- if args.rotatable_bonds_max:- constraints["rotatable_bonds_max"] = args.rotatable_bonds_max-- if constraints:- df_constraints = apply_constraints(mols, constraints, args.n_jobs)- result_dfs.append(df_constraints)-- # Chemical groups+ result_parts.append(+ apply_complexity(mols, args.complexity, args.complexity_method, args.n_jobs)+ )+if args.groups:group_list = [g.strip() for g in args.groups.split(",")]- df_groups = apply_chemical_groups(mols, group_list)- result_dfs.append(df_groups)+ result_parts.append(apply_groups(mols, group_list))- # Combine results- df_final = pd.concat(result_dfs, axis=1)+ df_final = pd.concat(result_parts, axis=1)- # Filter output if requestedif args.filter_output:- pass_cols = [col for col in df_final.columns if col.startswith("passes_")]- if pass_cols:- df_final["passes_all"] = df_final[pass_cols].all(axis=1)- df_final = df_final[df_final["passes_all"]]+ pass_cols = [c for c in df_final.columns if c.startswith("passes_") or c == "pass_all"]+ bool_cols = [c for c in pass_cols if c in df_final.columns and df_final[c].dtype == bool]+ if bool_cols:+ mask = df_final[bool_cols].all(axis=1)+ df_final = df_final[mask]print(f"\nFiltered to {len(df_final)} molecules passing all filters")- # Save resultsargs.output.parent.mkdir(parents=True, exist_ok=True)df_final.to_csv(args.output, index=False)print(f"\nResults saved to: {args.output}")- # Generate summaryif not args.no_summary:generate_summary(df_final, args.output)diff --git a/scientific-skills/molfeat/SKILL.md b/scientific-skills/molfeat/SKILL.mdindex dd369362..6519d5e3 100644--- a/scientific-skills/molfeat/SKILL.md+++ b/scientific-skills/molfeat/SKILL.md@@ -2,6 +2,8 @@name: molfeatdescription: Molecular featurization for ML (100+ featurizers). ECFP, MACCS, descriptors, pretrained models (ChemBERTa), convert SMILES to features, for QSAR and molecular ML.license: Apache-2.0 license+allowed-tools: Read Write Edit Bash+compatibility: Requires Python 3.9–3.10 (molfeat 0.11.0 does not support 3.11+). Requires datamol, PyTorch, and optional extras for GNN/transformer models.metadata:skill-author: K-Dense Inc.---@@ -12,6 +14,8 @@ metadata:Molfeat is a comprehensive Python library for molecular featurization that unifies 100+ pre-trained embeddings and hand-crafted featurizers. Convert chemical structures (SMILES strings or RDKit molecules) into numerical representations for machine learning tasks including QSAR modeling, virtual screening, similarity searching, and deep learning applications. Features fast parallel processing, scikit-learn compatible transformers, and built-in caching.+**Version note:** Examples target **molfeat 0.11.0** (PyPI stable, May 2025). Requires **Python 3.9–3.10** (`requires-python` caps below 3.11). Depends on **datamol ≥0.8.0** and **PyTorch ≥1.13**. Since 0.8.7, prefer datamol `Mol` objects over raw `rdkit.Chem.Mol`. Since 0.10.1, fingerprint calculators use RDKit's `rdFingerprintGenerator` API internally. Since 0.11.0, pretrained models load in memory and base models are set to PyTorch evaluation mode automatically.+## When to Use This SkillThis skill should be used when working with:@@ -25,19 +29,24 @@ This skill should be used when working with:## Installation+Use a Python 3.9 or 3.10 environment (molfeat does not install on 3.11+ as of 0.11.0):+```bash-uv pip install molfeat+uv pip install "molfeat==0.11.0"-# With all optional dependencies-uv pip install "molfeat[all]"+# With all pip-installable optional dependencies+uv pip install "molfeat[all]==0.11.0"```-**Optional dependencies for specific featurizers:**-- `molfeat[dgl]` - GNN models (GIN variants)-- `molfeat[graphormer]` - Graphormer models-- `molfeat[transformer]` - ChemBERTa, ChemGPT, MolT5-- `molfeat[fcd]` - FCD descriptors-- `molfeat[map4]` - MAP4 fingerprints+**Optional dependency extras (PyPI):**+- `molfeat[dgl]` — GNN models (GIN variants); upstream recommends `dgl<=2.0` (graphbolt issues in newer DGL)+- `molfeat[graphormer]` — Graphormer models+- `molfeat[transformer]` — ChemBERTa, ChemGPT, MolT5+- `molfeat[fcd]` — FCD descriptors+- `molfeat[pyg]` — PyTorch Geometric featurizers+- `molfeat[viz]` — NGLView visualization widgets++**External featurizers:** MAP4 is not bundled in molfeat extras — install from [reymond-group/map4](https://github.com/reymond-group/map4) separately. Some heavy deps (DGL, dgllife, graphormer-pretrained) are easier via conda-forge; see [optional dependencies](https://molfeat-docs.datamol.io/stable/).## Core Concepts@@ -323,7 +332,7 @@ for name, feat in featurizers.items():transformer = MoleculeTransformer(feat, n_jobs=-1)X = transformer(smiles)# Evaluate with your ML model- score = evaluate_model(X, y)+ score = score_model(X, y)results[name] = score```@@ -373,6 +382,8 @@ transformer = CustomTransformer(FPCalculator("ecfp"), n_jobs=-1)### Batch Processing Large Datasets```python+import numpy as np+def featurize_in_chunks(smiles_list, transformer, chunk_size=10000):"""Process large datasets in chunks to manage memory"""all_features = []@@ -385,19 +396,20 @@ def featurize_in_chunks(smiles_list, transformer, chunk_size=10000):### Caching Expensive Embeddings+Prefer molfeat's built-in pretrained-model cache when possible. For custom embedding caches, use NumPy arrays instead of pickle (pickle can execute arbitrary code when loading untrusted files):+```python-import pickle+import numpy as np+from pathlib import Path-cache_file = "embeddings_cache.pkl"+cache_file = Path("embeddings_cache.npz") # fixed path under your projecttransformer = PretrainedMolTransformer("ChemBERTa-77M-MLM", n_jobs=-1)-try:- with open(cache_file, "rb") as f:- embeddings = pickle.load(f)-except FileNotFoundError:+if cache_file.exists():+ embeddings = np.load(cache_file)["embeddings"]+else:embeddings = transformer(smiles_list)- with open(cache_file, "wb") as f:- pickle.dump(embeddings, f)+ np.savez(cache_file, embeddings=embeddings)```## Performance Tips@@ -486,10 +498,11 @@ transformer = MoleculeTransformer(Process in chunks or use streaming approaches for datasets > 100K molecules.### Pretrained Model Dependencies-Some models require additional packages. Install specific extras:+Some models require additional packages. Install specific extras (pin version for reproducibility):```bash-uv pip install "molfeat[transformer]" # For ChemBERTa/ChemGPT-uv pip install "molfeat[dgl]" # For GIN models+uv pip install "molfeat[transformer]==0.11.0" # For ChemBERTa/ChemGPT+uv pip install "molfeat[dgl]==0.11.0" # For GIN models+uv pip install "molfeat[graphormer]==0.11.0" # For Graphormer```### Reproducibilitydiff --git a/scientific-skills/molfeat/references/api_reference.md b/scientific-skills/molfeat/references/api_reference.mdindex 752b14a6..ec20f5e2 100644--- a/scientific-skills/molfeat/references/api_reference.md+++ b/scientific-skills/molfeat/references/api_reference.md@@ -7,8 +7,9 @@ Molfeat is organized into several key modules that provide different aspects of- **`molfeat.store`** - Manages model loading, listing, and registration- **`molfeat.calc`** - Provides calculators for single-molecule featurization- **`molfeat.trans`** - Offers scikit-learn compatible transformers for batch processing+- **`molfeat.plugins`** - Plugin system for third-party featurizer extensions- **`molfeat.utils`** - Utility functions for data handling-- **`molfeat.viz`** - Visualization tools for molecular features+- **`molfeat.viz`** - Visualization tools for molecular features (requires `molfeat[viz]`)---diff --git a/scientific-skills/molfeat/references/available_featurizers.md b/scientific-skills/molfeat/references/available_featurizers.mdindex 08e00194..a03c0ae1 100644--- a/scientific-skills/molfeat/references/available_featurizers.md+++ b/scientific-skills/molfeat/references/available_featurizers.md@@ -261,14 +261,16 @@ Pre-trained GNN models from DGL-Life:### Model Dependencies-Some featurizers require optional dependencies:--- **DGL models** (gin-*, jtvae): `pip install "molfeat[dgl]"`-- **Graphormer**: `pip install "molfeat[graphormer]"`-- **Transformers** (ChemBERTa, ChemGPT, MolT5): `pip install "molfeat[transformer]"`-- **FCD**: `pip install "molfeat[fcd]"`-- **MAP4**: `pip install "molfeat[map4]"`-- **All dependencies**: `pip install "molfeat[all]"`+Some featurizers require optional dependencies (molfeat 0.11.0):++- **DGL models** (gin-*, jtvae): `uv pip install "molfeat[dgl]==0.11.0"` (upstream recommends `dgl<=2.0`)+- **Graphormer**: `uv pip install "molfeat[graphormer]==0.11.0"`+- **Transformers** (ChemBERTa, ChemGPT, MolT5): `uv pip install "molfeat[transformer]==0.11.0"`+- **FCD**: `uv pip install "molfeat[fcd]==0.11.0"`+- **PyTorch Geometric**: `uv pip install "molfeat[pyg]==0.11.0"`+- **Visualization**: `uv pip install "molfeat[viz]==0.11.0"`+- **MAP4**: external package — see [reymond-group/map4](https://github.com/reymond-group/map4) (not a molfeat PyPI extra)+- **All pip extras**: `uv pip install "molfeat[all]==0.11.0"`### Accessing All Available Modelsdiff --git a/scientific-skills/molfeat/references/examples.md b/scientific-skills/molfeat/references/examples.mdindex 16c937b3..d1f9e25a 100644--- a/scientific-skills/molfeat/references/examples.md+++ b/scientific-skills/molfeat/references/examples.md@@ -4,20 +4,20 @@ This document provides practical examples for common molfeat use cases.## Installation-```bash-# Recommended: Using conda/mamba-mamba install -c conda-forge molfeat+Requires Python 3.9 or 3.10 (molfeat 0.11.0 does not support 3.11+):-# Alternative: Using pip-pip install molfeat+```bash+uv pip install "molfeat==0.11.0"-# With all optional dependencies-pip install "molfeat[all]"+# With all pip-installable optional dependencies+uv pip install "molfeat[all]==0.11.0"# With specific dependencies-pip install "molfeat[dgl]" # For GNN models-pip install "molfeat[graphormer]" # For Graphormer-pip install "molfeat[transformer]" # For ChemBERTa, ChemGPT+uv pip install "molfeat[dgl]==0.11.0" # For GNN models+uv pip install "molfeat[graphormer]==0.11.0" # For Graphormer+uv pip install "molfeat[transformer]==0.11.0" # For ChemBERTa, ChemGPT+uv pip install "molfeat[pyg]==0.11.0" # For PyTorch Geometric+uv pip install "molfeat[viz]==0.11.0" # For NGLView widgets```---@@ -530,24 +530,21 @@ for n_jobs in [1, 2, 4, -1]:```pythonfrom molfeat.trans.pretrained import PretrainedMolTransformer-import pickle+import numpy as np+from pathlib import Path# Load expensive pretrained modeltransformer = PretrainedMolTransformer("ChemBERTa-77M-MLM", n_jobs=-1)-# Cache embeddings for reuse-cache_file = "embeddings_cache.pkl"+# Cache embeddings with NumPy (avoid pickle for untrusted paths)+cache_file = Path("embeddings_cache.npz")-try:- # Try loading cached embeddings- with open(cache_file, "rb") as f:- embeddings = pickle.load(f)+if cache_file.exists():+ embeddings = np.load(cache_file)["embeddings"]print("Loaded cached embeddings")-except FileNotFoundError:- # Compute and cache+else:embeddings = transformer(smiles_list)- with open(cache_file, "wb") as f:- pickle.dump(embeddings, f)+ np.savez(cache_file, embeddings=embeddings)print("Computed and cached embeddings")```diff --git a/scientific-skills/polars-bio/SKILL.md b/scientific-skills/polars-bio/SKILL.mdindex 0fcee270..679e13b4 100644--- a/scientific-skills/polars-bio/SKILL.md+++ b/scientific-skills/polars-bio/SKILL.md@@ -1,7 +1,9 @@---name: polars-biodescription: High-performance genomic interval operations and bioinformatics file I/O on Polars DataFrames. Overlap, nearest, merge, coverage, complement, subtract for BED/VCF/BAM/GFF intervals. Streaming, cloud-native, faster bioframe alternative.-license: https://github.com/biodatageeks/polars-bio/blob/main/LICENSE+license: Apache-2.0+allowed-tools: Read Write Edit Bash+compatibility: Requires Python 3.11–3.14 and polars-bio (uv pip install). Cloud I/O uses standard AWS/GCS/Azure SDK env vars when paths use s3://, gs://, or az:// URIs.metadata:skill-author: K-Dense Inc.---@@ -34,15 +36,16 @@ Use this skill when:### Installation+Requires Python 3.11–3.14 (see [PyPI](https://pypi.org/project/polars-bio/)).+```bash-pip install polars-bio-# or-uv pip install polars-bio+uv pip install "polars-bio==0.31.0"```-For pandas compatibility:+For pandas compatibility (pandas ≥3.0):+```bash-pip install polars-bio[pandas]+uv pip install "polars-bio[pandas]==0.31.0"```### Basic Overlap Example@@ -96,7 +99,7 @@ result = lf.collect()polars-bio provides 8 core interval operations for genomic range arithmetic. All operations accept Polars DataFrames with `chrom`, `start`, `end` columns (configurable). All operations return a `LazyFrame` by default (use `output_type="polars.DataFrame"` for eager results).**Operations:**-- `overlap` / `count_overlaps` - Find or count overlapping intervals between two sets+- `overlap` / `count_overlaps` - Find or count overlapping intervals between two sets (`overlap_output="left"` returns df1-only hits since 0.30.0)- `nearest` - Find nearest intervals (with configurable `k`, `overlap`, `distance` params)- `merge` - Merge overlapping/bookended intervals within a set- `cluster` - Assign cluster IDs to overlapping intervals@@ -133,11 +136,12 @@ Read and write common bioinformatics formats with `read_*`, `scan_*`, `write_*`,**Supported formats:**- **BED** - Genomic intervals (`read_bed`, `scan_bed`, `write_*` via generic)- **VCF** - Genetic variants (`read_vcf`, `scan_vcf`, `write_vcf`, `sink_vcf`)+- **VCF Zarr** - Analysis-ready Zarr stores (`read_vcf_zarr`, `scan_vcf_zarr`; local directory paths)- **BAM** - Aligned reads (`read_bam`, `scan_bam`, `write_bam`, `sink_bam`)- **CRAM** - Compressed alignments (`read_cram`, `scan_cram`, `write_cram`, `sink_cram`)- **GFF** - Gene annotations (`read_gff`, `scan_gff`)- **GTF** - Gene annotations (`read_gtf`, `scan_gtf`)-- **FASTA** - Reference sequences (`read_fasta`, `scan_fasta`)+- **FASTA** - Reference sequences (`read_fasta`, `scan_fasta`, `write_fasta`, `sink_fasta`)- **FASTQ** - Sequencing reads (`read_fastq`, `scan_fastq`, `write_fastq`, `sink_fastq`)- **SAM** - Text alignments (`read_sam`, `scan_sam`, `write_sam`, `sink_sam`)- **Hi-C pairs** - Chromatin contacts (`read_pairs`, `scan_pairs`)@@ -211,11 +215,11 @@ polars-bio defaults to **1-based** coordinates (genomic convention). This can be```pythonimport polars_bio as pb-# Switch to 0-based coordinates-pb.set_option("coordinate_system", "0-based")+# Switch to 0-based half-open coordinates (default is 1-based / False)+pb.set_option("datafusion.bio.coordinate_system_zero_based", True)# Switch back to 1-based (default)-pb.set_option("coordinate_system", "1-based")+pb.set_option("datafusion.bio.coordinate_system_zero_based", False)```I/O functions also accept `use_zero_based` to set coordinate metadata on the resulting DataFrame:@@ -302,8 +306,8 @@ For datasets larger than available RAM, use `scan_*` functions and streaming exe# Scan files lazilylf = pb.scan_bed("large_intervals.bed")-# Process with streaming-result = lf.collect(streaming=True)+# Process with Polars streaming (requires polars ≥1.37, bundled with polars-bio)+result = lf.collect(engine="streaming")```DataFusion streaming is enabled by default for interval operations, processing data in batches without loading the full dataset into memory.@@ -316,7 +320,7 @@ DataFusion streaming is enabled by default for interval operations, processing d3. **Column name mismatches:** polars-bio expects `chrom`, `start`, `end` by default. Use `cols1`/`cols2` parameters (as lists) if your columns have different names.-4. **Coordinate system metadata:** When constructing DataFrames manually (not via `read_*`/`scan_*`), polars-bio warns about missing coordinate metadata. Use `pb.set_option("coordinate_system", "0-based")` globally, or use I/O functions that set metadata automatically.+4. **Coordinate system metadata:** Interval operations read coordinate metadata from I/O functions or DataFrame `config_meta`. For manually built DataFrames, set `df.config_meta.set(coordinate_system_zero_based=True)` (0-based) or `False` (1-based). If metadata is missing, polars-bio falls back to the global `datafusion.bio.coordinate_system_zero_based` setting (with a warning). Set `pb.set_option("datafusion.bio.coordinate_system_check", True)` to raise `MissingCoordinateSystemError` instead. Mismatched systems between inputs raise `CoordinateSystemMismatchError`.5. **Probe-build order matters:** For overlap, nearest, and coverage, the first DataFrame is probed against the second. Swapping arguments changes which intervals appear in the left vs right output columns, and can affect performance.@@ -348,7 +352,7 @@ DataFusion streaming is enabled by default for interval operations, processing ddf = pb.read_vcf("large.vcf.gz").select("chrom", "start", "end", "ref", "alt")```-5. **Use cloud paths directly:** Pass S3/GCS/Azure URIs directly to read/scan functions instead of downloading files first:+5. **Use cloud paths directly:** Pass S3/GCS/Azure URIs directly to read/scan/register functions instead of downloading files first. Authenticated access uses your cloud SDK credentials (`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, `GOOGLE_APPLICATION_CREDENTIALS`, Azure defaults) only when those cloud paths are accessed:```pythondf = pb.read_bed("s3://my-bucket/regions.bed", allow_anonymous=True)```diff --git a/scientific-skills/polars-bio/references/bioframe_migration.md b/scientific-skills/polars-bio/references/bioframe_migration.mdindex 87b7ce17..52ff48a6 100644--- a/scientific-skills/polars-bio/references/bioframe_migration.md+++ b/scientific-skills/polars-bio/references/bioframe_migration.md@@ -206,7 +206,7 @@ import polars_bio as pb# Lazy scan, streaming executionlf = pb.scan_bed("huge_intervals.bed")-result = pb.merge(lf).collect(streaming=True)+result = pb.merge(lf).collect(engine="streaming")```## pandas Compatibility Mode@@ -214,7 +214,7 @@ result = pb.merge(lf).collect(streaming=True)For gradual migration, install with pandas support:```bash-pip install polars-bio[pandas]+uv pip install "polars-bio[pandas]==0.31.0"```This enables conversion between pandas and Polars DataFrames:diff --git a/scientific-skills/polars-bio/references/configuration.md b/scientific-skills/polars-bio/references/configuration.mdindex 23e2c1d8..d1f8af81 100644--- a/scientific-skills/polars-bio/references/configuration.md+++ b/scientific-skills/polars-bio/references/configuration.md@@ -45,7 +45,7 @@ pb.set_option("datafusion.execution.target_partitions", 8)## Coordinate Systems-polars-bio defaults to 1-based coordinates (standard genomic convention).+polars-bio defaults to **1-based** coordinates (genomic convention). Configure globally with the DataFusion bio option (boolean, not a string):### Global Coordinate System@@ -53,15 +53,25 @@ polars-bio defaults to 1-based coordinates (standard genomic convention).import polars_bio as pb# Switch to 0-based half-open coordinates-pb.set_option("coordinate_system", "0-based")+pb.set_option("datafusion.bio.coordinate_system_zero_based", True)# Switch back to 1-based (default)-pb.set_option("coordinate_system", "1-based")+pb.set_option("datafusion.bio.coordinate_system_zero_based", False)-# Check current setting-print(pb.get_option("coordinate_system"))+# Check current setting ("true" or "false")+print(pb.get_option("datafusion.bio.coordinate_system_zero_based"))```+### Strict Coordinate Metadata Checking++By default, missing coordinate metadata on manually constructed DataFrames triggers a warning and falls back to the global setting. Enable strict checking to raise `MissingCoordinateSystemError`:++```python+pb.set_option("datafusion.bio.coordinate_system_check", True)+```++When both inputs have metadata but different coordinate systems, interval operations raise `CoordinateSystemMismatchError`.+### Per-File Override via I/O FunctionsI/O functions accept `use_zero_based` to set coordinate metadata on the resulting DataFrame:@@ -71,17 +81,17 @@ I/O functions accept `use_zero_based` to set coordinate metadata on the resultindf = pb.read_bed("regions.bed", use_zero_based=True)```-**Note:** Interval operations (overlap, nearest, etc.) do **not** accept `use_zero_based`. They read coordinate metadata from the DataFrames, which is set by I/O functions or the global option. When using manually constructed DataFrames, polars-bio warns about missing metadata and falls back to the global setting.--### Setting Metadata on Manual DataFrames+**Note:** Interval operations (overlap, nearest, etc.) do **not** accept `use_zero_based`. They read coordinate metadata from the DataFrames, which is set by I/O functions or the global option. For manually constructed Polars DataFrames, attach metadata before calling interval ops:```python-import polars_bio as pb+import polars as pl-# Set coordinate metadata on a manually created DataFrame-pb.set_source_metadata(df, format="bed", path="")+df = pl.DataFrame({"chrom": ["chr1"], "start": [1], "end": [100]})+df.config_meta.set(coordinate_system_zero_based=False) # 1-based```+Alternatively, use `pb.set_source_metadata(df, format="bed", path="")` or I/O functions that set metadata automatically.+### File Format Conventions| Format | Native Coordinate System | polars-bio Conversion |@@ -109,8 +119,8 @@ result = pb.overlap(lf1, lf2) # Streams if inputs are LazyFramesUse Polars' native streaming for post-processing operations:```python-# Collect with Polars streaming-result = lf.collect(streaming=True)+# Collect with Polars streaming engine+result = lf.collect(engine="streaming")```### Combining Both@@ -126,7 +136,7 @@ lf2 = pb.scan_bed("large2.bed")result_lf = pb.overlap(lf1, lf2)# Collect with Polars streaming for final materialization-result = result_lf.collect(streaming=True)+result = result_lf.collect(engine="streaming")```## Logging@@ -172,4 +182,6 @@ pb.from_polars("my_table", df)| Option | Default | Description ||--------|---------|-------------|| `datafusion.execution.target_partitions` | `1` | Number of parallel execution partitions |-| `coordinate_system` | `"1-based"` | Default coordinate system (`"0-based"` or `"1-based"`) |+| `datafusion.bio.coordinate_system_zero_based` | `false` | Global coordinate system (`true` = 0-based half-open, `false` = 1-based) |+| `datafusion.bio.coordinate_system_check` | `false` | When `true`, raise `MissingCoordinateSystemError` if inputs lack coordinate metadata |+| `bio.interval_join_algorithm` | `"coitrees"` | Interval join algorithm (`Coitrees`, `IntervalTree`, `ArrayIntervalTree`, `Lapper`, `SuperIntervals`) |diff --git a/scientific-skills/polars-bio/references/file_io.md b/scientific-skills/polars-bio/references/file_io.mdindex e1e9f90d..5cc83ef2 100644--- a/scientific-skills/polars-bio/references/file_io.md+++ b/scientific-skills/polars-bio/references/file_io.md@@ -10,11 +10,12 @@ polars-bio provides `read_*`, `scan_*`, `write_*`, and `sink_*` functions for co|--------|------|------|-----------------|-------|------|| BED | `read_bed` | `scan_bed` | `register_bed` | — | — || VCF | `read_vcf` | `scan_vcf` | `register_vcf` | `write_vcf` | `sink_vcf` |+| VCF Zarr | `read_vcf_zarr` | `scan_vcf_zarr` | — | — | — || BAM | `read_bam` | `scan_bam` | `register_bam` | `write_bam` | `sink_bam` || CRAM | `read_cram` | `scan_cram` | `register_cram` | `write_cram` | `sink_cram` || GFF | `read_gff` | `scan_gff` | `register_gff` | — | — || GTF | `read_gtf` | `scan_gtf` | `register_gtf` | — | — |-| FASTA | `read_fasta` | `scan_fasta` | — | — | — |+| FASTA | `read_fasta` | `scan_fasta` | — | `write_fasta` | `sink_fasta` || FASTQ | `read_fastq` | `scan_fastq` | `register_fastq` | `write_fastq` | `sink_fastq` || SAM | `read_sam` | `scan_sam` | `register_sam` | `write_sam` | `sink_sam` || Hi-C pairs | `read_pairs` | `scan_pairs` | `register_pairs` | — | — |@@ -107,6 +108,8 @@ df = pb.read_vcf("variants.vcf.gz", samples=["SAMPLE1", "SAMPLE2"])| `filter` | String | Filter status || `info` | String | INFO field (raw, unless `info_fields` specified) |+**Genotype columns:** In single-sample VCFs, requested `format_fields` (e.g., `GT`, `DP`, `GQ`) appear as top-level columns. In multi-sample VCFs, per-sample FORMAT data is nested in a `genotypes` column.+### write_vcf / sink_vcf```python@@ -119,6 +122,35 @@ rows_written = pb.write_vcf(df, "output.vcf")pb.sink_vcf(lf, "output.vcf")```+## VCF Zarr Format++### read_vcf_zarr / scan_vcf_zarr++Read analysis-ready [VCF Zarr](https://github.com/sgkit-dev/vcf-zarr-spec) stores (local directory paths). Supports the same INFO/FORMAT projection and predicate pushdown as VCF readers.++```python+import polars_bio as pb++# Eager read from a Zarr store directory+df = pb.read_vcf_zarr("/path/to/vcf.zarr")++# Lazy scan (preferred for large stores)+lf = pb.scan_vcf_zarr(+ "/path/to/vcf.zarr",+ info_fields=["AF", "END"],+ format_fields=["GT", "DP"],+)++# Disable INFO/FORMAT discovery explicitly+lf = pb.scan_vcf_zarr("/path/to/vcf.zarr", info_fields=[], format_fields=[])+```++### Additional Parameters++Same as VCF where applicable: `info_fields`, `format_fields`, `samples`, `projection_pushdown`, `predicate_pushdown`, `use_zero_based`, `genotype_encoding_raw`.++**Note:** VCF Zarr is currently local-path only (no cloud URI support). There is no `register_vcf_zarr` SQL helper yet — use `scan_vcf_zarr` + `from_polars` if needed.+## BAM Format### read_bam / scan_bam@@ -264,6 +296,19 @@ df = pb.read_fasta("reference.fasta")| `description` | String | Description line || `sequence` | String | Nucleotide sequence |+### write_fasta / sink_fasta++Write sequences from DataFrames with `name` and `sequence` columns (optional `description`):++```python+import polars_bio as pb++rows_written = pb.write_fasta(df, "output.fasta")+rows_written = pb.write_fasta(df, "output.fasta.gz")++pb.sink_fasta(lf, "output.fasta.bgz")+```+## FASTQ Format### read_fastq / scan_fastq@@ -385,7 +430,15 @@ df = pb.read_vcf("gs://bucket/variants.vcf.gz", allow_anonymous=True)df = pb.read_bam("az://container/aligned.bam", allow_anonymous=False)```-**Note:** For authenticated access, configure credentials via environment variables or cloud SDK configuration (e.g., `AWS_ACCESS_KEY_ID`, `GOOGLE_APPLICATION_CREDENTIALS`).+**Cloud credential usage:** Cloud paths (`s3://`, `gs://`, `az://`) trigger reads through Apache OpenDAL using your environment's cloud SDK credentials. Credentials are read only when a cloud URI is accessed — not from broad `.env` scanning.++| Provider | Example path | Typical env vars |+|----------|--------------|------------------|+| AWS S3 | `s3://bucket/file.bed` | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION` |+| GCS | `gs://bucket/file.vcf.gz` | `GOOGLE_APPLICATION_CREDENTIALS` |+| Azure | `az://container/file.bam` | Azure SDK defaults (`AZURE_STORAGE_ACCOUNT`, etc.) |++Set `allow_anonymous=True` (default) for public buckets; set `allow_anonymous=False` when authenticated access is required.## Compression Support@@ -412,3 +465,5 @@ schema_df = pb.describe_bam("aligned.bam")schema_df = pb.describe_sam("alignments.sam")schema_df = pb.describe_cram("aligned.cram", reference_path="ref.fasta")```++Use `describe_bam`/`describe_sam` to auto-discover optional SAM tags before specifying `tag_fields`.diff --git a/scientific-skills/polars-bio/references/interval_operations.md b/scientific-skills/polars-bio/references/interval_operations.mdindex d545cbd3..f3d7f3d3 100644--- a/scientific-skills/polars-bio/references/interval_operations.md+++ b/scientific-skills/polars-bio/references/interval_operations.md@@ -45,6 +45,12 @@ result_df = result_lf.collect()# Or get DataFrame directlyresult_df = pb.overlap(df1, df2, suffixes=("_1", "_2"), output_type="polars.DataFrame")++# Left output: keep df1 rows that overlap df2 (original column names, no suffixes)+left_hits = pb.overlap(df1, df2, overlap_output="left", output_type="polars.DataFrame")++# Left output with one row per df1 interval (deduplicated)+left_unique = pb.overlap(df1, df2, overlap_output="left", distinct_output=True, output_type="polars.DataFrame")```### Method-Chaining API (LazyFrame only)@@ -65,6 +71,8 @@ result = df1.lazy().pb.overlap(df2, suffixes=("_1", "_2")).collect()| `cols2` | list[str] | `["chrom", "start", "end"]` | Column names in df2 || `algorithm` | str | `"Coitrees"` | Interval algorithm || `low_memory` | bool | `False` | Low memory mode |+| `overlap_output` | str | `"join"` | `"join"` returns both sides with suffixes; `"left"` returns only overlapping df1 rows with original column names |+| `distinct_output` | bool | `False` | When `overlap_output="left"`, deduplicate df1 rows by row identity || `output_type` | str | `"polars.LazyFrame"` | Output format: `"polars.LazyFrame"`, `"polars.DataFrame"`, `"pandas.DataFrame"` || `projection_pushdown` | bool | `True` | Enable projection pushdown optimization |diff --git a/scientific-skills/statistical-analysis/SKILL.md b/scientific-skills/statistical-analysis/SKILL.mdindex d029c23c..0a0396e2 100644--- a/scientific-skills/statistical-analysis/SKILL.md+++ b/scientific-skills/statistical-analysis/SKILL.md@@ -25,6 +25,28 @@ This skill should be used when:---+## Installation++Use **uv** to install the libraries used in this skill. Pin versions in production; unpinned installs are fine for exploration.++```bash+# Core frequentist stack (Python 3.10+; 3.12+ recommended for latest SciPy/ArviZ)+uv pip install "pingouin>=0.6" "scipy>=1.11" "statsmodels>=0.14.6" pandas matplotlib seaborn++# Bayesian modeling (PyMC 5 + ArviZ; ArviZ 0.23+ requires Python 3.12+)+uv pip install "pymc>=5.0" "arviz>=0.17"+```++**Compatibility notes (2025–2026):**++- **Pingouin 0.5+** renamed output columns (`p_val`, `cohen_d`, `CI95`, `p_unc`) — examples below use the current names.+- **statsmodels + SciPy**: use `statsmodels>=0.14.6` with `scipy>=1.11` to avoid `_lazywhere` import errors on SciPy 1.16+.+- **Pingouin Bayes Factors**: one-sided BF for t-tests was removed in 0.5+; use dedicated packages (e.g. JASP, BayesFactor via R) or PyMC for hypothesis testing.++For model-specific APIs (OLS, GLM, ARIMA), see the **statsmodels** skill. For PyMC workflows, see the **pymc** skill.++---+## Core Capabilities### 1. Test Selection and Planning@@ -119,10 +141,10 @@ All tests have Bayesian versions that provide:**ALWAYS check assumptions before interpreting test results.**-Use the provided `scripts/assumption_checks.py` module for automated checking:+Use the bundled `scripts/assumption_checks.py` module for automated checking. Run Python from the skill directory (`scientific-skills/statistical-analysis/`) or add `scripts/` to `sys.path`:```python-from scripts.assumption_checks import comprehensive_assumption_check+from assumption_checks import comprehensive_assumption_check# Comprehensive check with visualizationsresults = comprehensive_assumption_check(@@ -144,7 +166,7 @@ This performs:For targeted checks, use individual functions:```python-from scripts.assumption_checks import (+from assumption_checks import (check_normality,check_normality_per_group,check_homogeneity_of_variance,@@ -206,13 +228,13 @@ import numpy as np# Run independent t-testresult = pg.ttest(group_a, group_b, correction='auto')-# Extract results+# Extract results (Pingouin 0.5+ column names)t_stat = result['T'].values[0]df = result['dof'].values[0]-p_value = result['p-val'].values[0]-cohens_d = result['cohen-d'].values[0]-ci_lower = result['CI95%'].values[0][0]-ci_upper = result['CI95%'].values[0][1]+p_value = result['p_val'].values[0]+cohens_d = result['cohen_d'].values[0]+ci = result['CI95'].values[0]+ci_lower, ci_upper = ci[0], ci[1]# Reportprint(f"t({df:.0f}) = {t_stat:.2f}, p = {p_value:.3f}")@@ -229,7 +251,7 @@ aov = pg.anova(dv='score', between='group', data=df, detailed=True)print(aov)# If significant, conduct post-hoc tests-if aov['p-unc'].values[0] < 0.05:+if aov['p_unc'].values[0] < 0.05:posthoc = pg.pairwise_tukey(dv='score', between='group', data=df)print(posthoc)@@ -356,7 +378,7 @@ Most effect sizes are automatically calculated by pingouin:```python# T-test returns Cohen's dresult = pg.ttest(x, y)-d = result['cohen-d'].values[0]+d = result['cohen_d'].values[0]# ANOVA returns partial eta-squaredaov = pg.anova(dv='score', between='group', data=df)diff --git a/scientific-skills/statistical-analysis/references/bayesian_statistics.md b/scientific-skills/statistical-analysis/references/bayesian_statistics.mdindex 7e83a5c7..1e8b4594 100644--- a/scientific-skills/statistical-analysis/references/bayesian_statistics.md+++ b/scientific-skills/statistical-analysis/references/bayesian_statistics.md@@ -131,19 +131,18 @@ Where:```pythonimport pymc as pm-# Model with different priors-priors = [- ('weakly_informative', pm.Normal.dist(0, 1)),- ('diffuse', pm.Normal.dist(0, 10)),- ('informative', pm.Normal.dist(0.5, 0.3))+prior_specs = [+ ('weakly_informative', 0, 1),+ ('diffuse', 0, 10),+ ('informative', 0.5, 0.3),]results = {}-for name, prior in priors:- with pm.Model():- effect = pm.Normal('effect', mu=prior.mu, sigma=prior.sigma)- # ... rest of model- trace = pm.sample()+for name, mu_prior, sigma_prior in prior_specs:+ with pm.Model() as model:+ effect = pm.Normal('effect', mu=mu_prior, sigma=sigma_prior)+ # ... likelihood and observed data+ trace = pm.sample(2000, tune=1000, return_inferencedata=True)results[name] = trace```@@ -184,24 +183,13 @@ BF₁₀ = P(D|H₁) / P(D|H₀)**Python calculation**:```python+# Pingouin 0.5+: BF10 for independent two-sided t-tests; one-sided BF removed.import pingouin as pg-# Note: Limited BF support in Python-# Better options: R packages (BayesFactor), JASP software--# Approximate BF from t-statistic-# Using Jeffreys-Zellner-Siow prior-from scipy import stats--def bf_from_t(t, n1, n2, r_scale=0.707):- """- Approximate Bayes Factor from t-statistic- r_scale: Cauchy prior scale (default 0.707 for medium effect)- """- # This is simplified; use dedicated packages for accurate calculation- df = n1 + n2 - 2- # Implementation requires numerical integration- pass+result = pg.ttest(group1, group2, correction=False)+bf10 = result['BF10'].values[0]++# Rigorous Bayes Factors: BayesFactor (R), JASP, or PyMC model comparison (see pymc skill)```---@@ -637,9 +625,11 @@ p_value = np.mean(pred_means >= obs_mean) # Bayesian p-value## Key Python Packages-- **PyMC**: Full Bayesian modeling framework-- **ArviZ**: Visualization and diagnostics-- **Bambi**: High-level interface for regression models+Install with uv (see SKILL.md). ArviZ 0.23+ requires Python 3.12+.++- **PyMC** (`pymc>=5`): Full Bayesian modeling framework+- **ArviZ** (`arviz>=0.17`): Visualization and diagnostics ([docs](https://python.arviz.org))+- **Bambi**: High-level interface for regression models (`uv pip install bambi`)- **PyStan**: Python interface to Stan- **TensorFlow Probability**: Bayesian inference with TensorFlowdiff --git a/scientific-skills/statistical-analysis/references/effect_sizes_and_power.md b/scientific-skills/statistical-analysis/references/effect_sizes_and_power.mdindex 40f07337..14c47455 100644--- a/scientific-skills/statistical-analysis/references/effect_sizes_and_power.md+++ b/scientific-skills/statistical-analysis/references/effect_sizes_and_power.md@@ -41,7 +41,7 @@ import numpy as np# Independent t-test with effect sizeresult = pg.ttest(group1, group2, correction=False)-cohens_d = result['cohen-d'].values[0]+cohens_d = result['cohen_d'].values[0]# Manual calculationmean_diff = np.mean(group1) - np.mean(group2)@@ -50,7 +50,7 @@ cohens_d = mean_diff / pooled_std# Paired t-testresult = pg.ttest(pre, post, paired=True)-cohens_d = result['cohen-d'].values[0]+cohens_d = result['cohen_d'].values[0]```**Confidence intervals for d**:@@ -207,7 +207,7 @@ import pingouin as pg# Pearson correlation with CIresult = pg.corr(x, y, method='pearson')r = result['r'].values[0]-ci = [result['CI95%'][0][0], result['CI95%'][0][1]]+ci = result['CI95'].values[0] # Pingouin 0.5+: was CI95%# Spearman correlationresult = pg.corr(x, y, method='spearman')@@ -409,12 +409,9 @@ ci = np.exp(model.conf_int()) # Exponentiate CIs```pythonimport pingouin as pg-# Bayesian t-test+# Pingouin 0.5+: two-sided BF10 on independent t-tests; use BayesFactor/JASP/PyMC for full inferenceresult = pg.ttest(group1, group2, correction=False)-# Note: pingouin doesn't include BF; use other packages--# Using JASP or BayesFactor (R) via rpy2-# Or implement using numerical integration+bf10 = result['BF10'].values[0]```---diff --git a/scientific-skills/statistical-analysis/references/reporting_standards.md b/scientific-skills/statistical-analysis/references/reporting_standards.mdindex 3e03e9f6..5ca231f5 100644--- a/scientific-skills/statistical-analysis/references/reporting_standards.md+++ b/scientific-skills/statistical-analysis/references/reporting_standards.md@@ -102,7 +102,7 @@ This document provides guidelines for reporting statistical analyses according t- Effect size measures used**Example**:-> "All analyses were conducted using Python 3.10 with scipy 1.11 and statsmodels 0.14. An alpha level of .05 was used for all significance tests. Assumptions of normality and homogeneity of variance were assessed using Shapiro-Wilk and Levene's tests, respectively. Missing data (< 2% for all variables) were handled using listwise deletion. Outliers beyond 3 SD from the mean were winsorized. For the primary ANOVA, partial eta-squared (η²_p) is reported as the effect size measure. Post hoc comparisons used Tukey's HSD to control family-wise error rate."+> "All analyses were conducted using Python 3.12 with Pingouin 0.6, SciPy 1.16, and statsmodels 0.14.6. An alpha level of .05 was used for all significance tests. Assumptions of normality and homogeneity of variance were assessed using Shapiro-Wilk and Levene's tests, respectively. Missing data (< 2% for all variables) were handled using listwise deletion. Outliers beyond 3 SD from the mean were winsorized. For the primary ANOVA, partial eta-squared (η²_p) is reported as the effect size measure. Post hoc comparisons used Tukey's HSD to control family-wise error rate."---diff --git a/scientific-skills/torchdrug/SKILL.md b/scientific-skills/torchdrug/SKILL.mdindex 5088c79c..db0c7b84 100644--- a/scientific-skills/torchdrug/SKILL.md+++ b/scientific-skills/torchdrug/SKILL.md@@ -42,15 +42,21 @@ This skill should be used when working with:### Installation+TorchDrug **0.2.1** (latest on PyPI, July 2023) requires **Python 3.7–3.10** and **PyTorch 1.8–2.0**. Install PyTorch and `torch-scatter` / `torch-cluster` first (wheel URL depends on your PyTorch and CUDA versions — see [installation docs](https://torchdrug.ai/docs/installation.html)).+```bash-uv pip install torchdrug-# Or with optional dependencies-uv pip install torchdrug[full]+uv pip install torch+# Match torch/CUDA in the URL, e.g. torch-2.0.0+cu118 or cpu+uv pip install torch-scatter torch-cluster -f https://pytorch-geometric.com/whl/torch-2.0.0+cu118.html+uv pip install torchdrug==0.2.1```+On Apple Silicon, compile scatter/cluster from source; TorchDrug runs on CPU only (no MPS). Conda: `conda install torchdrug -c milagraph -c conda-forge -c pytorch -c pyg`.+### Quick Example```python+import torchfrom torchdrug import datasets, models, tasksfrom torch.utils.data import DataLoader@@ -425,9 +431,15 @@ For deep dives into TorchDrug's architecture:→ Post-process with RDKit validation→ See `references/molecular_generation.md` → Validation and Filtering+## Version Notes (0.2.1)++- `PropertyPrediction.predict()` returns **original-scale** values (not standardized); code written for older TorchDrug may need metric/threshold updates ([release notes](https://github.com/DeepGraphLearning/torchdrug/releases/tag/v0.2.1)).+- Dataset constructors prefer `atom_feature` / `bond_feature` / `mol_feature`; `node_feature` / `edge_feature` / `graph_feature` are deprecated aliases.+- `EvolutionaryScaleModeling` supports ESM-2 checkpoints in addition to ESM-1b.+## Resources-**Official Documentation:** https://torchdrug.ai/docs/+**Official Documentation:** https://torchdrug.ai/docs/ (0.2.1)**GitHub:** https://github.com/DeepGraphLearning/torchdrug**Paper:** TorchDrug: A Powerful and Flexible Machine Learning Platform for Drug Discoverydiff --git a/scientific-skills/torchdrug/references/core_concepts.md b/scientific-skills/torchdrug/references/core_concepts.mdindex 27e5c3f2..6817f512 100644--- a/scientific-skills/torchdrug/references/core_concepts.md+++ b/scientific-skills/torchdrug/references/core_concepts.md@@ -306,6 +306,12 @@ task = tasks.PropertyPrediction()```+## Version Notes (0.2.1)++- Pin installs with `uv pip install torchdrug==0.2.1` (Python 3.7–3.10, PyTorch 1.8–2.0).+- `PropertyPrediction.predict()` returns unstandardized targets/predictions (breaking vs older releases).+- Prefer `atom_feature` / `bond_feature` on dataset constructors; `node_feature` / `edge_feature` are deprecated aliases (dataset properties like `node_feature_dim` are unchanged).+## Training Workflow### Standard Training Loop@@ -342,19 +348,34 @@ for epoch in range(100):loss.backward()optimizer.step()- # Validate- task.eval()- preds, targets = [], []- for batch in valid_loader:- pred = task.predict(batch)- target = task.target(batch)- preds.append(pred)- targets.append(target)-- preds = torch.cat(preds)- targets = torch.cat(targets)- metrics = task.evaluate(preds, targets)- print(f"Epoch {epoch}: {metrics}")+ # Validate (inference_mode disables autograd; train(False) disables dropout/BN)+ with torch.inference_mode():+ task.train(False)+ preds, targets = [], []+ for batch in valid_loader:+ pred = task.predict(batch)+ target = task.target(batch)+ preds.append(pred)+ targets.append(target)++ preds = torch.cat(preds)+ targets = torch.cat(targets)+ metrics = task.evaluate(preds, targets)+ print(f"Epoch {epoch}: {metrics}")+ task.train(True)+```++### Built-in Engine (`core.Engine`)++For standard train/validate loops without hand-written epochs, use the configurable engine:++```python+from torchdrug import core++solver = core.Engine(task, train_set, valid_set, test_set, optimizer,+ gpus=[0], batch_size=32)+solver.train(num_epoch=100)+solver.evaluate("valid")```### PyTorch Lightning Integration@@ -368,6 +389,7 @@ class LightningWrapper(pl.LightningModule):def __init__(self, task):super().__init__()self.task = task+ self._val_outputs = []def training_step(self, batch, batch_idx):loss = self.task(batch)@@ -376,13 +398,14 @@ class LightningWrapper(pl.LightningModule):def validation_step(self, batch, batch_idx):pred = self.task.predict(batch)target = self.task.target(batch)- return {"pred": pred, "target": target}+ self._val_outputs.append({"pred": pred, "target": target})- def validation_epoch_end(self, outputs):- preds = torch.cat([o["pred"] for o in outputs])- targets = torch.cat([o["target"] for o in outputs])+ def on_validation_epoch_end(self):+ preds = torch.cat([o["pred"] for o in self._val_outputs])+ targets = torch.cat([o["target"] for o in self._val_outputs])metrics = self.task.evaluate(preds, targets)self.log_dict(metrics)+ self._val_outputs.clear()def configure_optimizers(self):return torch.optim.Adam(self.parameters(), lr=1e-3)diff --git a/scientific-skills/torchdrug/references/molecular_property_prediction.md b/scientific-skills/torchdrug/references/molecular_property_prediction.mdindex 9d97c6dc..38757915 100644--- a/scientific-skills/torchdrug/references/molecular_property_prediction.md+++ b/scientific-skills/torchdrug/references/molecular_property_prediction.md@@ -38,6 +38,8 @@ Molecular property prediction involves predicting chemical, physical, or biologiStandard task for graph-level property prediction supporting both classification and regression.+**TorchDrug 0.2.1+:** `predict()` returns values on the **original scale** (not standardized). Update thresholds and downstream metrics if migrating from older versions.+**Key Parameters:**- `model`: Graph representation model (GNN)- `task`: "node", "edge", or "graph" level predictiondiff --git a/scientific-skills/torchdrug/references/protein_modeling.md b/scientific-skills/torchdrug/references/protein_modeling.mdindex 11796c39..7c6529c2 100644--- a/scientific-skills/torchdrug/references/protein_modeling.md+++ b/scientific-skills/torchdrug/references/protein_modeling.md@@ -91,7 +91,7 @@ Specialized task for predicting spatial proximity between residues in folded str### Sequence-Based Models**ESM (Evolutionary Scale Modeling):**-- Pre-trained transformer model on 250M sequences+- Pre-trained transformer via `models.EvolutionaryScaleModeling` (ESM-1b and ESM-2; TorchDrug 0.2.1+)- State-of-the-art for sequence-only tasks- Available in multiple sizes (ESM-1b, ESM-2)- Captures evolutionary and structural informationdiff --git a/scientific-skills/umap-learn/SKILL.md b/scientific-skills/umap-learn/SKILL.mdindex 8f22650e..58c442a3 100644--- a/scientific-skills/umap-learn/SKILL.md+++ b/scientific-skills/umap-learn/SKILL.md@@ -16,8 +16,10 @@ UMAP (Uniform Manifold Approximation and Projection) is a dimensionality reducti### Installation+Requires Python 3.9+. Pin to a verified release:+```bash-uv pip install umap-learn+uv pip install umap-learn==0.5.12```### Basic Usage@@ -210,6 +212,12 @@ UMAP serves as effective preprocessing for density-based clustering algorithms l### Clustering Workflow+Install HDBSCAN separately for density-based clustering:++```bash+uv pip install hdbscan+```+```pythonimport umapimport hdbscan@@ -309,7 +317,7 @@ print(f"Test accuracy: {accuracy:.3f}")**Performance:** Transform operations are efficient (typically <1 second), though initial calls may be slower due to Numba JIT compilation.-**Scikit-learn compatibility:** UMAP follows standard sklearn conventions and works seamlessly in pipelines:+**Scikit-learn compatibility:** UMAP follows standard sklearn conventions and works seamlessly in pipelines. Since 0.5.x, `UMAP` implements `get_feature_names_out()` for sklearn column-transformer pipelines:```pythonfrom sklearn.pipeline import Pipeline@@ -322,6 +330,7 @@ pipeline = Pipeline([pipeline.fit(X_train, y_train)predictions = pipeline.predict(X_test)+feature_names = pipeline.named_steps['umap'].get_feature_names_out()```## Advanced Features@@ -338,8 +347,8 @@ Parametric UMAP replaces direct embedding optimization with a learned neural net**Installation:**```bash-uv pip install umap-learn[parametric_umap]-# Requires TensorFlow 2.x+uv pip install "umap-learn[parametric-umap]==0.5.12"+# Requires TensorFlow 2.x (install separately if needed)```**Basic usage:**@@ -463,11 +472,21 @@ UMAP uses stochastic optimization, so results will vary slightly between runs wi**Issue:** Slow performance on large datasets- **Solution:** Set `low_memory=True` (default), or consider dimensionality reduction with PCA first+**Issue:** NaN or inf values in input data+- **Solution:** Impute or drop invalid rows before fitting (0.5.6+ accepts NaN/inf in some paths, but clean numeric input is still recommended)+**Issue:** All points collapsed to single cluster- **Solution:** Check data preprocessing (ensure proper scaling), increase `min_dist`## Resources+### Official documentation++- [UMAP user guide](https://umap-learn.readthedocs.io/en/latest/)+- [Release notes](https://umap-learn.readthedocs.io/en/latest/release_notes.html)+- [PyPI package](https://pypi.org/project/umap-learn/) (current stable: 0.5.12)+- [GitHub repository](https://github.com/lmcinnes/umap)+### references/Contains detailed API documentation:diff --git a/scientific-skills/umap-learn/references/api_reference.md b/scientific-skills/umap-learn/references/api_reference.mdindex 3e0dbefe..30239cce 100644--- a/scientific-skills/umap-learn/references/api_reference.md+++ b/scientific-skills/umap-learn/references/api_reference.md@@ -1,5 +1,7 @@# UMAP API Reference+Reference for **umap-learn 0.5.12** (Python >=3.9). See [official API guide](https://umap-learn.readthedocs.io/en/latest/api.html) for the full upstream reference.+## UMAP Class`umap.UMAP(n_neighbors=15, n_components=2, metric='euclidean', n_epochs=None, learning_rate=1.0, init='spectral', min_dist=0.1, spread=1.0, low_memory=True, set_op_mix_ratio=1.0, local_connectivity=1.0, repulsion_strength=1.0, negative_sample_rate=5, transform_queue_size=4.0, a=None, b=None, random_state=None, metric_kwds=None, angular_rp_forest=False, target_n_neighbors=-1, target_metric='categorical', target_metric_kwds=None, target_weight=0.5, transform_seed=42, transform_mode='embedding', force_approximation_algorithm=False, verbose=False, unique=False, densmap=False, dens_lambda=2.0, dens_frac=0.3, dens_var_shift=0.1, output_dens=False, disconnection_distance=None, precomputed_knn=(None, None, None))`@@ -245,6 +247,15 @@ Update the model with new data. Allows incremental fitting.**Note:** Experimental feature, may not preserve all properties of batch training.+### get_feature_names_out(input_features=None)+Return output feature names for sklearn pipeline compatibility (added in 0.5.x).++**Parameters:**+- `input_features`: array-like of str, optional - Ignored; present for sklearn API compatibility++**Returns:**+- `ndarray` of shape `(n_components,)` with names like `umap0`, `umap1`, ...+## Attributes### embedding_@@ -276,9 +287,9 @@ list - Random projection forest used for approximate nearest neighbor search.## ParametricUMAP Class-`umap.ParametricUMAP(encoder=None, decoder=None, parametric_reconstruction=False, autoencoder_loss=False, reconstruction_validation=None, dims=None, batch_size=None, n_training_epochs=1, loss_report_frequency=10, optimizer=None, keras_fit_kwargs={}, **kwargs)`+`umap.parametric_umap.ParametricUMAP(encoder=None, decoder=None, parametric_reconstruction=False, autoencoder_loss=False, reconstruction_validation=None, dims=None, batch_size=None, n_training_epochs=1, loss_report_frequency=10, optimizer=None, keras_fit_kwargs={}, **kwargs)`-Parametric UMAP using neural networks to learn the embedding function.+Install with `uv pip install "umap-learn[parametric-umap]==0.5.12"`. Parametric UMAP uses neural networks to learn the embedding function.### Additional Parameters (beyond UMAP)