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
Update PyTDC skill for current APIs
Timothy Kassis825f800240e9
diff --git a/skills/pytdc/SKILL.md b/skills/pytdc/SKILL.mdindex 1c34f5ca..14aaec60 100644--- a/skills/pytdc/SKILL.md+++ b/skills/pytdc/SKILL.md@@ -1,457 +1,297 @@---name: pytdc-description: Therapeutics Data Commons. AI-ready drug discovery datasets (ADME, toxicity, DTI), benchmarks, scaffold splits, molecular oracles, for therapeutic ML and pharmacological prediction.-license: MIT license-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}+description: Use Therapeutics Data Commons through the PyTDC Python package for registry discovery, approved dataset access, task-aware splits, evaluator metrics, benchmark groups, and bounded molecular-oracle workflows.+license: MIT+allowed-tools: Read, Write, Edit, Bash+compatibility: Requires uv, CPython 3.11, PyTDC 1.1.15, and setuptools 80.9.0 for its legacy pkg_resources runtime import. Dataset, benchmark, checkpoint, and remote-oracle operations require network/storage review and explicit user approval.+metadata:+ version: "1.1"+ skill-author: K-Dense Inc.---# PyTDC (Therapeutics Data Commons)-## Overview+Use the official `PyTDC` distribution (`import tdc`) to discover therapeutic ML+tasks, load approved datasets, apply task-appropriate splits, evaluate predictions,+and work with curated benchmark groups. Prefer package metadata over copied dataset+lists, and plan network/storage effects before constructing any loader.-PyTDC is an open-science platform providing AI-ready datasets and benchmarks for drug discovery and development. Access curated datasets spanning the entire therapeutics pipeline with standardized evaluation metrics and meaningful data splits, organized into three categories: single-instance prediction (molecular/protein properties), multi-instance prediction (drug-target interactions, DDI), and generation (molecule generation, retrosynthesis).+## Verified snapshot-## When to Use This Skill+- Research date: **2026-07-23**+- PyPI stable: **PyTDC 1.1.15**, released 2025-03-31+- Package/source repository: `mims-harvard/TDC`+- Code license: MIT+- PyPI supplies only a source distribution and declares no `Requires-Python`+- The dependency graph makes **CPython 3.11** the reproducible target used here:+ `cellxgene-census==1.15.0` excludes Python 3.12, and PyTDC's constrained+ RDKit release has no CPython 3.13 wheel+- PyTDC imports deprecated `pkg_resources` at runtime. Setuptools 82 removed that+ module; pin the verified compatibility release **setuptools 80.9.0**.+- `tdc.readthedocs.io` still identifies itself as TDC 0.4.1; use it as API+ cross-reference, not as release-version evidence+- Upstream publishes no GitHub tags/releases or maintained changelog. Treat+ undocumented migration claims as uncertainty and verify against the installed+ 1.1.15 source/metadata.-This skill should be used when:-- Working with drug discovery or therapeutic ML datasets-- Benchmarking machine learning models on standardized pharmaceutical tasks-- Predicting molecular properties (ADME, toxicity, bioactivity)-- Predicting drug-target or drug-drug interactions-- Generating novel molecules with desired properties-- Accessing curated datasets with proper train/test splits (scaffold, cold-split)-- Using molecular oracles for property optimization+See [references/sources.md](references/sources.md) for dated evidence and known+documentation conflicts.-## Installation & Setup+## Installation-Install PyTDC using pip:+Use an isolated CPython 3.11 environment and pin the reviewed snapshot:```bash-uv pip install PyTDC+uv venv --python 3.11 .venv-pytdc+uv pip install --dry-run --python .venv-pytdc/bin/python \+ "setuptools==80.9.0" "PyTDC==1.1.15"+uv pip install --python .venv-pytdc/bin/python \+ "setuptools==80.9.0" "PyTDC==1.1.15"```-To upgrade to the latest version:+The tested macOS ARM64 resolution installed 123 packages, including large+scientific/ML dependencies, so the environment itself can transfer and occupy+hundreds of megabytes before any dataset is downloaded. Review the dry run and+available disk first. The direct pins identify the reviewed API snapshot; generate+a platform-specific `uv.lock` in the user's project when every transitive version+must also be frozen.-```bash-uv pip install PyTDC --upgrade-```--Core dependencies (automatically installed):-- numpy, pandas, tqdm, seaborn, scikit_learn, fuzzywuzzy--Additional packages are installed automatically as needed for specific features.--## Quick Start--The basic pattern for accessing any TDC dataset follows this structure:--```python-from tdc.<problem> import <Task>-data = <Task>(name='<Dataset>')-split = data.get_split(method='scaffold', seed=1, frac=[0.7, 0.1, 0.2])-df = data.get_data(format='df')-```--Where:-- `<problem>`: One of `single_pred`, `multi_pred`, or `generation`-- `<Task>`: Specific task category (e.g., ADME, DTI, MolGen)-- `<Dataset>`: Dataset name within that task--**Example - Loading ADME data:**--```python-from tdc.single_pred import ADME-data = ADME(name='Caco2_Wang')-split = data.get_split(method='scaffold')-# Returns dict with 'train', 'valid', 'test' DataFrames-```--## Single-Instance Prediction Tasks--Single-instance prediction involves forecasting properties of individual biomedical entities (molecules, proteins, etc.).--### Available Task Categories--#### 1. ADME (Absorption, Distribution, Metabolism, Excretion)--Predict pharmacokinetic properties of drug molecules.--```python-from tdc.single_pred import ADME-data = ADME(name='Caco2_Wang') # Intestinal permeability-# Other datasets: HIA_Hou, Bioavailability_Ma, Lipophilicity_AstraZeneca, etc.-```--**Common ADME datasets:**-- Caco2 - Intestinal permeability-- HIA - Human intestinal absorption-- Bioavailability - Oral bioavailability-- Lipophilicity - Octanol-water partition coefficient-- Solubility - Aqueous solubility-- BBB - Blood-brain barrier penetration-- CYP - Cytochrome P450 metabolism--#### 2. Toxicity (Tox)--Predict toxicity and adverse effects of compounds.--```python-from tdc.single_pred import Tox-data = Tox(name='hERG') # Cardiotoxicity-# Other datasets: AMES, DILI, Carcinogens_Lagunin, etc.-```--**Common toxicity datasets:**-- hERG - Cardiac toxicity-- AMES - Mutagenicity-- DILI - Drug-induced liver injury-- Carcinogens - Carcinogenicity-- ClinTox - Clinical trial toxicity--#### 3. HTS (High-Throughput Screening)--Bioactivity predictions from screening data.+For an ephemeral command:-```python-from tdc.single_pred import HTS-data = HTS(name='SARSCoV2_Vitro_Touret')-```--#### 4. QM (Quantum Mechanics)--Quantum mechanical properties of molecules.--```python-from tdc.single_pred import QM-data = QM(name='QM7')+```bash+uv run --python 3.11 \+ --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind tasks```-#### 5. Other Single Prediction Tasks--- **Yields**: Chemical reaction yield prediction-- **Epitope**: Epitope prediction for biologics-- **Develop**: Development-stage predictions-- **CRISPROutcome**: Gene editing outcome prediction+To check for a newer release, inspect the PyPI release history at+<https://pypi.org/project/pytdc/>. Before changing the pin, compare its source+distribution, dependencies, official repository, task registries, and smoke tests;+do not silently substitute the separate `pytdc-nextml` package.++## Non-negotiable data and network policy++1. **Discover first.** Reading `tdc.metadata` or using+ `scripts/discover_metadata.py` does not instantiate a loader or download data.+2. **Plan second.** Record the exact task/dataset, official task page, license,+ expected size, cache directory, split, metric, and reproducibility seed.+3. **Ask the user before downloading.** Loader constructors fetch missing data.+ Some datasets and benchmark-group archives are large; model-backed oracles can+ fetch checkpoints; remote/docking oracles can transmit molecular structures.+4. **Execute only after approval.** In bundled CLIs, `--execute` acknowledges+ execution and `--download` is additionally required for MolGen corpora or+ supported oracle checkpoints.+5. **Keep outputs bounded.** Emit counts, schema, and small previews rather than+ full datasets, sequences, prediction arrays, or molecule corpora.++### Cache and cost behavior++- Ordinary loaders default to `path="./data"` and save files beneath that path.+ The bundled scripts instead default to explicit `.pytdc-*` directories.+- Core downloads use Harvard Dataverse file endpoints when a local filename is+ absent. Newer resource classes may use other upstream services.+- `admet_group(path=...)` and other benchmark-group constructors download and+ extract the group archive when `<path>/<group>` is absent.+- Download-backed `Oracle(...)` construction uses `./oracle` internally. The+ bundled oracle CLI changes into a safe runtime directory before approved calls.+- PyTDC 1.1.15 does not provide a universal cache quota, eviction policy, or+ dataset-wide checksum manifest. Use `scripts/cache_audit.py` and manage disk+ retention explicitly.+- Network transfer, local storage, decompression, parsing, feature generation,+ docking, and external service calls can all incur time or monetary cost.++The PyTDC **code** is MIT. Dataset/task licenses are heterogeneous: official task+pages include per-dataset terms ranging from Creative Commons licenses to+non-commercial restrictions or “Not Specified.” Verify the exact dataset's page and+original source terms before download, redistribution, publication, or commercial+use. Cite both TDC and the original dataset.++## Start with metadata-only discovery++From this skill directory:-### Data Format--Single prediction datasets typically return DataFrames with columns:-- `Drug_ID` or `Compound_ID`: Unique identifier-- `Drug` or `X`: SMILES string or molecular representation-- `Y`: Target label (continuous or binary)--## Multi-Instance Prediction Tasks--Multi-instance prediction involves forecasting properties of interactions between multiple biomedical entities.--### Available Task Categories--#### 1. DTI (Drug-Target Interaction)+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind datasets --task ADME --limit 50-Predict binding affinity between drugs and protein targets.+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind benchmarks --limit 50-```python-from tdc.multi_pred import DTI-data = DTI(name='BindingDB_Kd')-split = data.get_split()+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind evaluators --limit 100```-**Available datasets:**-- BindingDB_Kd - Dissociation constant (52,284 pairs)-- BindingDB_IC50 - Half-maximal inhibitory concentration (991,486 pairs)-- BindingDB_Ki - Inhibition constant (375,032 pairs)-- DAVIS, KIBA - Kinase binding datasets--**Data format:** Drug_ID, Target_ID, Drug (SMILES), Target (sequence), Y (binding affinity)--#### 2. DDI (Drug-Drug Interaction)--Predict interactions between drug pairs.+The package API is also metadata-only:```python-from tdc.multi_pred import DDI-data = DDI(name='DrugBank')-split = data.get_split()-```--Multi-class classification task predicting interaction types. Dataset contains 191,808 DDI pairs with 1,706 drugs.+from tdc.utils import retrieve_dataset_names, retrieve_benchmark_names-#### 3. PPI (Protein-Protein Interaction)--Predict protein-protein interactions.--```python-from tdc.multi_pred import PPI-data = PPI(name='HuRI')+adme_names = retrieve_dataset_names("ADME")+admet_benchmarks = retrieve_benchmark_names("admet_group")```-#### 4. Other Multi-Prediction Tasks--- **GDA**: Gene-disease associations-- **DrugRes**: Drug resistance prediction-- **DrugSyn**: Drug synergy prediction-- **PeptideMHC**: Peptide-MHC binding-- **AntibodyAff**: Antibody affinity prediction-- **MTI**: miRNA-target interactions-- **Catalyst**: Catalyst prediction-- **TrialOutcome**: Clinical trial outcome prediction+Use exact returned names. PyTDC performs fuzzy matching internally, but explicit+matching avoids silently selecting the wrong dataset/oracle.-## Generation Tasks+## Dataset workflow-Generation tasks involve creating novel biomedical entities with desired properties.+Plan a split without downloading:-### 1. Molecular Generation (MolGen)--Generate diverse, novel molecules with desirable chemical properties.--```python-from tdc.generation import MolGen-data = MolGen(name='ChEMBL_V29')-split = data.get_split()-```--Use with oracles to optimize for specific properties:--```python-from tdc import Oracle-oracle = Oracle(name='GSK3B')-score = oracle('CC(C)Cc1ccc(cc1)C(C)C(O)=O') # Evaluate SMILES+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/load_and_split_data.py \+ --task ADME --dataset Caco2_Wang --method scaffold \+ --seed 42 --data-dir .pytdc-data```-See `references/oracles.md` for all available oracle functions.--### 2. Retrosynthesis (RetroSyn)+After the user approves the dataset, license, transfer, and storage:-Predict reactants needed to synthesize a target molecule.--```python-from tdc.generation import RetroSyn-data = RetroSyn(name='USPTO')-split = data.get_split()+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/load_and_split_data.py \+ --task ADME --dataset Caco2_Wang --method scaffold \+ --seed 42 --data-dir .pytdc-data --execute```-Dataset contains 1,939,253 reactions from USPTO database.--### 3. Paired Molecule Generation--Generate molecule pairs (e.g., prodrug-drug pairs).+Verified public import patterns include:```python-from tdc.generation import PairMolGen-data = PairMolGen(name='Prodrug')+from tdc.single_pred import ADME, Tox+from tdc.multi_pred import DDI, DTI+from tdc.generation import MolGen, Reaction, RetroSyn```-For detailed oracle documentation and molecular generation workflows, refer to `references/oracles.md` and `scripts/molecular_generation.py`.--## Benchmark Groups--Benchmark groups provide curated collections of related datasets for systematic model evaluation.--### ADMET Benchmark Group+Constructors perform data access, so do not run them before approval:```python-from tdc.benchmark_group import admet_group-group = admet_group(path='data/')--# Get benchmark datasets-benchmark = group.get('Caco2_Wang')-predictions = {}--for seed in [1, 2, 3, 4, 5]:- train, valid = benchmark['train'], benchmark['valid']- # Train model here- predictions[seed] = model.predict(benchmark['test'])--# Evaluate with required 5 seeds-results = group.evaluate(predictions)+data = ADME(name="Caco2_Wang", path=".pytdc-data")+frame = data.get_data(format="df")+split = data.get_split(+ method="scaffold",+ seed=42,+ frac=[0.7, 0.1, 0.2],+)+# split keys are: train, valid, test```-**ADMET Group includes 22 datasets** covering absorption, distribution, metabolism, excretion, and toxicity.+Read [references/datasets.md](references/datasets.md) before choosing a task or+dataset.-### Other Benchmark Groups+## Split selection without overclaiming leakage control-Available benchmark groups include collections for:-- ADMET properties-- Drug-target interactions-- Drug combination prediction-- And more specialized therapeutic tasks+- `random`: default for loaders; default seed 42 and fractions 0.7/0.1/0.2.+- `scaffold`: documented generic support for molecule-based ADME, Tox, and HTS.+ PyTDC groups RDKit Bemis–Murcko scaffold strings (chirality disabled), but that+ does **not** prove absence of analog, duplicate, label, temporal, or provenance+ leakage.+- `cold_split`: multi-instance API. Pass exact dataframe columns, for example+ `method="cold_split", column_name=["Drug", "Target"]`. Multi-column splitting can+ discard cross-partition rows and need not preserve requested row fractions.+- `combination`: built-in DrugSyn combination split.+- `time`: pair-loader API requiring `time_column`; the verified built-in case is+ `BindingDB_Patent` with its `Year` column. The API spelling is `time`, not+ `temporal`.-For benchmark evaluation workflows, see `scripts/benchmark_evaluation.py`.+Do not use undocumented `cold_drug_target`, `temporal`, or `stratified=True`+examples. For every split, record PyTDC version, parameters, row counts, and exact+entity overlap audits. PyTDC 1.1.15's random splitter uses the supplied seed for+test sampling but a fixed `random_state=1` for validation sampling; do not describe+all partitions as independently varying with the seed.-## Data Functions+Detailed semantics and caveats are in+[references/utilities.md](references/utilities.md).-TDC provides comprehensive data processing utilities organized into four categories.+## Evaluators-### 1. Dataset Splits--Retrieve train/validation/test partitions with various strategies:--```python-# Scaffold split (default for most tasks)-split = data.get_split(method='scaffold', seed=1, frac=[0.7, 0.1, 0.2])--# Random split-split = data.get_split(method='random', seed=42, frac=[0.8, 0.1, 0.1])--# Cold split (for DTI/DDI tasks)-split = data.get_split(method='cold_drug', seed=1) # Unseen drugs in test-split = data.get_split(method='cold_target', seed=1) # Unseen targets in test-```--**Available split strategies:**-- `random`: Random shuffling-- `scaffold`: Scaffold-based (for chemical diversity)-- `cold_drug`, `cold_target`, `cold_drug_target`: For DTI tasks-- `temporal`: Time-based splits for temporal datasets--### 2. Model Evaluation--Use standardized metrics for evaluation:+Use exact names from the installed evaluator registry:```pythonfrom tdc import Evaluator-# For binary classification-evaluator = Evaluator(name='ROC-AUC')-score = evaluator(y_true, y_pred)--# For regression-evaluator = Evaluator(name='RMSE')-score = evaluator(y_true, y_pred)-```--**Available metrics:** ROC-AUC, PR-AUC, F1, Accuracy, RMSE, MAE, R2, Spearman, Pearson, and more.--### 3. Data Processing--TDC provides 11 key processing utilities:--```python-from tdc.chem_utils import MolConvert--# Molecule format conversion-converter = MolConvert(src='SMILES', dst='PyG')-pyg_graph = converter('CC(C)Cc1ccc(cc1)C(C)C(O)=O')+mae = Evaluator(name="MAE")(y_true, y_pred)+auroc = Evaluator(name="ROC-AUC")(y_true_binary, predicted_scores)+pcc = Evaluator(name="PCC")(y_true, y_pred)```-**Processing utilities include:**-- Molecule format conversion (SMILES, SELFIES, PyG, DGL, ECFP, etc.)-- Molecule filters (PAINS, drug-likeness)-- Label binarization and unit conversion-- Data balancing (over/under-sampling)-- Negative sampling for pair data-- Graph transformation-- Entity retrieval (CID to SMILES, UniProt to sequence)+`PCC` is the registered Pearson-correlation name; `Pearson` is not. Multi-class+registry names are `micro-f1`, `macro-f1`, and `kappa`. Thresholded binary metrics+default to 0.5. Metric direction and input shape are metric-specific; use the+official task/benchmark metric rather than choosing from task type alone.-For comprehensive utilities documentation, see `references/utilities.md`.+## Benchmark groups-### 4. Molecule Generation Oracles--TDC provides 17+ oracle functions for molecular optimization:--```python-from tdc import Oracle--# Single oracle-oracle = Oracle(name='DRD2')-score = oracle('CC(C)Cc1ccc(cc1)C(C)C(O)=O')--# Multiple oracles-oracle = Oracle(name='JNK3')-scores = oracle(['SMILES1', 'SMILES2', 'SMILES3'])-```--For complete oracle documentation, see `references/oracles.md`.--## Advanced Features--### Retrieve Available Datasets+Use specialized classes. Top-level `from tdc import BenchmarkGroup` is retained+only as a deprecated compatibility path in 1.1.15.```python-from tdc.utils import retrieve_dataset_names--# Get all ADME datasets-adme_datasets = retrieve_dataset_names('ADME')+from tdc.benchmark_group import admet_group-# Get all DTI datasets-dti_datasets = retrieve_dataset_names('DTI')+# Run only after approval: construction may download the group archive.+group = admet_group(path=".pytdc-benchmarks")+benchmark = group.get("Caco2_Wang")+train_val = benchmark["train_val"]+test = benchmark["test"]+train, valid = group.get_train_valid_split(+ seed=1,+ benchmark=benchmark["name"],+ split_type="default",+)```-### Label Transformations--```python-# Get label mapping-label_map = data.get_label_map(name='DrugBank')--# Convert labels-from tdc.chem_utils import label_transform-transformed = label_transform(y, from_unit='nM', to_unit='p')-```+For one run, `group.evaluate({name: test_predictions})` returns metric results.+For leaderboard aggregation, pass a **list of at least five prediction+dictionaries** to `group.evaluate_many(...)`. Do not index `group.get(...)` by+seed, and do not derive dummy predictions from test labels.-### Database Queries+Use `scripts/benchmark_evaluation.py` to validate a bounded JSON prediction plan+before any group download. See [references/utilities.md](references/utilities.md)+for the exact JSON shape and API behavior.-```python-from tdc.utils import cid2smiles, uniprot2seq+## Molecular generation and oracles-# Convert PubChem CID to SMILES-smiles = cid2smiles(2244)+PyTDC supplies molecule corpora, evaluators, and oracles; it does not train or+provide a generic molecule generator in the core workflow. Discover current names:-# Convert UniProt ID to amino acid sequence-sequence = uniprot2seq('P12345')+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind oracles --limit 100```-## Common Workflows--### Workflow 1: Train a Single Prediction Model--See `scripts/load_and_split_data.py` for a complete example:--```python-from tdc.single_pred import ADME-from tdc import Evaluator--# Load data-data = ADME(name='Caco2_Wang')-split = data.get_split(method='scaffold', seed=42)--train, valid, test = split['train'], split['valid'], split['test']+Plan bounded local QED scoring:-# Train model (user implements)-# model.fit(train['Drug'], train['Y'])--# Evaluate-evaluator = Evaluator(name='MAE')-# score = evaluator(test['Y'], predictions)+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/molecular_generation.py score --oracle QED --smiles CCO```-### Workflow 2: Benchmark Evaluation--See `scripts/benchmark_evaluation.py` for a complete example with multiple seeds and proper evaluation protocol.--### Workflow 3: Molecular Generation with Oracles--See `scripts/molecular_generation.py` for an example of goal-directed generation using oracle functions.--## Resources--This skill includes bundled resources for common TDC workflows:+Add `--execute` only after review. LogP and SA call the downloadable `fpscores`+artifact in 1.1.15; they and DRD2/GSK3B/JNK3/CYP3A4_Veith also require+`--download`. The helper intentionally refuses remote services, docking,+distribution, and composite oracles. It preserves input order and never assumes+score direction.-### scripts/+Read [references/oracles.md](references/oracles.md) before any oracle call.-- `load_and_split_data.py`: Template for loading and splitting TDC datasets with various strategies-- `benchmark_evaluation.py`: Template for running benchmark group evaluations with proper 5-seed protocol-- `molecular_generation.py`: Template for molecular generation using oracle functions+## Bundled resources-### references/+### Scripts-- `datasets.md`: Comprehensive catalog of all available datasets organized by task type-- `oracles.md`: Complete documentation of all 17+ molecule generation oracles-- `utilities.md`: Detailed guide to data processing, splitting, and evaluation utilities+- `scripts/discover_metadata.py` — download-free package registry discovery+- `scripts/load_and_split_data.py` — task-aware split plan/explicit execution+- `scripts/benchmark_evaluation.py` — prediction validation and explicit evaluation+- `scripts/molecular_generation.py` — bounded local/checkpoint scoring and MolGen plan+- `scripts/cache_audit.py` — read-only bounded cache manifest-## Additional Resources+Every CLI uses lazy optional imports, safe relative output/cache paths, JSON+summaries, bounded output, and no implicit dataset/model download.-- **Official Website**: https://tdcommons.ai-- **Documentation**: https://tdc.readthedocs.io-- **GitHub**: https://github.com/mims-harvard/TDC-- **Paper**: NeurIPS 2021 - "Therapeutics Data Commons: Machine Learning Datasets and Tasks for Drug Discovery and Development"+### References+- [references/datasets.md](references/datasets.md) — task discovery, data access,+ cache behavior, and licensing+- [references/utilities.md](references/utilities.md) — splits, evaluators, and+ benchmark-group APIs+- [references/oracles.md](references/oracles.md) — oracle categories, side effects,+ and safe execution+- [references/sources.md](references/sources.md) — dated authoritative sources and+ unresolved upstream gapsdiff --git a/skills/pytdc/references/datasets.md b/skills/pytdc/references/datasets.mdindex e936f0a1..019aa256 100644--- a/skills/pytdc/references/datasets.md+++ b/skills/pytdc/references/datasets.md@@ -1,246 +1,242 @@-# TDC Datasets Comprehensive Catalog--This document provides a comprehensive catalog of all available datasets in the Therapeutics Data Commons, organized by task category.--## Single-Instance Prediction Datasets--### ADME (Absorption, Distribution, Metabolism, Excretion)--**Absorption:**-- `Caco2_Wang` - Caco-2 cell permeability (906 compounds)-- `Caco2_AstraZeneca` - Caco-2 permeability from AstraZeneca (700 compounds)-- `HIA_Hou` - Human intestinal absorption (578 compounds)-- `Pgp_Broccatelli` - P-glycoprotein inhibition (1,212 compounds)-- `Bioavailability_Ma` - Oral bioavailability (640 compounds)-- `F20_edrug3d` - Oral bioavailability F>=20% (1,017 compounds)-- `F30_edrug3d` - Oral bioavailability F>=30% (1,017 compounds)--**Distribution:**-- `BBB_Martins` - Blood-brain barrier penetration (1,975 compounds)-- `PPBR_AZ` - Plasma protein binding rate (1,797 compounds)-- `VDss_Lombardo` - Volume of distribution at steady state (1,130 compounds)--**Metabolism:**-- `CYP2C19_Veith` - CYP2C19 inhibition (12,665 compounds)-- `CYP2D6_Veith` - CYP2D6 inhibition (13,130 compounds)-- `CYP3A4_Veith` - CYP3A4 inhibition (12,328 compounds)-- `CYP1A2_Veith` - CYP1A2 inhibition (12,579 compounds)-- `CYP2C9_Veith` - CYP2C9 inhibition (12,092 compounds)-- `CYP2C9_Substrate_CarbonMangels` - CYP2C9 substrate (666 compounds)-- `CYP2D6_Substrate_CarbonMangels` - CYP2D6 substrate (664 compounds)-- `CYP3A4_Substrate_CarbonMangels` - CYP3A4 substrate (667 compounds)--**Excretion:**-- `Half_Life_Obach` - Half-life (667 compounds)-- `Clearance_Hepatocyte_AZ` - Hepatocyte clearance (1,020 compounds)-- `Clearance_Microsome_AZ` - Microsome clearance (1,102 compounds)+# PyTDC datasets and data access-**Solubility & Lipophilicity:**-- `Solubility_AqSolDB` - Aqueous solubility (9,982 compounds)-- `Lipophilicity_AstraZeneca` - Lipophilicity (logD) (4,200 compounds)-- `HydrationFreeEnergy_FreeSolv` - Hydration free energy (642 compounds)+This reference targets the **PyTDC 1.1.15** source distribution, verified+2026-07-23. Dataset registries evolve independently of this skill, so query the+installed package instead of copying a historical catalog.-### Toxicity+## Discovery is not download-**Organ Toxicity:**-- `hERG` - hERG channel inhibition/cardiotoxicity (648 compounds)-- `hERG_Karim` - hERG blockers extended dataset (13,445 compounds)-- `DILI` - Drug-induced liver injury (475 compounds)-- `Skin_Reaction` - Skin reaction (404 compounds)-- `Carcinogens_Lagunin` - Carcinogenicity (278 compounds)-- `Respiratory_Toxicity` - Respiratory toxicity (278 compounds)+`tdc.metadata` contains static Python registries. Reading them does not construct a+loader, contact Harvard Dataverse, or download a dataset:-**General Toxicity:**-- `AMES` - Ames mutagenicity (7,255 compounds)-- `LD50_Zhu` - Acute toxicity LD50 (7,385 compounds)-- `ClinTox` - Clinical trial toxicity (1,478 compounds)-- `SkinSensitization` - Skin sensitization (278 compounds)-- `EyeCorrosion` - Eye corrosion (278 compounds)-- `EyeIrritation` - Eye irritation (278 compounds)+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind tasks --limit 100-**Environmental Toxicity:**-- `Tox21-AhR` - Nuclear receptor signaling (8,169 compounds)-- `Tox21-AR` - Androgen receptor (9,362 compounds)-- `Tox21-AR-LBD` - Androgen receptor ligand binding (8,343 compounds)-- `Tox21-ARE` - Antioxidant response element (6,475 compounds)-- `Tox21-aromatase` - Aromatase inhibition (6,733 compounds)-- `Tox21-ATAD5` - DNA damage (8,163 compounds)-- `Tox21-ER` - Estrogen receptor (7,257 compounds)-- `Tox21-ER-LBD` - Estrogen receptor ligand binding (8,163 compounds)-- `Tox21-HSE` - Heat shock response (8,162 compounds)-- `Tox21-MMP` - Mitochondrial membrane potential (7,394 compounds)-- `Tox21-p53` - p53 pathway (8,163 compounds)-- `Tox21-PPAR-gamma` - PPAR gamma activation (7,396 compounds)--### HTS (High-Throughput Screening)--**SARS-CoV-2:**-- `SARSCoV2_Vitro_Touret` - In vitro antiviral activity (1,484 compounds)-- `SARSCoV2_3CLPro_Diamond` - 3CL protease inhibition (879 compounds)-- `SARSCoV2_Vitro_AlabdulKareem` - In vitro screening (5,953 compounds)--**Other Targets:**-- `Orexin1_Receptor_Butkiewicz` - Orexin receptor screening (4,675 compounds)-- `M1_Receptor_Agonist_Butkiewicz` - M1 receptor agonist (1,700 compounds)-- `M1_Receptor_Antagonist_Butkiewicz` - M1 receptor antagonist (1,700 compounds)-- `HIV_Butkiewicz` - HIV inhibition (40,000+ compounds)-- `ToxCast` - Environmental chemical screening (8,597 compounds)--### QM (Quantum Mechanics)--- `QM7` - Quantum mechanics properties (7,160 molecules)-- `QM8` - Electronic spectra and excited states (21,786 molecules)-- `QM9` - Geometric, energetic, electronic, thermodynamic properties (133,885 molecules)--### Yields--- `Buchwald-Hartwig` - Reaction yield prediction (3,955 reactions)-- `USPTO_Yields` - Yield prediction from USPTO (853,879 reactions)--### Epitope+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind datasets --task DTI --limit 100+```-- `IEDBpep-DiseaseBinder` - Disease-associated epitope binding (6,080 peptides)-- `IEDBpep-NonBinder` - Non-binding peptides (24,320 peptides)+The package helper is also metadata-only:-### Develop (Development)+```python+from tdc.utils import retrieve_dataset_names-- `Manufacturing` - Manufacturing success prediction-- `Formulation` - Formulation stability+# Task key is exact and case-sensitive in PyTDC 1.1.15.+names = retrieve_dataset_names("ADME")+```-### CRISPROutcome+`retrieve_dataset_names` returns normalized package identifiers, usually lowercase.+Pass an exact returned name to scripts. Although constructors support fuzzy+matching, fuzzy selection can hide a typo or select an unintended resource.-- `CRISPROutcome_Doench` - Gene editing efficiency prediction (5,310 guide RNAs)+## Public task imports in 1.1.15-## Multi-Instance Prediction Datasets+These names come from the stable source distribution's public `__init__.py` files,+not from older prose catalogs.-### DTI (Drug-Target Interaction)+### Single-instance prediction-**Binding Affinity:**-- `BindingDB_Kd` - Dissociation constant (52,284 pairs, 10,665 drugs, 1,413 proteins)-- `BindingDB_IC50` - Half-maximal inhibitory concentration (991,486 pairs, 549,205 drugs, 5,078 proteins)-- `BindingDB_Ki` - Inhibition constant (375,032 pairs, 174,662 drugs, 3,070 proteins)+```python+from tdc.single_pred import (+ ADME,+ CRISPROutcome,+ Develop,+ Epitope,+ HTS,+ Paratope,+ QM,+ Tox,+ Yields,+)+```-**Kinase Binding:**-- `DAVIS` - Davis kinase binding dataset (30,056 pairs, 68 drugs, 442 proteins)-- `KIBA` - KIBA kinase binding dataset (118,254 pairs, 2,111 drugs, 229 proteins)+### Multi-instance prediction-**Binary Interaction:**-- `BindingDB_Patent` - Patent-derived DTI (8,503 pairs)-- `BindingDB_Approval` - FDA-approved drug DTI (1,649 pairs)+```python+from tdc.multi_pred import (+ AntibodyAff,+ Catalyst,+ DDI,+ DrugRes,+ DrugSyn,+ DTI,+ GDA,+ MTI,+ PeptideMHC,+ PPI,+ PerturbOutcome,+ ProteinPeptide,+ TCREpitopeBinding,+ TrialOutcome,+)+```-### DDI (Drug-Drug Interaction)+Some new task classes and resource APIs do not share the ordinary+download-to-DataFrame contract. Confirm that a task appears both in public imports+and `metadata.dataset_names` before using the generic loader CLI.-- `DrugBank` - Drug-drug interactions (191,808 pairs, 1,706 drugs)-- `TWOSIDES` - Side effect-based DDI (4,649,441 pairs, 645 drugs)+### Generation-### PPI (Protein-Protein Interaction)+```python+from tdc.generation import MolGen, Reaction, RetroSyn, SBDD+```-- `HuRI` - Human reference protein interactome (52,569 interactions)-- `STRING` - Protein functional associations (19,247 interactions)+The 1.1.15 registry exposes ordinary MolGen corpora under `MolGen`, paired reaction+data under `Reaction`/`RetroSyn`, and structure-based resources under the lowercase+`sbdd` key. The bundled generic loader supports the verified ordinary+MolGen/Reaction/RetroSyn paths; use specialized upstream documentation for SBDD.-### GDA (Gene-Disease Association)+## What causes a download-- `DisGeNET` - Gene-disease associations (81,746 pairs)-- `PrimeKG_GDA` - Gene-disease from PrimeKG knowledge graph+Ordinary constructor calls immediately invoke a load wrapper:-### DrugRes (Drug Response/Resistance)+```python+from tdc.single_pred import ADME-- `GDSC1` - Genomics of Drug Sensitivity in Cancer v1 (178,000 pairs)-- `GDSC2` - Genomics of Drug Sensitivity in Cancer v2 (125,000 pairs)+# Potential network and disk write if the exact local file is absent.+data = ADME(name="caco2_wang", path=".pytdc-data")+```-### DrugSyn (Drug Synergy)+For core datasets, PyTDC 1.1.15:-- `DrugComb` - Drug combination synergy (345,502 combinations)-- `DrugCombDB` - Drug combination database (448,555 combinations)-- `OncoPolyPharmacology` - Oncology drug combinations (22,737 combinations)+1. normalizes the requested name against the task registry;+2. checks for a task-specific filename beneath `path`;+3. if absent, requests a Harvard Dataverse file endpoint;+4. streams the response to that path;+5. parses the local tab/CSV/XLSX/pickle/JSON/H5AD/archive format.-### PeptideMHC+Many datasets are associated with the Harvard Dataverse collection+<https://doi.org/10.7910/DVN/21LKWG>. Newer resources may instead use CELLxGENE,+Hugging Face, or task-specific APIs; inspect the resource class before approval.-- `MHC1_NetMHCpan` - MHC class I binding (184,983 pairs)-- `MHC2_NetMHCIIpan` - MHC class II binding (134,281 pairs)+PyTDC checks for expected filenames, not a complete content-addressed cache with+documented checksums. An interrupted or stale local file may therefore need manual+review. Never delete or redownload a user's cache without confirmation.-### AntibodyAff (Antibody Affinity)+## Cache locations-- `Protein_SAbDab` - Antibody-antigen affinity (1,500+ pairs)+- Ordinary loader default: `./data`+- `MolGen`/`Reaction`/`RetroSyn` default: `./data`+- Generic `BenchmarkGroup` default: `./data`, then a normalized group subdirectory+- Download-backed oracle default: `./oracle`+- Bundled dataset CLI default: `.pytdc-data`+- Bundled benchmark CLI default: `.pytdc-benchmarks`+- Bundled MolGen CLI default: `.pytdc-molgen`+- Bundled oracle runtime default: `.pytdc-oracles` (upstream creates `oracle/`+ inside it for acknowledged checkpoints)-### MTI (miRNA-Target Interaction)+All bundled CLIs require relative paths inside the current workspace. They do not+overwrite JSON outputs unless `--force` is supplied.-- `miRTarBase` - Experimentally validated miRNA-target interactions (380,639 pairs)+Audit an existing directory without network access:-### Catalyst+```bash+python scripts/cache_audit.py --cache-dir .pytdc-data --largest 20+```-- `USPTO_Catalyst` - Catalyst prediction for reactions (11,000+ reactions)+The audit reports regular-file counts, total bytes, extensions, bounded largest+files, errors, and skipped symbolic links. It does not hash, modify, or upload data.-### TrialOutcome+## Approval gate-- `TrialOutcome_WuXi` - Clinical trial outcome prediction (3,769 trials)+Before constructing any loader, present:-## Generation Datasets+- exact package version, task, and dataset registry name;+- official TDC task/dataset page and original data source;+- dataset-specific license/terms and required citations;+- published row/record count or archive size when available;+- proposed relative cache path and available local disk;+- likely network transfer and decompressed footprint;+- split method, fractions, seed, and rationale;+- any sensitive/proprietary inputs that must not leave the environment.-### MolGen (Molecular Generation)+Ask for explicit approval before the first download or any large redownload. The+bundled scripts make planning the default and reserve construction for `--execute`;+MolGen additionally requires `--download`.-- `ChEMBL_V29` - Drug-like molecules from ChEMBL (1,941,410 molecules)-- `ZINC` - ZINC database subset (100,000+ molecules)-- `GuacaMol` - Goal-directed benchmark molecules-- `Moses` - Molecular sets benchmark (1,936,962 molecules)+## Data license is not the code license-### RetroSyn (Retrosynthesis)+The `mims-harvard/TDC` codebase and this skill are MIT-licensed. That does not grant+a blanket MIT license for hosted data.-- `USPTO` - Retrosynthesis from USPTO patents (1,939,253 reactions)-- `USPTO-50K` - Curated USPTO subset (50,000 reactions)+Official task pages show dataset-specific entries. As of the verification date,+examples include Creative Commons licenses, “Not Specified” entries, and+non-commercial terms (for example, clinical-trial outcome data). Treat the exact+page and original provider terms as authoritative for:-### PairMolGen (Paired Molecule Generation)+- commercial use;+- redistribution or derivative datasets;+- attribution and citation;+- patient/clinical restrictions;+- access tokens or API terms;+- geographic or institutional restrictions.-- `Prodrug` - Prodrug to drug transformations (1,000+ pairs)-- `Metabolite` - Drug to metabolite transformations+If the TDC page says “Not Specified,” do not infer permission from its nearby+Creative Commons link. Trace the original source and ask the user to resolve the+license before reuse.-## Using retrieve_dataset_names+## Returned data-To programmatically access all available datasets for a specific task:+For ordinary prediction loaders:```python-from tdc.utils import retrieve_dataset_names--# Get all datasets for a specific task-adme_datasets = retrieve_dataset_names('ADME')-tox_datasets = retrieve_dataset_names('Tox')-dti_datasets = retrieve_dataset_names('DTI')-hts_datasets = retrieve_dataset_names('HTS')+frame = data.get_data(format="df")+mapping = data.get_data(format="dict")```-## Dataset Statistics+Supported formats and columns are loader-specific. Common prediction frames use+entity identifiers/representations plus `Y`, but do not hard-code `Drug`, `Target`,+or identifier columns before inspecting `frame.columns`.-Access dataset statistics directly:+Some loaders also expose `format="DeepPurpose"`. Do not assume PyG, DGL, or+arbitrary graph formats are valid `get_data` formats; representation conversion is+a separate, dependency-heavy workflow.-```python-from tdc.single_pred import ADME-data = ADME(name='Caco2_Wang')+For multi-label datasets, constructors can require `label_name`. Discover labels+without loading the main dataset:-# Print basic statistics-data.print_stats()+```python+from tdc.utils import retrieve_label_name_list-# Get label distribution-data.label_distribution()+labels = retrieve_label_name_list("tox21")```-## Loading Datasets--All datasets follow the same loading pattern:+Label meaning may require a separate mapping file and therefore can trigger its own+download. Do not call it during a metadata-only plan.++## Dataset and split provenance++Record at minimum:++```json+{+ "package": "PyTDC",+ "version": "1.1.15",+ "task": "ADME",+ "dataset": "caco2_wang",+ "cache_path": ".pytdc-data",+ "split_method": "scaffold",+ "split_seed": 42,+ "split_fractions": [0.7, 0.1, 0.2],+ "license_reviewed": true,+ "source_page": "https://tdcommons.ai/single_pred_tasks/adme"+}+```-```python-from tdc.<problem_type> import <TaskType>-data = <TaskType>(name='<DatasetName>')+Also record the downloaded filename, byte size, retrieval date, row count, columns,+target transformation, duplicate handling, missing-value handling, and split+overlap audits. Do not claim a split is leakage-free solely because it is named+`scaffold` or `cold_split`.-# Get full dataset-df = data.get_data(format='df') # or 'dict', 'DeepPurpose', etc.+## Stable verified examples-# Get train/valid/test split-split = data.get_split(method='scaffold', seed=1, frac=[0.7, 0.1, 0.2])-```+These are used only as API checks; run package discovery before use:-## Notes+- `ADME` → `caco2_wang` (official ADME page)+- `DTI` → `davis` and `bindingdb_patent` (official DTI/benchmark sources)+- `MolGen` → `moses` (official molecule-generation page)-- Dataset sizes and statistics are approximate and may be updated-- New datasets are regularly added to TDC-- Some datasets may require additional dependencies-- Check the official TDC website for the most up-to-date dataset list: https://tdcommons.ai/overview/+Names such as `PairMolGen`, generic `Prodrug`, or arbitrary `GuacaMol` datasets do+not appear in the PyTDC 1.1.15 public generation imports/registry and must not be+presented as supported loaders.diff --git a/skills/pytdc/references/oracles.md b/skills/pytdc/references/oracles.mdindex e12f157c..a98128e5 100644--- a/skills/pytdc/references/oracles.md+++ b/skills/pytdc/references/oracles.md@@ -1,400 +1,273 @@-# TDC Molecule Generation Oracles+# Molecular generation and PyTDC oracles-Oracles are functions that evaluate the quality of generated molecules across specific dimensions. TDC provides 17+ oracle functions for molecular optimization tasks in de novo drug design.+This reference targets **PyTDC 1.1.15**, verified 2026-07-23. Oracle names and+behavior are heterogeneous. Discover the installed registry and classify side+effects before constructing an `Oracle`.-## Overview+## PyTDC's role-Oracles measure molecular properties and serve two main purposes:+Core PyTDC provides:-1. **Goal-Directed Generation**: Optimize molecules to maximize/minimize specific properties-2. **Distribution Learning**: Evaluate whether generated molecules match desired property distributions+- molecular corpora through `tdc.generation.MolGen`;+- `Evaluator` functions for generated sets;+- scalar, composite, checkpoint-backed, remote-service, and docking oracles.-## Using Oracles+It does not supply one universal trainable molecule generator. Users bring or+implement the generative model and must define a scientifically justified+objective, constraints, validation protocol, and experimental follow-up.-### Basic Usage+## Discover names without calling an oracle-```python-from tdc import Oracle--# Initialize oracle-oracle = Oracle(name='GSK3B')--# Evaluate single molecule (SMILES string)-score = oracle('CC(C)Cc1ccc(cc1)C(C)C(O)=O')--# Evaluate multiple molecules-scores = oracle(['SMILES1', 'SMILES2', 'SMILES3'])+```bash+uv run --python 3.11 --with "setuptools==80.9.0" --with "PyTDC==1.1.15" \+ python scripts/discover_metadata.py --kind oracles --limit 100```-### Oracle Categories+This reads `tdc.metadata.oracle_names`; it does not instantiate an oracle, download+a checkpoint/receptor, or transmit a SMILES string.-TDC oracles are organized into several categories based on the molecular property being evaluated.+Use exact names. PyTDC fuzzy matching can silently normalize approximate input,+which is undesirable for expensive or remote operations.-## Biochemical Oracles+## Side-effect categories in the stable metadata-Predict binding affinity or activity against biological targets.+### Local scalar property-### Target-Specific Oracles+Verified direct local scalar name:-**DRD2 - Dopamine Receptor D2**-```python-oracle = Oracle(name='DRD2')-score = oracle(smiles)+```text+qed```-- Measures binding affinity to DRD2 receptor-- Important for neurological and psychiatric drug development-- Higher scores indicate stronger binding-**GSK3B - Glycogen Synthase Kinase-3 Beta**-```python-oracle = Oracle(name='GSK3B')-score = oracle(smiles)-```-- Predicts GSK3β inhibition-- Relevant for Alzheimer's, diabetes, and cancer research-- Higher scores indicate better inhibition+`qed` requires RDKit but no PyTDC model artifact. It is the quantitative estimate+of drug-likeness; higher is more drug-like on its documented 0–1 scale.-**JNK3 - c-Jun N-terminal Kinase 3**-```python-oracle = Oracle(name='JNK3')-score = oracle(smiles)-```-- Measures JNK3 kinase inhibition-- Target for neurodegenerative diseases-- Higher scores indicate stronger inhibition+Although upstream metadata groups `logp` and `sa` with “trivial” oracles, source+and execution verification show that both call `calculateScore`, which downloads+the `fpscores` artifact when absent. Treat both as download-backed.-**5HT2A - Serotonin 2A Receptor**-```python-oracle = Oracle(name='5HT2A')-score = oracle(smiles)-```-- Predicts serotonin receptor binding-- Important for psychiatric medications-- Higher scores indicate stronger binding+### Local composite/GuacaMol-style objectives-**ACE - Angiotensin-Converting Enzyme**-```python-oracle = Oracle(name='ACE')-score = oracle(smiles)-```-- Measures ACE inhibition-- Target for hypertension treatment-- Higher scores indicate better inhibition+The registry contains rediscovery, similarity, isomer, median, MPO, SMARTS, and hop+objectives. Some names use fixed targets; `*_meta` variants require constructor+arguments such as `target_smiles`.-**MAPK - Mitogen-Activated Protein Kinase**-```python-oracle = Oracle(name='MAPK')-score = oracle(smiles)-```-- Predicts MAPK inhibition-- Target for cancer and inflammatory diseases+Do not infer a constructor signature or score direction from the name. Read the+matching official oracle section and stable source before use. The bundled CLI does+not execute these objectives.-**CDK - Cyclin-Dependent Kinase**-```python-oracle = Oracle(name='CDK')-score = oracle(smiles)-```-- Measures CDK inhibition-- Important for cancer drug development+### Checkpoint-backed models-**P38 - p38 MAP Kinase**-```python-oracle = Oracle(name='P38')-score = oracle(smiles)-```-- Predicts p38 MAPK inhibition-- Target for inflammatory diseases+Stable download metadata includes:-**PARP1 - Poly (ADP-ribose) Polymerase 1**-```python-oracle = Oracle(name='PARP1')-score = oracle(smiles)+```text+drd2, gsk3b, jnk3, cyp3a4_veith, fpscores,+drd2_current, gsk3b_current, jnk3_current```-- Measures PARP1 inhibition-- Target for cancer treatment (DNA repair mechanism)-**PIK3CA - Phosphatidylinositol-4,5-Bisphosphate 3-Kinase**-```python-oracle = Oracle(name='PIK3CA')-score = oracle(smiles)-```-- Predicts PIK3CA inhibition-- Important target in oncology+Constructing one can call Harvard Dataverse and write a model file beneath+`./oracle`. For DRD2/GSK3B/JNK3, PyTDC may normalize the request to a `_current`+checkpoint according to the installed scikit-learn version.-## Physicochemical Oracles+Checkpoint files are serialized model artifacts. Review source, origin, local path,+size, and trust boundary before download/loading. The bundled CLI supports only+bounded LogP/SA/DRD2/GSK3B/JNK3/CYP3A4_Veith calls and requires both `--execute`+and `--download`.-Evaluate drug-like properties and ADME characteristics.+The 1.1.15 `LogP` oracle is not raw octanol/water partition alone. It implements+the normalized **penalized logP** objective: RDKit MolLogP plus a normalized+negative synthetic-accessibility term and a large-cycle penalty. Higher is the+objective's optimization direction. `SA` returns synthetic accessibility, for+which lower conventionally means easier synthesis. Do not combine either with+other scores without documenting transformation, scale, and direction.-### Drug-Likeness Oracles+### Distribution evaluators-**QED - Quantitative Estimate of Drug-likeness**-```python-oracle = Oracle(name='QED')-score = oracle(smiles)-```-- Combines multiple physicochemical properties-- Score ranges from 0 (non-drug-like) to 1 (drug-like)-- Based on Bickerton et al. criteria+The Oracle/Evaluator registries include:-**Lipinski - Rule of Five**-```python-oracle = Oracle(name='Lipinski')-score = oracle(smiles)+```text+novelty, diversity, uniqueness, validity, fcd_distance, kl_divergence```-- Number of Lipinski rule violations-- Rules: MW ≤ 500, logP ≤ 5, HBD ≤ 5, HBA ≤ 10-- Score of 0 means fully compliant-### Molecular Properties+These operate on collections, and several need a training/reference set. They are+not interchangeable scalar objectives:-**SA - Synthetic Accessibility**-```python-oracle = Oracle(name='SA')-score = oracle(smiles)-```-- Estimates ease of synthesis-- Score ranges from 1 (easy) to 10 (difficult)-- Lower scores indicate easier synthesis+- validity/uniqueness/novelty/diversity are higher by their documented definitions;+- FCD distance and KL divergence are lower as distance/divergence quantities;+- novelty and distribution comparisons depend on the exact reference corpus and+ canonicalization;+- optional chemical-model dependencies may be substantial.-**LogP - Octanol-Water Partition Coefficient**-```python-oracle = Oracle(name='LogP')-score = oracle(smiles)-```-- Measures lipophilicity-- Important for membrane permeability-- Typical drug-like range: 0-5+Use `Evaluator` and the official input signature. Do not send these through the+bundled scalar-scoring helper.-**MW - Molecular Weight**-```python-oracle = Oracle(name='MW')-score = oracle(smiles)-```-- Returns molecular weight in Daltons-- Drug-like range typically 150-500 Da+### Remote synthesis services-## Composite Oracles+Metadata includes `askcos` and `ibm_rxn`. Official documentation describes extra+host/API inputs. Calling them can transmit molecular structures and credentials to+an external service.-Combine multiple properties for multi-objective optimization.+Before any call:-**Isomer Meta**-```python-oracle = Oracle(name='Isomer_Meta')-score = oracle(smiles)-```-- Evaluates specific isomeric properties-- Used for stereochemistry optimization+1. identify the exact service operator and current terms;+2. determine whether the molecule is confidential or patent-sensitive;+3. obtain explicit user approval for transmission and cost;+4. read only the named credential required by that service;+5. never print or save the credential in JSON, logs, or command arguments;+6. enforce request/time/call limits.-**Median Molecules**-```python-oracle = Oracle(name='Median1', 'Median2')-score = oracle(smiles)-```-- Tests ability to generate molecules with median properties-- Useful for distribution learning benchmarks+The bundled script intentionally refuses these remote services. The 1.1.15 docs may+show historical endpoints or token flows; verify them with the service provider.-**Rediscovery**-```python-oracle = Oracle(name='Rediscovery')-score = oracle(smiles)-```-- Measures similarity to known reference molecules-- Tests ability to regenerate existing drugs+### Receptor and docking oracles-**Similarity**-```python-oracle = Oracle(name='Similarity')-score = oracle(smiles)-```-- Computes structural similarity to target molecules-- Based on molecular fingerprints (typically Tanimoto similarity)+The registry contains PDB-specific names ending in `_docking`,+`_docking_normalize`, and `_docking_vina`, plus specialized names such as+`pyscreener`, `docking_score`, `smina`, `rmsd`, and `kabsch_rmsd`.-**Uniqueness**-```python-oracle = Oracle(name='Uniqueness')-scores = oracle(smiles_list)-```-- Measures diversity in generated molecule set-- Returns fraction of unique molecules+These paths can involve:-**Novelty**-```python-oracle = Oracle(name='Novelty')-scores = oracle(smiles_list, training_set)-```-- Measures how different generated molecules are from training set-- Higher scores indicate more novel structures+- receptor PDB/PDBQT downloads;+- local executables and substantial CPU/storage;+- user-specified box centers/sizes;+- generated conformers and temporary files;+- license restrictions for docking software;+- remote or proprietary synthesis scoring in benchmark evaluation.-## Specialized Oracles+Raw docking energies and normalized variants have different directions. Never infer+direction from a generic “Docking” label. The bundled molecular CLI and benchmark+CLI do not execute docking.-**ASKCOS - Retrosynthesis Scoring**-```python-oracle = Oracle(name='ASKCOS')-score = oracle(smiles)-```-- Evaluates synthetic feasibility using retrosynthesis-- Requires ASKCOS backend (IBM RXN)-- Scores based on retrosynthetic route availability+## Bounded local scoring-**Docking Score**-```python-oracle = Oracle(name='Docking')-score = oracle(smiles)-```-- Molecular docking score against target protein-- Requires protein structure and docking software-- Lower scores typically indicate better binding+Plan first:-**Vina - AutoDock Vina Score**-```python-oracle = Oracle(name='Vina')-score = oracle(smiles)+```bash+python scripts/molecular_generation.py score \+ --oracle QED \+ --smiles "CCO"```-- Uses AutoDock Vina for protein-ligand docking-- Predicts binding affinity in kcal/mol-- More negative scores indicate stronger binding--## Multi-Objective Optimization--Combine multiple oracles for multi-property optimization:--```python-from tdc import Oracle-# Initialize multiple oracles-qed_oracle = Oracle(name='QED')-sa_oracle = Oracle(name='SA')-drd2_oracle = Oracle(name='DRD2')+The JSON plan reports classification, input count, runtime directory, and required+acknowledgement. It does not instantiate `Oracle`.-# Define custom scoring function-def multi_objective_score(smiles):- qed = qed_oracle(smiles)- sa = 1 / (1 + sa_oracle(smiles)) # Invert SA (lower is better)- drd2 = drd2_oracle(smiles)+Execute a local scalar only after review:- # Weighted combination- return 0.3 * qed + 0.3 * sa + 0.4 * drd2--# Evaluate molecule-score = multi_objective_score('CC(C)Cc1ccc(cc1)C(C)C(O)=O')+```bash+python scripts/molecular_generation.py score \+ --oracle QED \+ --smiles "CCO" \+ --execute```-## Oracle Performance Considerations--### Speed-- **Fast**: QED, SA, LogP, MW, Lipinski (rule-based calculations)-- **Medium**: Target-specific ML models (DRD2, GSK3B, etc.)-- **Slow**: Docking-based oracles (Vina, ASKCOS)--### Reliability-- Oracles are ML models trained on specific datasets-- May not generalize to all chemical spaces-- Use multiple oracles to validate results+Execute a supported checkpoint-backed model only after approving the checkpoint:-### Batch Processing-```python-# Efficient batch evaluation-oracle = Oracle(name='GSK3B')-smiles_list = ['SMILES1', 'SMILES2', ..., 'SMILES1000']-scores = oracle(smiles_list) # Faster than individual calls+```bash+python scripts/molecular_generation.py score \+ --oracle DRD2 \+ --smiles "CCO" \+ --runtime-dir .pytdc-oracles \+ --execute --download```-## Common Workflows--### Goal-Directed Generation-```python-from tdc import Oracle-from tdc.generation import MolGen--# Load training data-data = MolGen(name='ChEMBL_V29')-train_smiles = data.get_data()['Drug'].tolist()--# Initialize oracle-oracle = Oracle(name='GSK3B')+The helper:-# Generate molecules (user implements generative model)-# generated_smiles = generator.generate(n=1000)+- accepts at most 500 SMILES and a 1 MiB input file;+- keeps output in input order;+- truncates long strings;+- never ranks candidates or assumes score direction;+- changes into the safe runtime directory so upstream `./oracle` writes remain+ contained;+- refuses remote services, docking, distribution metrics, and composite objectives.-# Evaluate generated molecules-scores = oracle(generated_smiles)-best_molecules = [(s, score) for s, score in zip(generated_smiles, scores)]-best_molecules.sort(key=lambda x: x[1], reverse=True)+## Direct Oracle API-print(f"Top 10 molecules:")-for smiles, score in best_molecules[:10]:- print(f"{smiles}: {score:.3f}")-```+After side-effect review:-### Distribution Learning```pythonfrom tdc import Oracle-import numpy as np-# Initialize oracle-oracle = Oracle(name='QED')+oracle = Oracle(name="QED", num_max_call=100)+scores = oracle(["CCO", "c1ccccc1"])+```-# Evaluate training set-train_scores = oracle(train_smiles)-train_mean = np.mean(train_scores)-train_std = np.std(train_scores)+`num_max_call` bounds accumulated valid scalar calls for supported paths. It is not+a network timeout, memory limit, or cost limit.-# Evaluate generated set-gen_scores = oracle(generated_smiles)-gen_mean = np.mean(gen_scores)-gen_std = np.std(gen_scores)+For list input, PyTDC validates each SMILES with RDKit. Invalid entries can receive+the oracle's default value (commonly zero) rather than raising. Pre-validate+structures, preserve an explicit validity flag, and do not interpret the default as+a measured low score.-# Compare distributions-print(f"Training: μ={train_mean:.3f}, σ={train_std:.3f}")-print(f"Generated: μ={gen_mean:.3f}, σ={gen_std:.3f}")-```+Oracle results are predictions or computed proxies, not experimental evidence.+Applicability domains, model training data, stereochemistry, protonation,+tautomerization, salts, and assay context can materially change interpretation.-## Integration with TDC Benchmarks--```python-from tdc.generation import MolGen+## MolGen datasets-# Use with GuacaMol benchmark-data = MolGen(name='GuacaMol')+Discover the exact stable registry:-# Oracles are automatically integrated-# Each GuacaMol task has associated oracle-benchmark_results = data.evaluate_guacamol(- generated_molecules=your_molecules,- oracle_name='GSK3B'-)+```bash+python scripts/discover_metadata.py --kind datasets --task MolGen```-## Notes+Plan a random split:-- Oracle scores are predictions, not experimental measurements-- Always validate top candidates experimentally-- Different oracles may have different score ranges and interpretations-- Some oracles require additional dependencies or API access-- Check oracle documentation for specific details: https://tdcommons.ai/functions/oracles/--## Adding Custom Oracles+```bash+python scripts/molecular_generation.py dataset \+ --dataset MOSES \+ --seed 42 \+ --data-dir .pytdc-molgen+```-To create custom oracle functions:+MolGen corpora can contain hundreds of thousands or millions of structures. Review+the official page, per-dataset license, compressed/decompressed size, free disk,+and network budget. Execution intentionally requires both flags:-```python-class CustomOracle:- def __init__(self):- # Initialize your model/method- pass-- def __call__(self, smiles):- # Implement your scoring logic- # Return score or list of scores- pass--# Use like built-in oracles-custom_oracle = CustomOracle()-score = custom_oracle('CC(C)Cc1ccc(cc1)C(C)C(O)=O')+```bash+python scripts/molecular_generation.py dataset \+ --dataset MOSES \+ --seed 42 \+ --data-dir .pytdc-molgen \+ --execute --download```-## References--- TDC Oracles Documentation: https://tdcommons.ai/functions/oracles/-- GuacaMol Paper: "GuacaMol: Benchmarking Models for de Novo Molecular Design"-- MOSES Paper: "Molecular Sets (MOSES): A Benchmarking Platform for Molecular Generation Models"+PyTDC 1.1.15's MolGen loader exposes random split only. The supplied seed controls+test sampling, while the generic splitter uses fixed `random_state=1` for+validation sampling.++## Goal-directed optimization safeguards++Before optimizing:++- define whether every objective is maximized, minimized, targeted, or constrained;+- normalize only with justified transformations;+- separate train, validation, and final evaluation budgets;+- cap total unique oracle calls and deduplicate canonical structures;+- record invalid/failed/time-out results rather than silently dropping them;+- retain all candidates and scores needed for audit, but keep chat/CLI output+ bounded;+- monitor exploitation of model artifacts and out-of-domain structures;+- evaluate novelty against the exact declared training/reference set;+- add medicinal-chemistry, synthesizability, selectivity, safety, and diversity+ review rather than relying on a single score;+- treat computational hits as hypotheses requiring expert and experimental+ validation.++Do not claim a weighted sum is scientifically valid merely because every term is+numerical.++## Unsupported historical examples removed++The stable 1.1.15 metadata/public imports do not support old examples that presented+the following as generic ready-to-use APIs:++- `PairMolGen` / `Prodrug`;+- `MolGen(name="GuacaMol")`;+- `evaluate_guacamol(...)`;+- scalar `MW`, `Lipinski`, generic `Docking`, or generic `Vina` oracle names;+- target oracles such as `5HT2A`, `ACE`, `MAPK`, `CDK`, `P38`, `PARP1`, or+ `PIK3CA`.++Do not restore these names without verifying a newer official package registry and+source implementation.diff --git a/skills/pytdc/references/sources.md b/skills/pytdc/references/sources.mdnew file mode 100644index 00000000..7c49912d--- /dev/null+++ b/skills/pytdc/references/sources.md@@ -0,0 +1,165 @@+# Sources and verification record++Research performed **2026-07-23** with targeted Parallel search/extract, official+PyPI JSON metadata, the PyTDC 1.1.15 source distribution, and an isolated import/API+smoke test. Web results were treated as untrusted text; only authoritative sources+below determined the skill.++## Release and package metadata++1. [PyTDC on PyPI](https://pypi.org/project/pytdc/)+ - Stable release: **1.1.15**+ - Uploaded: **2025-03-31**+ - Distribution: source tarball only, 154,168 bytes+ - SHA-256:+ `cd6164859af7b9b6f60e0c6d6e50679eacaffd09cfdea1acfc8bb7360e8e2205`+ - License metadata: MIT+ - No `Requires-Python` or Python classifiers+2. [PyPI JSON for 1.1.15](https://pypi.org/pypi/PyTDC/1.1.15/json)+ - Used to verify exact `Requires-Dist`, artifact metadata, and absence of+ `Requires-Python`.+3. [Official setup.py](https://github.com/mims-harvard/TDC/blob/main/setup.py)+ - Package name `pytdc`; version loaded from `tdc/version.py`; dependencies loaded+ from `requirements.txt`; no `python_requires`.+4. [Official requirements.txt](https://github.com/mims-harvard/TDC/blob/main/requirements.txt)+ - 1.1.15 pins/constrains a large dependency graph, including+ `cellxgene-census==1.15.0`, NumPy `<2`, RDKit `<2024.3.1`, Hugging Face+ packages, and TileDB-SOMA.+5. [cellxgene-census 1.15.0 JSON](https://pypi.org/pypi/cellxgene-census/1.15.0/json)+ - Declares `Requires-Python: >=3.8,<3.12`.+6. [RDKit 2023.9.6 JSON](https://pypi.org/pypi/rdkit/2023.9.6/json)+ - Provides CPython 3.8–3.12 wheels for common platforms, including macOS ARM64,+ but no CPython 3.13 wheel.+7. [Setuptools release history](https://setuptools.pypa.io/en/stable/history.html)+ - `pkg_resources` was deprecated long before this snapshot and removed in+ setuptools 82.0.0 (2026-02-08).+ - PyTDC 1.1.15 still imports it at runtime. The isolated smoke test therefore+ pins the verified compatibility release `setuptools==80.9.0`.++The pinned smoke environment uses CPython 3.11. PyTDC itself does not publish a+supported Python range, so this skill describes Python 3.11 plus setuptools 80.9.0+as the verified target rather than claiming broader upstream support. On the tested+macOS ARM64 resolver, the environment contained 123 packages and included large+Torch, RDKit, TileDB, Arrow, and scientific-Python artifacts.++## Official source used for API verification++1. [Package metadata registry](https://github.com/mims-harvard/TDC/blob/main/tdc/metadata.py)+ - Task/dataset names, evaluator names, oracle categories, benchmark names,+ benchmark metrics, and split metadata.+2. [Top-level public imports](https://github.com/mims-harvard/TDC/blob/main/tdc/__init__.py)+ - `Evaluator`, `Oracle`, and deprecated generic `BenchmarkGroup`.+3. [Single-prediction imports](https://github.com/mims-harvard/TDC/blob/main/tdc/single_pred/__init__.py)+4. [Multi-prediction imports](https://github.com/mims-harvard/TDC/blob/main/tdc/multi_pred/__init__.py)+5. [Generation imports](https://github.com/mims-harvard/TDC/blob/main/tdc/generation/__init__.py)+6. [Base loader](https://github.com/mims-harvard/TDC/blob/main/tdc/base_dataset.py)+7. [Single-prediction loader](https://github.com/mims-harvard/TDC/blob/main/tdc/single_pred/single_pred_dataset.py)+8. [Pair-prediction loader](https://github.com/mims-harvard/TDC/blob/main/tdc/multi_pred/bi_pred_dataset.py)+9. [General multi-prediction loader](https://github.com/mims-harvard/TDC/blob/main/tdc/multi_pred/multi_pred_dataset.py)+10. [Generation loader](https://github.com/mims-harvard/TDC/blob/main/tdc/generation/generation_dataset.py)+11. [Split implementations](https://github.com/mims-harvard/TDC/blob/main/tdc/utils/split.py)+12. [Evaluator implementation](https://github.com/mims-harvard/TDC/blob/main/tdc/evaluator.py)+13. [Oracle implementation](https://github.com/mims-harvard/TDC/blob/main/tdc/oracles.py)+14. [Download/load implementation](https://github.com/mims-harvard/TDC/blob/main/tdc/utils/load.py)+15. [Metadata retrieval helpers](https://github.com/mims-harvard/TDC/blob/main/tdc/utils/retrieve.py)+16. [Specialized BenchmarkGroup base](https://github.com/mims-harvard/TDC/blob/main/tdc/benchmark_group/base_group.py)+17. [Deprecated generic BenchmarkGroup](https://github.com/mims-harvard/TDC/blob/main/tdc/benchmark_deprecated.py)++The stable PyPI source distribution was inspected directly rather than assuming+that `main` or old generated documentation exactly matched 1.1.15.++## Official user documentation++1. [TDC quick start](https://tdcommons.ai/start/)+ - Problem/task/dataset hierarchy and constructor/get-data/get-split workflow.+2. [Dataset splits](https://tdcommons.ai/functions/data_split/)+ - Random defaults, documented scaffold scope, `cold_split` plus `column_name`,+ and combination split.+3. [Model evaluation](https://tdcommons.ai/functions/data_evaluation/)+ - Exact evaluator examples, input types, thresholds, and metric definitions.+4. [Benchmark/leaderboard guide](https://tdcommons.ai/benchmark/overview/)+ - `get`, `get_train_valid_split`, `evaluate`, `evaluate_many`, fixed test set,+ and at least five independent runs.+5. [ADMET benchmark group](https://tdcommons.ai/benchmark/admet_group/overview)+ - Dataset-specific benchmark metrics and scaffold protocol.+6. [Oracle documentation](https://tdcommons.ai/functions/oracles/)+ - Local, checkpoint, synthesis-service, and docking examples/requirements.+7. [Molecule generation task](https://tdcommons.ai/generation_tasks/molgen)+ - Stable MolGen names and random split examples.+8. [ADME task](https://tdcommons.ai/single_pred_tasks/adme)+ - Dataset-specific descriptions, splits, citations, and heterogeneous license+ labels.+9. [DTI task](https://tdcommons.ai/multi_pred_tasks/dti/)+ - DTI datasets, cold-drug/protein intent, and per-dataset licenses.+10. [Trial outcome task](https://tdcommons.ai/multi_pred_tasks/trialoutcome/)+ - Evidence that some TDC datasets carry non-commercial terms.+11. [TDC 0.4.1 ReadTheDocs](https://tdc.readthedocs.io/)+ - Generated API signatures and source links used only as a cross-check. Its+ displayed release is behind PyPI 1.1.15.+12. [Harvard Dataverse TDC collection](https://doi.org/10.7910/DVN/21LKWG)+ - Persistent collection identifier linked by the official README. The landing+ page was unavailable to the extraction service during this research, so file+ sizes/collection-level terms were not inferred from it.++## Primary TDC papers++1. Huang, K., Fu, T., Gao, W. *et al.* (2021).+ [Therapeutics Data Commons: Machine Learning Datasets and Tasks for Drug+ Discovery and Development](https://datasets-benchmarks-proceedings.neurips.cc/paper_files/paper/2021/hash/4c56ff4ce4aaf9573aa5dff913df997a-Abstract-round1.html).+ NeurIPS Datasets and Benchmarks 2021. Published 2021-12-06.+ - Defines the original TDC task/dataset/benchmark/data-function scope.+2. Huang, K., Fu, T., Gao, W. *et al.* (2022).+ [Artificial intelligence foundation for therapeutic+ science](https://doi.org/10.1038/s41589-022-01131-2).+ *Nature Chemical Biology* 18, 1033–1036. Published 2022-09-21.+ - Describes the Commons as infrastructure for AI-ready tasks, datasets, and+ benchmarks across therapeutic science.++Papers support the Commons design and citation guidance; current Python signatures+come from package source and official API documentation.++## Confirmed migrations and removed stale guidance++- `from tdc import BenchmarkGroup` is implemented in+ `benchmark_deprecated.py` and prints a deprecation message. Prefer+ `from tdc.benchmark_group import admet_group` (or another specialized group).+- `group.get(name)` returns `train_val`, `test`, and normalized `name`; it is not+ indexed by seed.+- Multi-run input is a list of prediction dictionaries passed to+ `evaluate_many`, with at least five runs for non-docking groups.+- Generic cold split is `method="cold_split", column_name=...`.+ `cold_drug_target` is not implemented.+- Pair temporal split is `method="time", time_column=...`; `temporal` is not+ implemented.+- `stratified=True` is not a loader split argument.+- Registered Pearson correlation is `PCC`, not `Pearson`.+- Public generation imports are `MolGen`, `Reaction`, `RetroSyn`, and `SBDD`;+ `PairMolGen` is absent.++## Unresolved upstream uncertainty++1. **No changelog, tags, or GitHub Releases.** PyPI release history establishes+ version/date, but upstream does not document a complete 0.4.x → 1.1.x migration.+2. **Python support is undeclared.** `Requires-Python` is absent, while transitive+ pins constrain viable interpreters/platforms. Re-run resolver/import smoke tests+ before changing Python or platform.+3. **Legacy runtime dependency.** PyTDC still imports deprecated `pkg_resources`;+ environments with setuptools 82+ fail unless upstream migrates or setuptools is+ pinned to a compatible release.+4. **Unmarked backport dependency.** PyTDC requires the `dataclasses` backport on+ modern Python without an environment marker even though Python 3.11 includes+ `dataclasses` in the standard library. Strict resolvers may handle that stale+ metadata differently.+5. **ReadTheDocs lags PyPI.** It identifies as 0.4.1 while PyPI is 1.1.15.+6. **Website/source drift exists.** Some website snippets use old names or output+ comments; stable source controls exact executable behavior.+7. **Ambiguous dataset license labels.** Some pages render “Not Specified” next to a+ Creative Commons link. Resolve terms from the original provider rather than+ inferring a license.+8. **Evaluator metadata inconsistency.** `smina` appears in the evaluator registry,+ but 1.1.15 does not bind it in `Evaluator.assign_evaluator`.+9. **Oracle metadata understates side effects.** `logp` and `sa` are grouped with+ trivial oracles, but their stable implementations call `calculateScore`, which+ downloads the `fpscores` artifact when it is absent.+10. **Separate fork/package.** `pytdc-nextml` is a distinct package/repository and+ was not treated as an upgrade or replacement for official PyPI `PyTDC`.diff --git a/skills/pytdc/references/utilities.md b/skills/pytdc/references/utilities.mdindex c9e029f4..c204ef87 100644--- a/skills/pytdc/references/utilities.md+++ b/skills/pytdc/references/utilities.md@@ -1,684 +1,364 @@-# TDC Utilities and Data Functions+# Splits, evaluators, and benchmark groups-This document provides comprehensive documentation for TDC's data processing, evaluation, and utility functions.+This reference describes behavior verified in the **PyTDC 1.1.15** source+distribution on 2026-07-23. The official website documents user-facing intent;+source inspection resolves exact method spellings and edge cases.-## Overview+## Split API overview-TDC provides utilities organized into four main categories:-1. **Dataset Splits** - Train/validation/test partitioning strategies-2. **Model Evaluation** - Standardized performance metrics-3. **Data Processing** - Molecule conversion, filtering, and transformation-4. **Entity Retrieval** - Database queries and conversions--## 1. Dataset Splits--Dataset splitting is crucial for evaluating model generalization. TDC provides multiple splitting strategies designed for therapeutic ML.--### Basic Split Usage+Ordinary loaders return:```python-from tdc.single_pred import ADME--data = ADME(name='Caco2_Wang')+{+ "train": train_frame,+ "valid": validation_frame,+ "test": test_frame,+}+```-# Get split with default parameters-split = data.get_split()-# Returns: {'train': DataFrame, 'valid': DataFrame, 'test': DataFrame}+The key is `valid`, not `val`. Generic defaults are:-# Customize split parameters+```pythonsplit = data.get_split(- method='scaffold',+ method="random",seed=42,- frac=[0.7, 0.1, 0.2]+ frac=[0.7, 0.1, 0.2],)```-### Split Methods--#### Random Split-Random shuffling of data - suitable for general ML tasks.--```python-split = data.get_split(method='random', seed=1)-```--**When to use:**-- Baseline model evaluation-- When chemical/temporal structure is not important-- Quick prototyping--**Not recommended for:**-- Realistic drug discovery scenarios-- Evaluating generalization to new chemical matter--#### Scaffold Split-Splits based on molecular scaffolds (Bemis-Murcko scaffolds) - ensures test molecules are structurally distinct from training.--```python-split = data.get_split(method='scaffold', seed=1)-```--**When to use:**-- Default for most single prediction tasks-- Evaluating generalization to new chemical series-- Realistic drug discovery scenarios--**How it works:**-1. Extract Bemis-Murcko scaffold from each molecule-2. Group molecules by scaffold-3. Assign scaffolds to train/valid/test sets-4. Ensures test molecules have unseen scaffolds--#### Cold Splits (DTI/DDI Tasks)-For multi-instance prediction, cold splits ensure test set contains unseen drugs, targets, or both.--**Cold Drug Split:**-```python-from tdc.multi_pred import DTI-data = DTI(name='BindingDB_Kd')-split = data.get_split(method='cold_drug', seed=1)-```-- Test set contains drugs not seen during training-- Evaluates generalization to new compounds--**Cold Target Split:**-```python-split = data.get_split(method='cold_target', seed=1)-```-- Test set contains targets not seen during training-- Evaluates generalization to new proteins--**Cold Drug-Target Split:**-```python-split = data.get_split(method='cold_drug_target', seed=1)-```-- Test set contains novel drug-target pairs-- Most challenging evaluation scenario--#### Temporal Split-For datasets with temporal information - ensures test data is from later time points.--```python-split = data.get_split(method='temporal', seed=1)-```--**When to use:**-- Datasets with time stamps-- Simulating prospective prediction-- Clinical trial outcome prediction+Fractions are train/validation/test and should be finite, non-negative, and sum to+one. Upstream does not consistently validate this before arithmetic; the bundled+CLI does.-### Custom Split Fractions+### Loader-specific methods-```python-# 80% train, 10% valid, 10% test-split = data.get_split(method='scaffold', frac=[0.8, 0.1, 0.1])--# 70% train, 15% valid, 15% test-split = data.get_split(method='scaffold', frac=[0.7, 0.15, 0.15])-```+| Loader family | Verified methods | Additional arguments |+|---|---|---|+| Single prediction | `random`, `scaffold`, internal `cold_<entity>` | none |+| Pair prediction (`DTI`, `DDI`, etc.) | `random`, `cold_split`, entity aliases such as `cold_drug`, `combination`, `time` | `column_name`, `time_column` |+| General multi-prediction frame | `random`, `cold_split`, `combination` | `column_name` |+| `MolGen`, `Reaction`, `RetroSyn` | `random` | none |+| Benchmark train/valid | group metadata chooses `scaffold`, `random`, `combination`, or `group` | `benchmark`, `split_type`, `seed` |-### Stratified Splits--For classification tasks with imbalanced labels:+The generic official cold-start spelling is:```python-split = data.get_split(method='scaffold', stratified=True)+split = data.get_split(+ method="cold_split",+ column_name=["Drug", "Target"],+ seed=42,+ frac=[0.7, 0.1, 0.2],+)```-Maintains label distribution across train/valid/test sets.--## 2. Model Evaluation--TDC provides standardized evaluation metrics for different task types.--### Basic Evaluator Usage--```python-from tdc import Evaluator+Inspect `data.get_data().columns` first. A DTI frame commonly uses `Drug` and+`Target`, but other tasks have different entity names. Prefer `cold_split` with+explicit columns over inferred aliases.-# Initialize evaluator-evaluator = Evaluator(name='ROC-AUC')+## Random split details-# Evaluate predictions-score = evaluator(y_true, y_pred)-```+`create_fold`:-### Classification Metrics+1. samples test rows with `random_state=seed`;+2. samples validation rows from the remainder with **fixed**+ `random_state=1`;+3. assigns remaining rows to train;+4. resets partition indices.-#### ROC-AUC-Receiver Operating Characteristic - Area Under Curve+Consequences:-```python-evaluator = Evaluator(name='ROC-AUC')-score = evaluator(y_true, y_pred_proba)-```+- the supplied seed changes test membership;+- it does not independently seed validation sampling;+- integer rounding and Pandas sampling can make exact counts differ from naïve+ multiplication;+- a different seed is not a guarantee that every partition changes.-**Best for:**-- Binary classification-- Imbalanced datasets-- Overall discriminative ability+Record content hashes or stable IDs when exact split reproducibility matters.-**Range:** 0-1 (higher is better, 0.5 is random)+## Scaffold split details-#### PR-AUC-Precision-Recall Area Under Curve+The official generic documentation limits scaffold split to molecule-based+single-instance ADME, Tox, and HTS tasks. In 1.1.15 the implementation:-```python-evaluator = Evaluator(name='PR-AUC')-score = evaluator(y_true, y_pred_proba)-```+- requires RDKit;+- parses the configured molecular entity as SMILES;+- computes Bemis–Murcko scaffold strings with `includeChirality=False`;+- groups rows by exact scaffold string;+- shuffles large and small scaffold groups with `seed`;+- greedily assigns whole groups to partitions;+- omits SMILES that raise during scaffold generation.-**Best for:**-- Highly imbalanced datasets-- When positive class is rare-- Complements ROC-AUC+The requested row fractions are targets, not guarantees, because whole scaffold+groups are assigned together. “Scaffold split” means exact computed scaffold groups+do not cross partitions in that implementation. It does **not** establish that:-**Range:** 0-1 (higher is better)+- close analogs or similar scaffolds cannot cross;+- duplicates, labels, assay batches, sources, or dates are isolated;+- stereochemistry is isolated;+- invalid/missing structures are represented;+- preprocessing performed before splitting did not leak information.-#### F1 Score-Harmonic mean of precision and recall+Audit exact structures, scaffolds, identifiers, labels, provenance, and temporal+fields appropriate to the scientific question. Use cautious language such as+“partitioned by PyTDC's 1.1.15 Murcko-scaffold implementation,” not “leakage-free.”-```python-evaluator = Evaluator(name='F1')-score = evaluator(y_true, y_pred_binary)-```+## Cold split details-**Best for:**-- Balance between precision and recall-- Multi-class classification+`cold_split` samples unique values independently for each requested column, then:-**Range:** 0-1 (higher is better)+- keeps test rows satisfying all sampled test-entity memberships;+- removes any row containing a test entity from the train/validation pool;+- samples validation entity values from the remainder;+- keeps validation rows satisfying all validation memberships;+- removes validation entities from train.-#### Accuracy-Fraction of correct predictions+For multiple columns this intersection/removal process can discard many+cross-combination rows, produce empty validation/test partitions, and yield row+fractions far from `frac`. PyTDC raises `ValueError` when test or validation is+empty.-```python-evaluator = Evaluator(name='Accuracy')-score = evaluator(y_true, y_pred_binary)-```+Exact values in each requested column are designed to be disjoint across returned+partitions. That is a narrow entity-overlap property, not proof against:-**Best for:**-- Balanced datasets-- Simple baseline metric+- aliases or duplicated entities with different identifiers;+- homologous targets or structurally near-identical compounds;+- shared higher-level groups;+- preprocessing or label leakage.-**Not recommended for:** Imbalanced datasets+The bundled loader CLI reports pairwise exact-value overlap counts for requested+columns without making a broader claim.-#### Cohen's Kappa-Agreement between predictions and ground truth, accounting for chance+`cold_drug_target` is not a 1.1.15 method. Use:```python-evaluator = Evaluator(name='Kappa')-score = evaluator(y_true, y_pred_binary)+data.get_split(+ method="cold_split",+ column_name=["Drug", "Target"],+ seed=42,+)```-**Range:** -1 to 1 (higher is better, 0 is random)+## Combination and time splits-### Regression Metrics+### Combination-#### RMSE - Root Mean Squared Error-```python-evaluator = Evaluator(name='RMSE')-score = evaluator(y_true, y_pred)-```+The built-in `combination` implementation is designed for DrugSyn data with+`Drug1_ID`, `Drug2_ID`, and `Cell_Line_ID`. It separates drug-pair combinations+across partitions while representing cell lines.-**Best for:**-- Continuous predictions-- Penalizes large errors heavily+In 1.1.15 it adds an internal `concat` column and does not remove it consistently+from every returned partition. Inspect schemas rather than assuming identical+columns. Do not apply it generically to DDI or DTI.-**Range:** 0-∞ (lower is better)+### Time-#### MAE - Mean Absolute Error-```python-evaluator = Evaluator(name='MAE')-score = evaluator(y_true, y_pred)-```+Pair loaders use:-**Best for:**-- Continuous predictions-- More robust to outliers than RMSE--**Range:** 0-∞ (lower is better)--#### R² - Coefficient of Determination```python-evaluator = Evaluator(name='R2')-score = evaluator(y_true, y_pred)+split = data.get_split(+ method="time",+ time_column="Year",+ frac=[0.7, 0.1, 0.2],+)```-**Best for:**-- Variance explained by model-- Comparing different models--**Range:** -∞ to 1 (higher is better, 1 is perfect)+The verified built-in dataset case is `DTI(name="BindingDB_Patent")`, whose loader+adds `Year`. The implementation sorts by the time column and returns an additional+`split_time` summary. It does not use `seed`.-#### MSE - Mean Squared Error-```python-evaluator = Evaluator(name='MSE')-score = evaluator(y_true, y_pred)-```+The spelling `temporal` is unsupported. Time boundaries can contain ties and the+implementation uses boundary comparisons, so inspect timestamps and counts.-**Range:** 0-∞ (lower is better)+`stratified=True` is not a supported `get_split` argument in these loaders.-### Ranking Metrics+## Evaluator registry-#### Spearman Correlation-Rank correlation coefficient+Discover exact names from the installed package:-```python-evaluator = Evaluator(name='Spearman')-score = evaluator(y_true, y_pred)+```bash+python scripts/discover_metadata.py --kind evaluators --limit 100```-**Best for:**-- Ranking tasks-- Non-linear relationships-- Ordinal data+Verified scalar registry names include:-**Range:** -1 to 1 (higher is better)--#### Pearson Correlation-Linear correlation coefficient--```python-evaluator = Evaluator(name='Pearson')-score = evaluator(y_true, y_pred)+```text+roc-auc, f1, pr-auc, precision, recall, accuracy,+mse, rmse, mae, r2, pcc, spearman,+micro-f1, macro-f1, kappa, avg-roc-auc,+rp@k, pr@k, range_logAUC```-**Best for:**-- Linear relationships-- Continuous data+Generation/distribution names include:-**Range:** -1 to 1 (higher is better)--### Multi-Label Classification--```python-evaluator = Evaluator(name='Micro-F1')-score = evaluator(y_true_multilabel, y_pred_multilabel)+```text+novelty, diversity, uniqueness, validity, fcd_distance, kl_divergence```-Available: `Micro-F1`, `Macro-F1`, `Micro-AUPR`, `Macro-AUPR`--### Benchmark Group Evaluation--For benchmark groups, evaluation requires multiple seeds:+Coordinate names include `rmsd` and `kabsch_rmsd`. Metadata also lists `smina`, but+the 1.1.15 `Evaluator.assign_evaluator` implementation does not bind an evaluator+function for it; treat `Evaluator("smina")` as an unresolved upstream inconsistency,+not supported usage.-```python-from tdc.benchmark_group import admet_group--group = admet_group(path='data/')-benchmark = group.get('Caco2_Wang')--# Predictions must be dict with seeds as keys-predictions = {}-for seed in [1, 2, 3, 4, 5]:- # Train model and predict- predictions[seed] = model_predictions--# Evaluate with mean and std across seeds-results = group.evaluate(predictions)-print(results) # {'Caco2_Wang': [mean_score, std_score]}-```+Always pass exact registry names. Fuzzy matching exists, but aliases such as+`Pearson`, `Micro-AUPR`, and `Macro-AUPR` are not registered.-## 3. Data Processing+### Inputs and direction-TDC provides 11 comprehensive data processing utilities.+| Metrics | Input | Better direction |+|---|---|---|+| `mse`, `rmse`, `mae` | continuous truth and predictions | lower |+| `r2`, `pcc`, `spearman` | continuous truth and predictions | higher |+| `roc-auc`, `pr-auc`, `range_logAUC` | binary truth and real-valued scores | higher |+| `accuracy`, `precision`, `recall`, `f1` | binary truth and scores plus optional threshold | higher |+| `micro-f1`, `macro-f1`, `kappa` | integer class labels | higher |+| `avg-roc-auc` | per-instance sequences of binary truth/scores | higher |+| `pr@k`, `rp@k` | binary truth/scores and target recall/precision | higher |+| `validity`, `uniqueness`, `novelty`, `diversity` | SMILES collections (some also need a reference set) | higher by their documented definitions |+| `fcd_distance`, `kl_divergence` | generated and reference SMILES | lower as distances/divergence |+| `rmsd`, `kabsch_rmsd` | paired coordinate arrays | lower |-### Molecule Format Conversion+This table describes evaluator semantics, not every benchmark's leaderboard+objective. Use `bm_metric_names` or the official benchmark page for the chosen+benchmark. Never infer a dataset's metric from “classification” or “regression”+alone.-Convert between ~15 molecular representations.+### Call behavior```python-from tdc.chem_utils import MolConvert--# SMILES to PyTorch Geometric-converter = MolConvert(src='SMILES', dst='PyG')-pyg_graph = converter('CC(C)Cc1ccc(cc1)C(C)C(O)=O')--# SMILES to DGL-converter = MolConvert(src='SMILES', dst='DGL')-dgl_graph = converter('CC(C)Cc1ccc(cc1)C(C)C(O)=O')+from tdc import Evaluator-# SMILES to Morgan Fingerprint (ECFP)-converter = MolConvert(src='SMILES', dst='ECFP')-fingerprint = converter('CC(C)Cc1ccc(cc1)C(C)C(O)=O')+mae = Evaluator("MAE")(y_true, y_pred)+auroc = Evaluator("ROC-AUC")(y_true_binary, predicted_scores)+spearman = Evaluator("Spearman")(y_true, y_pred)```-**Available formats:**-- **Text**: SMILES, SELFIES, InChI-- **Fingerprints**: ECFP (Morgan), MACCS, RDKit, AtomPair, TopologicalTorsion-- **Graphs**: PyG (PyTorch Geometric), DGL (Deep Graph Library)-- **3D**: Graph3D, Coulomb Matrix, Distance Matrix+Thresholded `accuracy`, `precision`, `recall`, and `f1` default to 0.5 and convert+scores with `score > threshold`; a score exactly equal to the threshold becomes+class 0. `PR@K` and `RP@K` default their target threshold to 0.9. Spearman returns+only the correlation coefficient from SciPy's result.-**Batch conversion:**-```python-converter = MolConvert(src='SMILES', dst='PyG')-graphs = converter(['SMILES1', 'SMILES2', 'SMILES3'])-```+Validate lengths, shapes, label encoding, missing values, score calibration, and+class presence before calling. ROC-AUC is undefined when only one class is present.-### Molecule Filters+## BenchmarkGroup API-Remove non-drug-like molecules using curated chemical rules.+Public specialized imports in 1.1.15 are:```python-from tdc.chem_utils import MolFilter--# Initialize filter with rules-mol_filter = MolFilter(- rules=['PAINS', 'BMS'], # Chemical filter rules- property_filters_dict={- 'MW': (150, 500), # Molecular weight range- 'LogP': (-0.4, 5.6), # Lipophilicity range- 'HBD': (0, 5), # H-bond donors- 'HBA': (0, 10) # H-bond acceptors- }+from tdc.benchmark_group import (+ admet_group,+ docking_group,+ drugcombo_group,+ dti_dg_group,)--# Filter molecules-filtered_smiles = mol_filter(smiles_list)-```--**Available filter rules:**-- `PAINS` - Pan-Assay Interference Compounds-- `BMS` - Bristol-Myers Squibb HTS deck filters-- `Glaxo` - GlaxoSmithKline filters-- `Dundee` - University of Dundee filters-- `Inpharmatica` - Inpharmatica filters-- `LINT` - Pfizer LINT filters--### Label Distribution Visualization--```python-# Visualize label distribution-data.label_distribution()--# Print statistics-data.print_stats()-```--Displays histogram and computes mean, median, std for continuous labels.--### Label Binarization--Convert continuous labels to binary using threshold.--```python-from tdc.utils import binarize--# Binarize with threshold-binary_labels = binarize(y_continuous, threshold=5.0, order='ascending')-# order='ascending': values >= threshold become 1-# order='descending': values <= threshold become 1```-### Label Units Conversion--Transform between measurement units.--```python-from tdc.chem_utils import label_transform--# Convert nM to pKd-y_pkd = label_transform(y_nM, from_unit='nM', to_unit='p')--# Convert μM to nM-y_nM = label_transform(y_uM, from_unit='uM', to_unit='nM')-```--**Available conversions:**-- Binding affinity: nM, μM, pKd, pKi, pIC50-- Log transformations-- Natural log conversions--### Label Meaning--Get interpretable descriptions for labels.+The generic top-level import is deprecated:```python-# Get label mapping-label_map = data.get_label_map(name='DrugBank')-print(label_map)-# {0: 'No interaction', 1: 'Increased effect', 2: 'Decreased effect', ...}+# Compatibility only; emits a deprecation message.+from tdc import BenchmarkGroup```-### Data Balancing--Handle class imbalance via over/under-sampling.+Use a specialized class. Construction can download and extract an entire group+archive:```python-from tdc.utils import balance--# Oversample minority class-X_balanced, y_balanced = balance(X, y, method='oversample')+from tdc.benchmark_group import admet_group-# Undersample majority class-X_balanced, y_balanced = balance(X, y, method='undersample')+group = admet_group(path=".pytdc-benchmarks")```-### Graph Transformation for Pair Data+Do this only after user approval.-Convert paired data to graph representations.+### Retrieve fixed test and train/validation data```python-from tdc.utils import create_graph_from_pairs+benchmark = group.get("Caco2_Wang")+name = benchmark["name"]+train_val = benchmark["train_val"]+test = benchmark["test"]-# Create graph from drug-drug pairs-graph = create_graph_from_pairs(- pairs=ddi_pairs, # [(drug1, drug2, label), ...]- format='edge_list' # or 'PyG', 'DGL'+train, valid = group.get_train_valid_split(+ seed=1,+ benchmark=name,+ split_type="default",)```-### Negative Sampling--Generate negative samples for binary tasks.--```python-from tdc.utils import negative_sample--# Generate negative samples for DTI-negative_pairs = negative_sample(- positive_pairs=known_interactions,- all_drugs=drug_list,- all_targets=target_list,- ratio=1.0 # Negative:positive ratio-)-```--**Use cases:**-- Drug-target interaction prediction-- Drug-drug interaction tasks-- Creating balanced datasets--### Entity Retrieval+There is no general `get_test()` method in 1.1.15. `group.get()` returns+`train_val`, `test`, and normalized `name`. `get_train_valid_split` reads the+downloaded train/validation file and applies group metadata. The held-out test set+is fixed.-Convert between database identifiers.+### One-run evaluation-#### PubChem CID to SMILES-```python-from tdc.utils import cid2smiles--smiles = cid2smiles(2244) # Aspirin-# Returns: 'CC(=O)Oc1ccccc1C(=O)O'-```+Predictions must align exactly with the downloaded test-frame row order:-#### UniProt ID to Amino Acid Sequence```python-from tdc.utils import uniprot2seq--sequence = uniprot2seq('P12345')-# Returns: 'MVKVYAPASS...'+predictions = {name: y_pred_test}+result = group.evaluate(predictions)+# {normalized_name: {metric_name: value}}```-#### Batch Retrieval-```python-# Multiple CIDs-smiles_list = [cid2smiles(cid) for cid in [2244, 5090, 6323]]+Do not include test labels as model features, generate predictions from test labels,+or tune against repeated test evaluations.-# Multiple UniProt IDs-sequences = [uniprot2seq(uid) for uid in ['P12345', 'Q9Y5S9']]-```--## 4. Advanced Utilities--### Retrieve Dataset Names+### Multi-run aggregation```python-from tdc.utils import retrieve_dataset_names--# Get all datasets for a task-adme_datasets = retrieve_dataset_names('ADME')-dti_datasets = retrieve_dataset_names('DTI')-tox_datasets = retrieve_dataset_names('Tox')--print(f"ADME datasets: {adme_datasets}")-```--### Fuzzy Search--TDC supports fuzzy matching for dataset names:--```python-from tdc.single_pred import ADME--# These all work (typo-tolerant)-data = ADME(name='Caco2_Wang')-data = ADME(name='caco2_wang')-data = ADME(name='Caco2') # Partial match-```--### Data Format Options--```python-# Pandas DataFrame (default)-df = data.get_data(format='df')--# Dictionary-data_dict = data.get_data(format='dict')--# DeepPurpose format (for DeepPurpose library)-dp_format = data.get_data(format='DeepPurpose')--# PyG/DGL graphs (if applicable)-graphs = data.get_data(format='PyG')-```--### Data Loader Utilities--```python-from tdc.utils import create_fold--# Create cross-validation folds-folds = create_fold(data, fold=5, seed=42)-# Returns list of (train_idx, test_idx) tuples--# Iterate through folds-for i, (train_idx, test_idx) in enumerate(folds):- train_data = data.iloc[train_idx]- test_data = data.iloc[test_idx]- # Train and evaluate-```--## Common Workflows--### Workflow 1: Complete Data Pipeline--```python-from tdc.single_pred import ADME-from tdc import Evaluator-from tdc.chem_utils import MolConvert, MolFilter--# 1. Load data-data = ADME(name='Caco2_Wang')--# 2. Filter molecules-mol_filter = MolFilter(rules=['PAINS'])-filtered_data = data.get_data()-filtered_data = filtered_data[- filtered_data['Drug'].apply(lambda x: mol_filter([x]))+prediction_runs = [+ {name: y_pred_seed_1},+ {name: y_pred_seed_2},+ {name: y_pred_seed_3},+ {name: y_pred_seed_4},+ {name: y_pred_seed_5},]--# 3. Split data-split = data.get_split(method='scaffold', seed=42)-train, valid, test = split['train'], split['valid'], split['test']--# 4. Convert to graph representations-converter = MolConvert(src='SMILES', dst='PyG')-train_graphs = converter(train['Drug'].tolist())--# 5. Train model (user implements)-# model.fit(train_graphs, train['Y'])--# 6. Evaluate-evaluator = Evaluator(name='MAE')-# score = evaluator(test['Y'], predictions)+summary = group.evaluate_many(prediction_runs)+# {normalized_name: [mean, population_standard_deviation]}```-### Workflow 2: Multi-Task Learning Preparation--```python-from tdc.benchmark_group import admet_group-from tdc.chem_utils import MolConvert+The input is a list of per-run dictionaries, not `{seed: predictions}` and not a+benchmark object indexed by seed. Non-docking groups require at least five runs.+The 1.1.15 implementation returns a `ValueError` object instead of raising when+fewer are supplied; the bundled CLI validates count first.-# Load benchmark group-group = admet_group(path='data/')+The official guidance calls for at least five independent runs. A seed should+control model initialization, stochastic training, and the train/validation split+where the upstream splitter actually uses it. Report every seed and protocol.-# Get multiple datasets-datasets = ['Caco2_Wang', 'HIA_Hou', 'Bioavailability_Ma']-all_data = {}+## Bundled benchmark JSON-for dataset_name in datasets:- benchmark = group.get(dataset_name)- all_data[dataset_name] = benchmark+Plan mode never constructs a group:-# Prepare for multi-task learning-converter = MolConvert(src='SMILES', dst='ECFP')-# Process each dataset...+```bash+python scripts/benchmark_evaluation.py \+ --group admet_group --dataset Caco2_Wang```-### Workflow 3: DTI Cold Split Evaluation+Single-run input:-```python-from tdc.multi_pred import DTI-from tdc import Evaluator--# Load DTI data-data = DTI(name='BindingDB_Kd')--# Cold drug split-split = data.get_split(method='cold_drug', seed=42)-train, test = split['train'], split['test']--# Verify no drug overlap-train_drugs = set(train['Drug_ID'])-test_drugs = set(test['Drug_ID'])-assert len(train_drugs & test_drugs) == 0, "Drug leakage detected!"--# Train and evaluate-# model.fit(train)-evaluator = Evaluator(name='RMSE')-# score = evaluator(test['Y'], predictions)+```json+{+ "caco2_wang": [0.1, 0.2, 0.3]+}```-## Best Practices--1. **Always use meaningful splits** - Use scaffold or cold splits for realistic evaluation-2. **Multiple seeds** - Run experiments with multiple seeds for robust results-3. **Appropriate metrics** - Choose metrics that match your task and dataset characteristics-4. **Data filtering** - Remove PAINS and non-drug-like molecules before training-5. **Format conversion** - Convert molecules to appropriate format for your model-6. **Batch processing** - Use batch operations for efficiency with large datasets--## Performance Tips+Multi-run input:-- Convert molecules in batch mode for faster processing-- Cache converted representations to avoid recomputation-- Use appropriate data formats for your framework (PyG, DGL, etc.)-- Filter data early in the pipeline to reduce computation--## References+```json+{+ "runs": [+ {"seed": 1, "predictions": {"caco2_wang": [0.1, 0.2]}},+ {"seed": 2, "predictions": {"caco2_wang": [0.1, 0.2]}},+ {"seed": 3, "predictions": {"caco2_wang": [0.1, 0.2]}},+ {"seed": 4, "predictions": {"caco2_wang": [0.1, 0.2]}},+ {"seed": 5, "predictions": {"caco2_wang": [0.1, 0.2]}}+ ]+}+```-- TDC Documentation: https://tdc.readthedocs.io-- Data Functions: https://tdcommons.ai/fct_overview/-- Evaluation Metrics: https://tdcommons.ai/functions/model_eval/-- Data Splits: https://tdcommons.ai/functions/data_split/+The CLI bounds input size/run count/value count, rejects non-finite numbers, and+requires `--execute` before group construction. It intentionally excludes+`docking_group` because that path can invoke docking, receptor downloads, molecular+filters, and optional external services.diff --git a/skills/pytdc/scripts/_common.py b/skills/pytdc/scripts/_common.pynew file mode 100644index 00000000..e55eff1a--- /dev/null+++ b/skills/pytdc/scripts/_common.py@@ -0,0 +1,205 @@+#!/usr/bin/env python3+"""Shared, standard-library-only helpers for the bundled PyTDC CLIs."""++from __future__ import annotations++import importlib+import json+import math+import os+import tempfile+from importlib.metadata import PackageNotFoundError, version+from pathlib import Path+from typing import Any, Iterable, Sequence+++class CliError(ValueError):+ """A user-facing command-line validation error."""+++def bounded_int(minimum: int, maximum: int):+ """Return an argparse converter for a bounded integer."""++ def convert(value: str) -> int:+ try:+ parsed = int(value)+ except ValueError as exc:+ raise ValueError(f"expected an integer, got {value!r}") from exc+ if not minimum <= parsed <= maximum:+ raise ValueError(+ f"expected an integer from {minimum} through {maximum}, got {parsed}"+ )+ return parsed++ return convert+++def canonical_name(query: str, choices: Iterable[str], label: str) -> str:+ """Resolve a name case-insensitively without fuzzy matching."""++ lookup = {str(choice).casefold(): str(choice) for choice in choices}+ try:+ return lookup[query.casefold()]+ except KeyError as exc:+ preview = ", ".join(sorted(lookup.values())[:20])+ suffix = "" if len(lookup) <= 20 else ", ..."+ raise CliError(f"unknown {label} {query!r}; available: {preview}{suffix}") from exc+++def safe_relative_path(+ raw_path: str,+ *,+ label: str,+ allow_workspace_root: bool = False,+) -> Path:+ """Resolve a relative path while preventing writes outside the workspace."""++ supplied = Path(raw_path)+ if supplied.is_absolute() or raw_path.startswith("~"):+ raise CliError(f"{label} must be a relative path inside the current workspace")++ workspace = Path.cwd().resolve()+ resolved = (workspace / supplied).resolve(strict=False)+ if resolved != workspace and workspace not in resolved.parents:+ raise CliError(f"{label} escapes the current workspace")+ if resolved == workspace and not allow_workspace_root:+ raise CliError(f"{label} must not be the workspace root")+ return resolved+++def safe_directory(+ raw_path: str,+ *,+ label: str,+ create: bool = False,+ must_exist: bool = False,+) -> Path:+ """Validate a workspace-contained directory."""++ path = safe_relative_path(raw_path, label=label)+ if path.exists() and (path.is_symlink() or not path.is_dir()):+ raise CliError(f"{label} is not a regular directory: {raw_path}")+ if must_exist and not path.is_dir():+ raise CliError(f"{label} does not exist: {raw_path}")+ if create:+ path.mkdir(parents=True, exist_ok=True)+ return path+++def safe_input_file(raw_path: str, *, max_bytes: int, label: str) -> Path:+ """Validate a bounded, workspace-contained input file."""++ path = safe_relative_path(raw_path, label=label)+ if path.is_symlink() or not path.is_file():+ raise CliError(f"{label} is not a regular file: {raw_path}")+ size = path.stat().st_size+ if size > max_bytes:+ raise CliError(f"{label} is {size} bytes; limit is {max_bytes} bytes")+ return path+++def validate_fractions(values: Sequence[float]) -> tuple[float, float, float]:+ """Validate train/validation/test fractions."""++ if len(values) != 3:+ raise CliError("--frac requires exactly three values")+ fractions = tuple(float(value) for value in values)+ if any(not math.isfinite(value) or value < 0 for value in fractions):+ raise CliError("split fractions must be finite and non-negative")+ if not math.isclose(sum(fractions), 1.0, rel_tol=0.0, abs_tol=1e-9):+ raise CliError("split fractions must sum to 1")+ if fractions[0] <= 0:+ raise CliError("the training fraction must be greater than zero")+ return fractions # type: ignore[return-value]+++def load_pytdc_metadata() -> tuple[Any, str]:+ """Lazily import bundled package metadata without instantiating a dataset."""++ try:+ metadata = importlib.import_module("tdc.metadata")+ package_version = version("PyTDC")+ except (ImportError, PackageNotFoundError) as exc:+ raise CliError(+ "PyTDC is unavailable; install the pinned snapshot with "+ "`uv pip install \"setuptools==80.9.0\" \"PyTDC==1.1.15\"`"+ ) from exc+ return metadata, package_version+++def truncate_value(value: Any, *, max_string: int = 160) -> Any:+ """Convert common scientific values to bounded JSON-compatible values."""++ if isinstance(value, Path):+ return str(value)+ if isinstance(value, str):+ if len(value) <= max_string:+ return value+ return value[:max_string] + f"...[{len(value) - max_string} chars omitted]"+ if isinstance(value, dict):+ return {+ str(key): truncate_value(item, max_string=max_string)+ for key, item in value.items()+ }+ if isinstance(value, (list, tuple)):+ return [truncate_value(item, max_string=max_string) for item in value]+ if isinstance(value, set):+ return sorted(truncate_value(item, max_string=max_string) for item in value)+ if hasattr(value, "item"):+ try:+ return truncate_value(value.item(), max_string=max_string)+ except (TypeError, ValueError):+ pass+ if hasattr(value, "tolist"):+ try:+ return truncate_value(value.tolist(), max_string=max_string)+ except (TypeError, ValueError):+ pass+ return value+++def read_json_file(path: Path) -> Any:+ """Read strict JSON, rejecting non-standard constants such as NaN."""++ def reject_constant(value: str) -> None:+ raise CliError(f"non-standard JSON constant is not allowed: {value}")++ try:+ with path.open("r", encoding="utf-8") as handle:+ return json.load(handle, parse_constant=reject_constant)+ except json.JSONDecodeError as exc:+ raise CliError(f"invalid JSON in {path.name}: {exc}") from exc+++def emit_json(payload: Any, output: str | None, *, force: bool = False) -> None:+ """Print JSON or atomically write it to a safe relative path."""++ serializable = truncate_value(payload)+ text = json.dumps(serializable, indent=2, sort_keys=True, allow_nan=False) + "\n"+ if output is None:+ print(text, end="")+ return++ destination = safe_relative_path(output, label="output path")+ if destination.exists() and (destination.is_symlink() or destination.is_dir()):+ raise CliError(f"output path is not a regular file: {output}")+ if destination.exists() and not force:+ raise CliError(f"output already exists: {output}; pass --force to replace it")++ destination.parent.mkdir(parents=True, exist_ok=True)+ temporary_name: str | None = None+ try:+ with tempfile.NamedTemporaryFile(+ "w",+ encoding="utf-8",+ dir=destination.parent,+ prefix=f".{destination.name}.",+ suffix=".tmp",+ delete=False,+ ) as handle:+ handle.write(text)+ temporary_name = handle.name+ os.replace(temporary_name, destination)+ finally:+ if temporary_name is not None:+ Path(temporary_name).unlink(missing_ok=True)diff --git a/skills/pytdc/scripts/benchmark_evaluation.py b/skills/pytdc/scripts/benchmark_evaluation.pyindex 1568d6b9..43a742e4 100644--- a/skills/pytdc/scripts/benchmark_evaluation.py+++ b/skills/pytdc/scripts/benchmark_evaluation.py@@ -1,327 +1,367 @@#!/usr/bin/env python3-"""-TDC Benchmark Group Evaluation Template--This script demonstrates how to use TDC benchmark groups for systematic-model evaluation following the required 5-seed protocol.--Usage:- python benchmark_evaluation.py-"""--from tdc.benchmark_group import admet_group-from tdc import Evaluator-import numpy as np-import pandas as pd---def load_benchmark_group():- """- Load the ADMET benchmark group- """- print("=" * 60)- print("Loading ADMET Benchmark Group")- print("=" * 60)-- # Initialize benchmark group- group = admet_group(path='data/')-- # Get available benchmarks- print("\nAvailable benchmarks in ADMET group:")- benchmark_names = group.dataset_names- print(f"Total: {len(benchmark_names)} datasets")-- for i, name in enumerate(benchmark_names[:10], 1):- print(f" {i}. {name}")-- if len(benchmark_names) > 10:- print(f" ... and {len(benchmark_names) - 10} more")-- return group---def single_dataset_evaluation(group, dataset_name='Caco2_Wang'):- """- Example: Evaluate on a single dataset with 5-seed protocol- """- print("\n" + "=" * 60)- print(f"Example 1: Single Dataset Evaluation ({dataset_name})")- print("=" * 60)-- # Get dataset benchmarks- benchmark = group.get(dataset_name)-- print(f"\nBenchmark structure:")- print(f" Seeds: {list(benchmark.keys())}")-- # Required: Evaluate with 5 different seeds- predictions = {}-- for seed in [1, 2, 3, 4, 5]:- print(f"\n--- Seed {seed} ---")-- # Get train/valid data for this seed- train = benchmark[seed]['train']- valid = benchmark[seed]['valid']-- print(f"Train size: {len(train)}")- print(f"Valid size: {len(valid)}")-- # TODO: Replace with your model training- # model = YourModel()- # model.fit(train['Drug'], train['Y'])-- # For demonstration, create dummy predictions- # Replace with: predictions[seed] = model.predict(benchmark[seed]['test'])- test = benchmark[seed]['test']- y_true = test['Y'].values-- # Simulate predictions (add controlled noise)- np.random.seed(seed)- y_pred = y_true + np.random.normal(0, 0.3, len(y_true))-- predictions[seed] = y_pred-- # Evaluate this seed- evaluator = Evaluator(name='MAE')- score = evaluator(y_true, y_pred)- print(f"MAE for seed {seed}: {score:.4f}")-- # Evaluate across all seeds- print("\n--- Overall Evaluation ---")- results = group.evaluate(predictions)-- print(f"\nResults for {dataset_name}:")- mean_score, std_score = results[dataset_name]- print(f" Mean MAE: {mean_score:.4f}")- print(f" Std MAE: {std_score:.4f}")-- return predictions, results---def multiple_datasets_evaluation(group):- """- Example: Evaluate on multiple datasets- """- print("\n" + "=" * 60)- print("Example 2: Multiple Datasets Evaluation")- print("=" * 60)-- # Select a subset of datasets for demonstration- selected_datasets = ['Caco2_Wang', 'HIA_Hou', 'Bioavailability_Ma']-- all_predictions = {}- all_results = {}-- for dataset_name in selected_datasets:- print(f"\n{'='*40}")- print(f"Evaluating: {dataset_name}")- print(f"{'='*40}")-- benchmark = group.get(dataset_name)- predictions = {}-- # Train and predict for each seed- for seed in [1, 2, 3, 4, 5]:- train = benchmark[seed]['train']- test = benchmark[seed]['test']-- # TODO: Replace with your model- # model = YourModel()- # model.fit(train['Drug'], train['Y'])- # predictions[seed] = model.predict(test['Drug'])-- # Dummy predictions for demonstration- np.random.seed(seed)- y_true = test['Y'].values- y_pred = y_true + np.random.normal(0, 0.3, len(y_true))- predictions[seed] = y_pred-- all_predictions[dataset_name] = predictions-- # Evaluate this dataset- results = group.evaluate({dataset_name: predictions})- all_results[dataset_name] = results[dataset_name]-- mean_score, std_score = results[dataset_name]- print(f" {dataset_name}: {mean_score:.4f} ± {std_score:.4f}")-- # Summary- print("\n" + "=" * 60)- print("Summary of Results")- print("=" * 60)-- results_df = pd.DataFrame([- {- 'Dataset': name,- 'Mean MAE': f"{mean:.4f}",- 'Std MAE': f"{std:.4f}"- }- for name, (mean, std) in all_results.items()- ])-- print(results_df.to_string(index=False))-- return all_predictions, all_results---def custom_model_template():- """- Template for integrating your own model with TDC benchmarks- """- print("\n" + "=" * 60)- print("Example 3: Custom Model Template")- print("=" * 60)-- code_template = '''-# Template for using your own model with TDC benchmarks--from tdc.benchmark_group import admet_group-from your_library import YourModel # Replace with your model--# Initialize benchmark group-group = admet_group(path='data/')-benchmark = group.get('Caco2_Wang')--predictions = {}--for seed in [1, 2, 3, 4, 5]:- # Get data for this seed- train = benchmark[seed]['train']- valid = benchmark[seed]['valid']- test = benchmark[seed]['test']-- # Extract features and labels- X_train, y_train = train['Drug'], train['Y']- X_valid, y_valid = valid['Drug'], valid['Y']- X_test = test['Drug']-- # Initialize and train model- model = YourModel(random_state=seed)- model.fit(X_train, y_train)-- # Optionally use validation set for early stopping- # model.fit(X_train, y_train, validation_data=(X_valid, y_valid))-- # Make predictions on test set- predictions[seed] = model.predict(X_test)--# Evaluate with TDC-results = group.evaluate(predictions)-print(f"Results: {results}")-'''-- print("\nCustom Model Integration Template:")- print("=" * 60)- print(code_template)-- return code_template---def multi_seed_statistics(predictions_dict):- """- Example: Analyzing multi-seed prediction statistics- """- print("\n" + "=" * 60)- print("Example 4: Multi-Seed Statistics Analysis")- print("=" * 60)-- # Analyze prediction variability across seeds- all_preds = np.array([predictions_dict[seed] for seed in [1, 2, 3, 4, 5]])-- print("\nPrediction statistics across 5 seeds:")- print(f" Shape: {all_preds.shape}")- print(f" Mean prediction: {all_preds.mean():.4f}")- print(f" Std across seeds: {all_preds.std(axis=0).mean():.4f}")- print(f" Min prediction: {all_preds.min():.4f}")- print(f" Max prediction: {all_preds.max():.4f}")-- # Per-sample variance- per_sample_std = all_preds.std(axis=0)- print(f"\nPer-sample prediction std:")- print(f" Mean: {per_sample_std.mean():.4f}")- print(f" Median: {np.median(per_sample_std):.4f}")- print(f" Max: {per_sample_std.max():.4f}")---def leaderboard_submission_guide():- """- Guide for submitting to TDC leaderboards- """- print("\n" + "=" * 60)- print("Example 5: Leaderboard Submission Guide")- print("=" * 60)-- guide = """-To submit results to TDC leaderboards:--1. Evaluate your model following the 5-seed protocol:- - Use seeds [1, 2, 3, 4, 5] exactly as provided- - Do not modify the train/valid/test splits- - Report mean ± std across all 5 seeds--2. Format your results:- results = group.evaluate(predictions)- # Returns: {'dataset_name': [mean_score, std_score]}--3. Submit to leaderboard:- - Visit: https://tdcommons.ai/benchmark/admet_group/- - Click on your dataset of interest- - Submit your results with:- * Model name and description- * Mean score ± standard deviation- * Reference to paper/code (if available)--4. Best practices:- - Report all datasets in the benchmark group- - Include model hyperparameters- - Share code for reproducibility- - Compare against baseline models--5. Evaluation metrics:- - ADMET Group uses MAE by default- - Other groups may use different metrics- - Check benchmark-specific requirements-"""-- print(guide)---def main():- """- Main function to run all benchmark evaluation examples- """- print("\n" + "=" * 60)- print("TDC Benchmark Group Evaluation Examples")- print("=" * 60)-- # Load benchmark group- group = load_benchmark_group()-- # Example 1: Single dataset evaluation- predictions, results = single_dataset_evaluation(group)-- # Example 2: Multiple datasets evaluation- all_predictions, all_results = multiple_datasets_evaluation(group)-- # Example 3: Custom model template- custom_model_template()-- # Example 4: Multi-seed statistics- multi_seed_statistics(predictions)-- # Example 5: Leaderboard submission guide- leaderboard_submission_guide()-- print("\n" + "=" * 60)- print("Benchmark evaluation examples completed!")- print("=" * 60)- print("\nNext steps:")- print("1. Replace dummy predictions with your model")- print("2. Run full evaluation on all benchmark datasets")- print("3. Submit results to TDC leaderboard")- print("=" * 60)+"""Plan or explicitly evaluate user-supplied TDC benchmark predictions."""++from __future__ import annotations++import argparse+import importlib+import math+import sys+from pathlib import Path+from typing import Any++from _common import (+ CliError,+ bounded_int,+ canonical_name,+ emit_json,+ load_pytdc_metadata,+ read_json_file,+ safe_directory,+ safe_input_file,+)+++# Docking is intentionally excluded: its evaluation can invoke specialized oracles.+GROUPS: dict[str, tuple[str, str]] = {+ "admet_group": ("tdc.benchmark_group", "admet_group"),+ "drugcombo_group": ("tdc.benchmark_group", "drugcombo_group"),+ "dti_dg_group": ("tdc.benchmark_group", "dti_dg_group"),+}++MAX_PREDICTION_FILE_BYTES = 50 * 1024 * 1024+MAX_PREDICTION_VALUES = 5_000_000+MAX_RUNS = 100+++def benchmark_names(metadata: Any, group: str) -> list[str]:+ return [+ name+ for names in metadata.benchmark_names[group].values()+ for name in names+ ]+++def validate_seeds(seeds: list[int]) -> list[int]:+ if not seeds:+ raise CliError("at least one seed is required")+ if len(seeds) > MAX_RUNS:+ raise CliError(f"at most {MAX_RUNS} seeds are allowed")+ if len(set(seeds)) != len(seeds):+ raise CliError("seeds must be unique")+ if any(seed < 0 for seed in seeds):+ raise CliError("seeds must be non-negative")+ return seeds+++def _validate_values(values: Any, dataset: str) -> list[float]:+ if not isinstance(values, list) or not values:+ raise CliError(f"predictions for {dataset} must be a non-empty JSON array")+ checked: list[float] = []+ for value in values:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise CliError(f"predictions for {dataset} must contain only numbers")+ number = float(value)+ if not math.isfinite(number):+ raise CliError(f"predictions for {dataset} must be finite")+ checked.append(number)+ return checked+++def normalize_prediction_mapping(+ value: Any,+ *,+ available: list[str],+ selected_dataset: str | None,+) -> tuple[dict[str, list[float]], int]:+ if not isinstance(value, dict) or not value:+ raise CliError("each prediction run must be a non-empty JSON object")+ normalized: dict[str, list[float]] = {}+ total = 0+ for query, predictions in value.items():+ if not isinstance(query, str):+ raise CliError("benchmark names in prediction objects must be strings")+ dataset = canonical_name(query, available, "benchmark")+ if selected_dataset is not None and dataset != selected_dataset:+ raise CliError(+ f"prediction object contains {dataset!r}, but --dataset selects "+ f"{selected_dataset!r}"+ )+ checked = _validate_values(predictions, dataset)+ normalized[dataset] = checked+ total += len(checked)+ if selected_dataset is not None and selected_dataset not in normalized:+ raise CliError(f"prediction object is missing {selected_dataset!r}")+ return normalized, total+++def normalize_predictions(+ payload: Any,+ *,+ mode: str,+ available: list[str],+ selected_dataset: str | None,+) -> tuple[dict[str, list[float]] | list[dict[str, list[float]]], list[int | None]]:+ """Validate the documented single-run or evaluate_many JSON shape."""++ if mode == "single":+ if isinstance(payload, dict) and "predictions" in payload:+ payload = payload["predictions"]+ mapping, total = normalize_prediction_mapping(+ payload, available=available, selected_dataset=selected_dataset+ )+ if total > MAX_PREDICTION_VALUES:+ raise CliError("prediction value limit exceeded")+ return mapping, [None]++ runs = payload.get("runs") if isinstance(payload, dict) else payload+ if not isinstance(runs, list):+ raise CliError(+ "many-run JSON must be a list or an object with a `runs` list"+ )+ if not 5 <= len(runs) <= MAX_RUNS:+ raise CliError(+ "evaluate_many requires at least five and at most "+ f"{MAX_RUNS} prediction runs"+ )++ normalized_runs: list[dict[str, list[float]]] = []+ run_seeds: list[int | None] = []+ total = 0+ for index, run in enumerate(runs):+ if not isinstance(run, dict):+ raise CliError(f"run {index} must be a JSON object")+ if "predictions" in run:+ predictions = run["predictions"]+ seed = run.get("seed")+ if seed is not None and (+ isinstance(seed, bool) or not isinstance(seed, int) or seed < 0+ ):+ raise CliError(f"run {index} seed must be a non-negative integer")+ else:+ predictions = run+ seed = None+ mapping, count = normalize_prediction_mapping(+ predictions, available=available, selected_dataset=selected_dataset+ )+ normalized_runs.append(mapping)+ run_seeds.append(seed)+ total += count+ if total > MAX_PREDICTION_VALUES:+ raise CliError("prediction value limit exceeded")++ supplied_seeds = [seed for seed in run_seeds if seed is not None]+ if supplied_seeds and len(supplied_seeds) != len(run_seeds):+ raise CliError("either provide a seed for every run or for none")+ if len(set(supplied_seeds)) != len(supplied_seeds):+ raise CliError("run seeds must be unique")+ return normalized_runs, run_seeds+++def build_plan(+ *,+ group: str,+ dataset: str | None,+ seeds: list[int],+ data_dir: Path,+ package_version: str,+ metric: str | None,+ prediction_summary: dict[str, Any] | None,+) -> dict[str, Any]:+ return {+ "action": "plan",+ "acknowledgement_required": "--execute",+ "benchmark_group": group,+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_performed": False,+ "metric_from_package_metadata": metric,+ "network_and_storage": (+ "Constructing a BenchmarkGroup downloads/extracts the group archive "+ "under data_directory if no local copy is found."+ ),+ "package": "PyTDC",+ "package_version": package_version,+ "prediction_input": prediction_summary,+ "protocol_note": (+ "TDC documents at least five independent runs for leaderboard "+ "mean/standard-deviation reporting; these seeds label the plan only."+ ),+ "seeds": seeds,+ }+++def execute_evaluation(+ *,+ group: str,+ dataset: str | None,+ mode: str,+ predictions: dict[str, list[float]] | list[dict[str, list[float]]],+ run_seeds: list[int | None],+ data_dir: Path,+ package_version: str,+) -> dict[str, Any]:+ module_name, class_name = GROUPS[group]+ group_class = getattr(importlib.import_module(module_name), class_name)+ benchmark_group = group_class(path=str(data_dir))+ if mode == "single":+ results = benchmark_group.evaluate(predictions)+ run_count = 1+ else:+ results = benchmark_group.evaluate_many(predictions)+ run_count = len(predictions)+ if isinstance(results, Exception):+ raise CliError(str(results))+ return {+ "action": "executed",+ "benchmark_group": group,+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_acknowledged": True,+ "mode": mode,+ "package": "PyTDC",+ "package_version": package_version,+ "results": results,+ "run_count": run_count,+ "run_seeds": run_seeds,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Plan a non-docking TDC BenchmarkGroup evaluation, or pass --execute "+ "with bounded JSON predictions to acknowledge group download/cache use. "+ "No dummy labels or predictions are generated."+ )+ )+ parser.add_argument(+ "--group",+ choices=tuple(GROUPS),+ default="admet_group",+ help="benchmark group (default: admet_group)",+ )+ parser.add_argument("--dataset", help="optional exact benchmark name")+ parser.add_argument(+ "--mode",+ choices=("single", "many"),+ default="many",+ help="call evaluate or evaluate_many (default: many)",+ )+ parser.add_argument(+ "--seeds",+ nargs="+",+ type=bounded_int(0, 4_294_967_295),+ default=[1, 2, 3, 4, 5],+ help="independent run seeds for the plan (default: 1 2 3 4 5)",+ )+ parser.add_argument(+ "--predictions",+ help=(+ "bounded JSON input. Single mode: {dataset: [values]}. Many mode: "+ "[{dataset: [values]}, ...] or {runs: [{seed, predictions}, ...]}"+ ),+ )+ parser.add_argument(+ "--data-dir",+ default=".pytdc-benchmarks",+ help="relative benchmark cache directory (default: .pytdc-benchmarks)",+ )+ parser.add_argument(+ "--execute",+ action="store_true",+ help="acknowledge network/storage use and evaluate supplied predictions",+ )+ parser.add_argument("--output", help="write JSON to a relative workspace path")+ parser.add_argument(+ "--force", action="store_true", help="replace an existing --output file"+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ if args.execute and not args.predictions:+ parser.error("--execute requires --predictions")++ try:+ seeds = validate_seeds(args.seeds)+ metadata, package_version = load_pytdc_metadata()+ group = canonical_name(args.group, GROUPS, "benchmark group")+ registry_group = canonical_name(+ group, metadata.benchmark_names, "package benchmark group"+ )+ available = benchmark_names(metadata, registry_group)+ dataset = (+ canonical_name(args.dataset, available, "benchmark")+ if args.dataset+ else None+ )+ metric = (+ metadata.bm_metric_names.get(registry_group, {}).get(dataset)+ if dataset+ else None+ )+ data_dir = safe_directory(+ args.data_dir,+ label="benchmark data directory",+ create=args.execute,+ )++ normalized: (+ dict[str, list[float]] | list[dict[str, list[float]]] | None+ ) = None+ run_seeds: list[int | None] = []+ prediction_summary: dict[str, Any] | None = None+ if args.predictions:+ prediction_path = safe_input_file(+ args.predictions,+ max_bytes=MAX_PREDICTION_FILE_BYTES,+ label="prediction input",+ )+ payload = read_json_file(prediction_path)+ normalized, run_seeds = normalize_predictions(+ payload,+ mode=args.mode,+ available=available,+ selected_dataset=dataset,+ )+ prediction_summary = {+ "mode": args.mode,+ "path": str(prediction_path),+ "run_count": 1 if args.mode == "single" else len(normalized),+ "validated": True,+ }++ if args.execute:+ if normalized is None:+ raise CliError("--execute requires validated predictions")+ result = execute_evaluation(+ group=group,+ dataset=dataset,+ mode=args.mode,+ predictions=normalized,+ run_seeds=run_seeds,+ data_dir=data_dir,+ package_version=package_version,+ )+ else:+ result = build_plan(+ group=group,+ dataset=dataset,+ seeds=seeds,+ data_dir=data_dir,+ package_version=package_version,+ metric=metric,+ prediction_summary=prediction_summary,+ )+ emit_json(result, args.output, force=args.force)+ except (CliError, ImportError, OSError, TypeError, ValueError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ return 0if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pytdc/scripts/cache_audit.py b/skills/pytdc/scripts/cache_audit.pynew file mode 100644index 00000000..4271ae73--- /dev/null+++ b/skills/pytdc/scripts/cache_audit.py@@ -0,0 +1,146 @@+#!/usr/bin/env python3+"""Create a bounded, read-only manifest of a local PyTDC data directory."""++from __future__ import annotations++import argparse+import heapq+import os+import sys+from collections import Counter+from pathlib import Path+from typing import Any++from _common import CliError, bounded_int, emit_json, safe_directory+++def audit_cache(root: Path, *, max_files: int, largest_limit: int) -> dict[str, Any]:+ """Inspect regular files without following symbolic links."""++ extension_counts: Counter[str] = Counter()+ largest: list[tuple[int, str]] = []+ errors: list[str] = []+ file_count = 0+ directory_count = 0+ symlink_count = 0+ total_bytes = 0+ scan_complete = True++ def on_error(error: OSError) -> None:+ nonlocal scan_complete+ scan_complete = False+ if len(errors) < 20:+ errors.append(str(error))++ for current, directories, files in os.walk(+ root, topdown=True, followlinks=False, onerror=on_error+ ):+ directory_count += 1+ current_path = Path(current)+ kept_directories: list[str] = []+ for name in sorted(directories):+ candidate = current_path / name+ if candidate.is_symlink():+ symlink_count += 1+ else:+ kept_directories.append(name)+ directories[:] = kept_directories++ for name in sorted(files):+ candidate = current_path / name+ if candidate.is_symlink():+ symlink_count += 1+ continue+ if file_count >= max_files:+ scan_complete = False+ break+ try:+ stat = candidate.stat(follow_symlinks=False)+ except OSError as exc:+ on_error(exc)+ continue+ if not candidate.is_file():+ continue++ relative = candidate.relative_to(root).as_posix()+ size = stat.st_size+ file_count += 1+ total_bytes += size+ extension_counts[candidate.suffix.lower() or "<none>"] += 1+ item = (size, relative)+ if largest_limit == 0:+ continue+ if len(largest) < largest_limit:+ heapq.heappush(largest, item)+ elif item > largest[0]:+ heapq.heapreplace(largest, item)+ if file_count >= max_files:+ break++ return {+ "cache_directory": str(root),+ "directory_count": directory_count,+ "download_performed": False,+ "errors": errors,+ "extension_counts": dict(sorted(extension_counts.items())),+ "file_count": file_count,+ "largest_files": [+ {"bytes": size, "path": relative}+ for size, relative in sorted(largest, reverse=True)+ ],+ "max_files": max_files,+ "scan_complete": scan_complete,+ "symlink_count_skipped": symlink_count,+ "total_bytes": total_bytes,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Audit an existing PyTDC data/oracle directory without network access. "+ "Symbolic links are skipped and output is bounded."+ )+ )+ parser.add_argument(+ "--cache-dir",+ default="data",+ help="existing relative directory to inspect (default: data)",+ )+ parser.add_argument(+ "--max-files",+ type=bounded_int(1, 1_000_000),+ default=100_000,+ help="stop after this many files (default: 100000)",+ )+ parser.add_argument(+ "--largest",+ type=bounded_int(0, 100),+ default=20,+ help="include at most this many largest files (default: 20)",+ )+ parser.add_argument("--output", help="write JSON to a relative workspace path")+ parser.add_argument(+ "--force", action="store_true", help="replace an existing --output file"+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ root = safe_directory(+ args.cache_dir, label="cache directory", must_exist=True+ )+ result = audit_cache(+ root, max_files=args.max_files, largest_limit=args.largest+ )+ emit_json(result, args.output, force=args.force)+ except (CliError, OSError, ValueError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pytdc/scripts/discover_metadata.py b/skills/pytdc/scripts/discover_metadata.pynew file mode 100644index 00000000..3d9afb38--- /dev/null+++ b/skills/pytdc/scripts/discover_metadata.py@@ -0,0 +1,174 @@+#!/usr/bin/env python3+"""Discover PyTDC registries without constructing loaders or downloading data."""++from __future__ import annotations++import argparse+import sys+from typing import Any, Iterable++from _common import (+ CliError,+ bounded_int,+ canonical_name,+ emit_json,+ load_pytdc_metadata,+)+++def _window(values: Iterable[Any], offset: int, limit: int) -> dict[str, Any]:+ items = list(values)+ selected = items[offset : offset + limit]+ return {+ "items": selected,+ "limit": limit,+ "offset": offset,+ "returned": len(selected),+ "total": len(items),+ "truncated": offset + len(selected) < len(items),+ }+++def collect_metadata(+ metadata: Any,+ package_version: str,+ *,+ kind: str,+ task: str | None,+ offset: int,+ limit: int,+) -> dict[str, Any]:+ """Collect a bounded view of the installed metadata registries."""++ dataset_registry = dict(metadata.dataset_names)+ if task is not None:+ task = canonical_name(task, dataset_registry, "task")++ sections: dict[str, Any] = {}+ requested = (+ ["tasks", "datasets", "benchmarks", "evaluators", "oracles"]+ if kind == "all"+ else [kind]+ )++ if "tasks" in requested:+ sections["tasks"] = _window(+ (+ {"task": name, "dataset_count": len(names)}+ for name, names in dataset_registry.items()+ ),+ offset,+ limit,+ )++ if "datasets" in requested:+ if task is not None:+ values = (+ {"task": task, "dataset": name}+ for name in dataset_registry[task]+ )+ else:+ values = (+ {"task": task_name, "dataset": dataset_name}+ for task_name, names in dataset_registry.items()+ for dataset_name in names+ )+ sections["datasets"] = _window(values, offset, limit)++ if "benchmarks" in requested:+ values = (+ {+ "group": group_name,+ "task": task_name,+ "benchmark": benchmark_name,+ }+ for group_name, task_map in metadata.benchmark_names.items()+ for task_name, names in task_map.items()+ for benchmark_name in names+ )+ sections["benchmarks"] = _window(values, offset, limit)++ if "evaluators" in requested:+ sections["evaluators"] = _window(+ ({"name": name} for name in dict.fromkeys(metadata.evaluator_name)),+ offset,+ limit,+ )++ if "oracles" in requested:+ sections["oracles"] = _window(+ ({"name": name} for name in dict.fromkeys(metadata.oracle_names)),+ offset,+ limit,+ )++ return {+ "download_performed": False,+ "kind": kind,+ "package": "PyTDC",+ "package_version": package_version,+ "source": "installed tdc.metadata registry",+ "task_filter": task,+ **sections,+ }+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Read task, dataset, benchmark, evaluator, and oracle names from the "+ "installed PyTDC metadata module. This command never instantiates a "+ "loader or downloads a dataset/model."+ )+ )+ parser.add_argument(+ "--kind",+ choices=("tasks", "datasets", "benchmarks", "evaluators", "oracles", "all"),+ default="tasks",+ help="registry to show (default: tasks)",+ )+ parser.add_argument("--task", help="exact task filter for --kind datasets")+ parser.add_argument(+ "--offset",+ type=bounded_int(0, 1_000_000),+ default=0,+ help="skip this many registry entries (default: 0)",+ )+ parser.add_argument(+ "--limit",+ type=bounded_int(1, 500),+ default=50,+ help="maximum entries returned per section (default: 50; max: 500)",+ )+ parser.add_argument("--output", help="write JSON to a relative workspace path")+ parser.add_argument(+ "--force", action="store_true", help="replace an existing --output file"+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ parser = build_parser()+ args = parser.parse_args(argv)+ if args.task and args.kind not in {"datasets", "all"}:+ parser.error("--task is only valid with --kind datasets or --kind all")++ try:+ metadata, package_version = load_pytdc_metadata()+ result = collect_metadata(+ metadata,+ package_version,+ kind=args.kind,+ task=args.task,+ offset=args.offset,+ limit=args.limit,+ )+ emit_json(result, args.output, force=args.force)+ except (CliError, OSError, TypeError, ValueError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/skills/pytdc/scripts/load_and_split_data.py b/skills/pytdc/scripts/load_and_split_data.pyindex 50238c75..c790faaf 100644--- a/skills/pytdc/scripts/load_and_split_data.py+++ b/skills/pytdc/scripts/load_and_split_data.py@@ -1,214 +1,374 @@#!/usr/bin/env python3-"""-TDC Data Loading and Splitting Template--This script demonstrates how to load TDC datasets and apply different-splitting strategies for model training and evaluation.--Usage:- python load_and_split_data.py-"""--from tdc.single_pred import ADME-from tdc.multi_pred import DTI-from tdc import Evaluator-import pandas as pd---def load_single_pred_example():- """- Example: Loading and splitting a single-prediction dataset (ADME)- """- print("=" * 60)- print("Example 1: Single-Prediction Task (ADME)")- print("=" * 60)-- # Load Caco2 dataset (intestinal permeability)- print("\nLoading Caco2_Wang dataset...")- data = ADME(name='Caco2_Wang')-- # Get basic dataset info- print(f"\nDataset size: {len(data.get_data())} molecules")- data.print_stats()-- # Method 1: Scaffold split (default, recommended)- print("\n--- Scaffold Split ---")- split = data.get_split(method='scaffold', seed=42, frac=[0.7, 0.1, 0.2])-- train = split['train']- valid = split['valid']- test = split['test']-- print(f"Train: {len(train)} molecules")- print(f"Valid: {len(valid)} molecules")- print(f"Test: {len(test)} molecules")-- # Display sample data- print("\nSample training data:")- print(train.head(3))-- # Method 2: Random split- print("\n--- Random Split ---")- split_random = data.get_split(method='random', seed=42, frac=[0.8, 0.1, 0.1])- print(f"Train: {len(split_random['train'])} molecules")- print(f"Valid: {len(split_random['valid'])} molecules")- print(f"Test: {len(split_random['test'])} molecules")-- return split---def load_multi_pred_example():- """- Example: Loading and splitting a multi-prediction dataset (DTI)- """- print("\n" + "=" * 60)- print("Example 2: Multi-Prediction Task (DTI)")- print("=" * 60)-- # Load BindingDB Kd dataset (drug-target interactions)- print("\nLoading BindingDB_Kd dataset...")- data = DTI(name='BindingDB_Kd')-- # Get basic dataset info- full_data = data.get_data()- print(f"\nDataset size: {len(full_data)} drug-target pairs")- print(f"Unique drugs: {full_data['Drug_ID'].nunique()}")- print(f"Unique targets: {full_data['Target_ID'].nunique()}")-- # Method 1: Random split- print("\n--- Random Split ---")- split_random = data.get_split(method='random', seed=42)- print(f"Train: {len(split_random['train'])} pairs")- print(f"Valid: {len(split_random['valid'])} pairs")- print(f"Test: {len(split_random['test'])} pairs")-- # Method 2: Cold drug split (unseen drugs in test)- print("\n--- Cold Drug Split ---")- split_cold_drug = data.get_split(method='cold_drug', seed=42)-- train = split_cold_drug['train']- test = split_cold_drug['test']-- # Verify no drug overlap- train_drugs = set(train['Drug_ID'])- test_drugs = set(test['Drug_ID'])- overlap = train_drugs & test_drugs-- print(f"Train: {len(train)} pairs, {len(train_drugs)} unique drugs")- print(f"Test: {len(test)} pairs, {len(test_drugs)} unique drugs")- print(f"Drug overlap: {len(overlap)} (should be 0)")-- # Method 3: Cold target split (unseen targets in test)- print("\n--- Cold Target Split ---")- split_cold_target = data.get_split(method='cold_target', seed=42)-- train = split_cold_target['train']- test = split_cold_target['test']-- train_targets = set(train['Target_ID'])- test_targets = set(test['Target_ID'])- overlap = train_targets & test_targets-- print(f"Train: {len(train)} pairs, {len(train_targets)} unique targets")- print(f"Test: {len(test)} pairs, {len(test_targets)} unique targets")- print(f"Target overlap: {len(overlap)} (should be 0)")-- # Display sample data- print("\nSample DTI data:")- print(full_data.head(3))-- return split_cold_drug---def evaluation_example(split):- """- Example: Evaluating model predictions with TDC evaluators- """- print("\n" + "=" * 60)- print("Example 3: Model Evaluation")- print("=" * 60)-- test = split['test']-- # For demonstration, create dummy predictions- # In practice, replace with your model's predictions- import numpy as np- np.random.seed(42)-- # Simulate predictions (replace with model.predict(test['Drug']))- y_true = test['Y'].values- y_pred = y_true + np.random.normal(0, 0.5, len(y_true)) # Add noise-- # Evaluate with different metrics- print("\nEvaluating predictions...")-- # Regression metrics- mae_evaluator = Evaluator(name='MAE')- mae = mae_evaluator(y_true, y_pred)- print(f"MAE: {mae:.4f}")-- rmse_evaluator = Evaluator(name='RMSE')- rmse = rmse_evaluator(y_true, y_pred)- print(f"RMSE: {rmse:.4f}")-- r2_evaluator = Evaluator(name='R2')- r2 = r2_evaluator(y_true, y_pred)- print(f"R²: {r2:.4f}")-- spearman_evaluator = Evaluator(name='Spearman')- spearman = spearman_evaluator(y_true, y_pred)- print(f"Spearman: {spearman:.4f}")---def custom_split_example():- """- Example: Creating custom splits with different fractions- """- print("\n" + "=" * 60)- print("Example 4: Custom Split Fractions")- print("=" * 60)-- data = ADME(name='HIA_Hou')-- # Custom split fractions- custom_fracs = [- ([0.6, 0.2, 0.2], "60/20/20 split"),- ([0.8, 0.1, 0.1], "80/10/10 split"),- ([0.7, 0.15, 0.15], "70/15/15 split")- ]-- for frac, description in custom_fracs:- split = data.get_split(method='scaffold', seed=42, frac=frac)- print(f"\n{description}:")- print(f" Train: {len(split['train'])} ({frac[0]*100:.0f}%)")- print(f" Valid: {len(split['valid'])} ({frac[1]*100:.0f}%)")- print(f" Test: {len(split['test'])} ({frac[2]*100:.0f}%)")---def main():- """- Main function to run all examples- """- print("\n" + "=" * 60)- print("TDC Data Loading and Splitting Examples")- print("=" * 60)-- # Example 1: Single prediction with scaffold split- split = load_single_pred_example()-- # Example 2: Multi prediction with cold splits- dti_split = load_multi_pred_example()-- # Example 3: Model evaluation- evaluation_example(split)-- # Example 4: Custom split fractions- custom_split_example()-- print("\n" + "=" * 60)- print("Examples completed!")- print("=" * 60)+"""Plan or explicitly execute one bounded PyTDC dataset split."""++from __future__ import annotations++import argparse+import importlib+import itertools+import sys+from pathlib import Path+from typing import Any++from _common import (+ CliError,+ bounded_int,+ canonical_name,+ emit_json,+ load_pytdc_metadata,+ safe_directory,+ truncate_value,+ validate_fractions,+)+++# Public imports verified against the PyTDC 1.1.15 source distribution.+TASKS: dict[str, tuple[str, str, str]] = {+ "ADME": ("tdc.single_pred", "ADME", "ADME"),+ "CRISPROutcome": ("tdc.single_pred", "CRISPROutcome", "CRISPROutcome"),+ "Develop": ("tdc.single_pred", "Develop", "Develop"),+ "Epitope": ("tdc.single_pred", "Epitope", "Epitope"),+ "HTS": ("tdc.single_pred", "HTS", "HTS"),+ "Paratope": ("tdc.single_pred", "Paratope", "Paratope"),+ "QM": ("tdc.single_pred", "QM", "QM"),+ "Tox": ("tdc.single_pred", "Tox", "Tox"),+ "Yields": ("tdc.single_pred", "Yields", "Yields"),+ "AntibodyAff": ("tdc.multi_pred", "AntibodyAff", "AntibodyAff"),+ "Catalyst": ("tdc.multi_pred", "Catalyst", "Catalyst"),+ "DDI": ("tdc.multi_pred", "DDI", "DDI"),+ "DrugRes": ("tdc.multi_pred", "DrugRes", "DrugRes"),+ "DrugSyn": ("tdc.multi_pred", "DrugSyn", "DrugSyn"),+ "DTI": ("tdc.multi_pred", "DTI", "DTI"),+ "GDA": ("tdc.multi_pred", "GDA", "GDA"),+ "MTI": ("tdc.multi_pred", "MTI", "MTI"),+ "PeptideMHC": ("tdc.multi_pred", "PeptideMHC", "PeptideMHC"),+ "PPI": ("tdc.multi_pred", "PPI", "PPI"),+ "ProteinPeptide": ("tdc.multi_pred", "ProteinPeptide", "ProteinPeptide"),+ "TCREpitopeBinding": (+ "tdc.multi_pred",+ "TCREpitopeBinding",+ "TCREpitopeBinding",+ ),+ "TrialOutcome": ("tdc.multi_pred", "TrialOutcome", "TrialOutcome"),+ "MolGen": ("tdc.generation", "MolGen", "MolGen"),+ "Reaction": ("tdc.generation", "Reaction", "Reaction"),+ "RetroSyn": ("tdc.generation", "RetroSyn", "RetroSyn"),+}++SPLIT_METHODS = ("random", "scaffold", "cold_split", "combination", "time")+++def normalize_columns(values: list[str] | None) -> list[str]:+ columns: list[str] = []+ for value in values or []:+ columns.extend(part.strip() for part in value.split(",") if part.strip())+ columns = list(dict.fromkeys(columns))+ if len(columns) > 8:+ raise CliError("at most eight cold-split columns may be specified")+ return columns+++def validate_request(+ *,+ task_query: str,+ dataset_query: str,+ method: str,+ columns: list[str],+ time_column: str | None,+ metadata: Any,+) -> tuple[str, str]:+ """Resolve exact registry names and reject unsupported split combinations."""++ task = canonical_name(task_query, TASKS, "task")+ module_name, _, registry_key = TASKS[task]+ registry_key = canonical_name(registry_key, metadata.dataset_names, "task registry")+ dataset = canonical_name(+ dataset_query, metadata.dataset_names[registry_key], f"{task} dataset"+ )++ if method == "scaffold" and task not in {"ADME", "Tox", "HTS"}:+ raise CliError(+ "the official generic scaffold-split documentation limits this method "+ "to the molecule-based ADME, Tox, and HTS single-instance tasks"+ )+ if method == "cold_split":+ if module_name != "tdc.multi_pred":+ raise CliError("cold_split is only exposed by multi-instance loaders")+ if not columns:+ raise CliError("cold_split requires one or more --column values")+ elif columns:+ raise CliError("--column is only valid with --method cold_split")++ if method == "combination" and task != "DrugSyn":+ raise CliError(+ "the built-in combination split is documented for DrugSyn combination data"+ )++ if method == "time":+ if not (+ task == "DTI"+ and dataset.casefold() == "bindingdb_patent"+ and time_column+ ):+ raise CliError(+ "the verified built-in temporal case is DTI/BindingDB_Patent and "+ "requires --time-column (normally Year)"+ )+ elif time_column:+ raise CliError("--time-column is only valid with --method time")++ if module_name == "tdc.generation" and method != "random":+ raise CliError("the verified MolGen/Reaction/RetroSyn loaders expose random split")+ return task, dataset+++def build_plan(+ *,+ task: str,+ dataset: str,+ method: str,+ seed: int,+ fractions: tuple[float, float, float],+ columns: list[str],+ time_column: str | None,+ data_dir: Path,+ package_version: str,+) -> dict[str, Any]:+ return {+ "action": "plan",+ "acknowledgement_required": "--execute",+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_performed": False,+ "network_and_storage": (+ "Constructing the loader may contact TDC/Harvard Dataverse and write "+ "the complete dataset under data_directory."+ ),+ "package": "PyTDC",+ "package_version": package_version,+ "split": {+ "cold_columns": columns,+ "fractions": list(fractions),+ "method": method,+ "seed": seed,+ "time_column": time_column,+ },+ "task": task,+ }+++def _summarize_frame(frame: Any, preview: int) -> dict[str, Any]:+ summary: dict[str, Any] = {"rows": len(frame)}+ if hasattr(frame, "columns"):+ summary["columns"] = [str(column) for column in list(frame.columns)[:100]]+ if preview and hasattr(frame, "head") and hasattr(frame, "to_dict"):+ records = frame.head(preview).to_dict(orient="records")+ summary["preview"] = truncate_value(records)+ return summary+++def _audit_cold_columns(+ split: dict[str, Any], columns: list[str]+) -> dict[str, Any]:+ """Report exact-value overlap; this is not a general leakage proof."""++ audit: dict[str, Any] = {}+ partitions = ("train", "valid", "test")+ for column in columns:+ missing = [+ name+ for name in partitions+ if not hasattr(split[name], "columns") or column not in split[name].columns+ ]+ if missing:+ audit[column] = {"missing_from": missing}+ continue+ values = {+ name: set(str(value) for value in split[name][column].dropna().unique())+ for name in partitions+ }+ audit[column] = {+ "distinct_values": {name: len(items) for name, items in values.items()},+ "pairwise_overlap_counts": {+ f"{left}:{right}": len(values[left] & values[right])+ for left, right in itertools.combinations(partitions, 2)+ },+ }+ return audit+++def execute_split(+ *,+ task: str,+ dataset: str,+ method: str,+ seed: int,+ fractions: tuple[float, float, float],+ columns: list[str],+ time_column: str | None,+ data_dir: Path,+ preview: int,+ package_version: str,+) -> dict[str, Any]:+ """Instantiate a loader only after the caller acknowledges the download."""++ module_name, class_name, _ = TASKS[task]+ task_class = getattr(importlib.import_module(module_name), class_name)+ loader = task_class(name=dataset, path=str(data_dir))++ split_kwargs: dict[str, Any] = {+ "method": method,+ "seed": seed,+ "frac": list(fractions),+ }+ if method == "cold_split":+ split_kwargs["column_name"] = columns+ if method == "time":+ split_kwargs["time_column"] = time_column+ split = loader.get_split(**split_kwargs)++ expected = {"train", "valid", "test"}+ if not isinstance(split, dict) or not expected.issubset(split):+ raise CliError("PyTDC returned an unexpected split structure")++ result: dict[str, Any] = {+ "action": "executed",+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_acknowledged": True,+ "package": "PyTDC",+ "package_version": package_version,+ "partitions": {+ name: _summarize_frame(split[name], preview)+ for name in ("train", "valid", "test")+ },+ "split": {+ "cold_columns": columns,+ "fractions": list(fractions),+ "method": method,+ "seed": seed,+ "time_column": time_column,+ },+ "task": task,+ }+ if method == "cold_split":+ result["cold_column_audit"] = _audit_cold_columns(split, columns)+ result["cold_column_audit_note"] = (+ "Counts cover exact values in requested columns only; zero overlap is "+ "not a blanket claim that all biological or chemical leakage is absent."+ )+ return result+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Validate and plan a PyTDC dataset split. The default is download-free; "+ "pass --execute to acknowledge that loader construction may download "+ "and cache the full dataset."+ )+ )+ parser.add_argument("--task", required=True, help="exact public PyTDC task class")+ parser.add_argument("--dataset", required=True, help="exact package-registry name")+ parser.add_argument(+ "--method",+ choices=SPLIT_METHODS,+ default="random",+ help="split method (default: random)",+ )+ parser.add_argument(+ "--column",+ action="append",+ help="cold-split column; repeat or pass comma-separated values",+ )+ parser.add_argument("--time-column", help="time column for --method time")+ parser.add_argument(+ "--frac",+ nargs=3,+ type=float,+ metavar=("TRAIN", "VALID", "TEST"),+ default=(0.7, 0.1, 0.2),+ help="split fractions summing to 1 (default: 0.7 0.1 0.2)",+ )+ parser.add_argument(+ "--seed",+ type=bounded_int(0, 4_294_967_295),+ default=42,+ help="non-negative split seed (default: 42)",+ )+ parser.add_argument(+ "--data-dir",+ default=".pytdc-data",+ help="relative cache directory (default: .pytdc-data)",+ )+ parser.add_argument(+ "--preview",+ type=bounded_int(0, 10),+ default=0,+ help="include at most this many bounded rows per partition (default: 0)",+ )+ parser.add_argument(+ "--execute",+ action="store_true",+ help="acknowledge network/storage use and construct the loader",+ )+ parser.add_argument("--output", help="write JSON to a relative workspace path")+ parser.add_argument(+ "--force", action="store_true", help="replace an existing --output file"+ )+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ fractions = validate_fractions(args.frac)+ columns = normalize_columns(args.column)+ metadata, package_version = load_pytdc_metadata()+ task, dataset = validate_request(+ task_query=args.task,+ dataset_query=args.dataset,+ method=args.method,+ columns=columns,+ time_column=args.time_column,+ metadata=metadata,+ )+ data_dir = safe_directory(+ args.data_dir,+ label="data directory",+ create=args.execute,+ )+ if args.execute:+ result = execute_split(+ task=task,+ dataset=dataset,+ method=args.method,+ seed=args.seed,+ fractions=fractions,+ columns=columns,+ time_column=args.time_column,+ data_dir=data_dir,+ preview=args.preview,+ package_version=package_version,+ )+ else:+ result = build_plan(+ task=task,+ dataset=dataset,+ method=args.method,+ seed=args.seed,+ fractions=fractions,+ columns=columns,+ time_column=args.time_column,+ data_dir=data_dir,+ package_version=package_version,+ )+ emit_json(result, args.output, force=args.force)+ except (CliError, ImportError, OSError, TypeError, ValueError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ return 0if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pytdc/scripts/molecular_generation.py b/skills/pytdc/scripts/molecular_generation.pyindex 7392f45b..1fce35b4 100644--- a/skills/pytdc/scripts/molecular_generation.py+++ b/skills/pytdc/scripts/molecular_generation.py@@ -1,404 +1,417 @@#!/usr/bin/env python3-"""-TDC Molecular Generation with Oracles Template--This script demonstrates how to use TDC oracles for molecular generation-tasks including goal-directed generation and distribution learning.--Usage:- python molecular_generation.py-"""--from tdc.generation import MolGen-from tdc import Oracle-import numpy as np---def load_generation_dataset():- """- Load molecular generation dataset- """- print("=" * 60)- print("Loading Molecular Generation Dataset")- print("=" * 60)-- # Load ChEMBL dataset- data = MolGen(name='ChEMBL_V29')-- # Get training molecules- split = data.get_split()- train_smiles = split['train']['Drug'].tolist()-- print(f"\nDataset: ChEMBL_V29")- print(f"Training molecules: {len(train_smiles)}")-- # Display sample molecules- print("\nSample SMILES:")- for i, smiles in enumerate(train_smiles[:5], 1):- print(f" {i}. {smiles}")-- return train_smiles---def single_oracle_example():- """- Example: Using a single oracle for molecular evaluation- """- print("\n" + "=" * 60)- print("Example 1: Single Oracle Evaluation")- print("=" * 60)-- # Initialize oracle for GSK3B target- oracle = Oracle(name='GSK3B')-- # Test molecules- test_molecules = [- 'CC(C)Cc1ccc(cc1)C(C)C(O)=O', # Ibuprofen- 'CC(=O)Oc1ccccc1C(=O)O', # Aspirin- 'Cn1c(=O)c2c(ncn2C)n(C)c1=O', # Caffeine- 'CN1C=NC2=C1C(=O)N(C(=O)N2C)C' # Theophylline- ]-- print("\nEvaluating molecules with GSK3B oracle:")- print("-" * 60)-- for smiles in test_molecules:- score = oracle(smiles)- print(f"SMILES: {smiles}")- print(f"GSK3B score: {score:.4f}\n")---def multiple_oracles_example():- """- Example: Using multiple oracles for multi-objective optimization- """- print("\n" + "=" * 60)- print("Example 2: Multiple Oracles (Multi-Objective)")- print("=" * 60)-- # Initialize multiple oracles- oracles = {- 'QED': Oracle(name='QED'), # Drug-likeness- 'SA': Oracle(name='SA'), # Synthetic accessibility- 'GSK3B': Oracle(name='GSK3B'), # Target binding- 'LogP': Oracle(name='LogP') # Lipophilicity+"""Safely plan PyTDC molecule data access or bounded oracle scoring."""++from __future__ import annotations++import argparse+import contextlib+import os+import sys+from pathlib import Path+from typing import Any, Iterator++from _common import (+ CliError,+ bounded_int,+ canonical_name,+ emit_json,+ load_pytdc_metadata,+ safe_directory,+ safe_input_file,+ truncate_value,+ validate_fractions,+)+++LOCAL_SCALAR_ORACLES = {"qed"}+# LogP and SA are listed as "trivial" upstream, but their 1.1.15 implementation+# lazily downloads the fpscores artifact through calculateScore().+CHECKPOINT_ORACLES = {+ "logp",+ "sa",+ "drd2",+ "gsk3b",+ "jnk3",+ "cyp3a4_veith",+}+MAX_SMILES_FILE_BYTES = 1 * 1024 * 1024+++def _working_directory(path: Path) -> Iterator[None]:+ original = Path.cwd()+ os.chdir(path)+ try:+ yield+ finally:+ os.chdir(original)+++def classify_oracle(metadata: Any, query: str) -> tuple[str, str]:+ name = canonical_name(query, metadata.oracle_names, "oracle")+ if name in LOCAL_SCALAR_ORACLES:+ return name, "local_scalar"+ if name in CHECKPOINT_ORACLES:+ return name, "checkpoint_download"+ if name in set(metadata.download_oracle_names):+ return name, "unsupported_checkpoint"+ if name in set(metadata.distribution_oracles):+ return name, "distribution_metric"+ if name in set(metadata.download_receptor_oracle_name):+ return name, "receptor_or_docking"+ if name in set(metadata.synthetic_oracle_name):+ return name, "remote_service"+ return name, "specialized_or_composite"+++def load_smiles(+ direct: list[str] | None,+ input_path: str | None,+ *,+ max_molecules: int,+) -> list[str]:+ values = list(direct or [])+ if input_path:+ path = safe_input_file(+ input_path,+ max_bytes=MAX_SMILES_FILE_BYTES,+ label="SMILES input",+ )+ with path.open("r", encoding="utf-8") as handle:+ values.extend(line.strip() for line in handle if line.strip())+ if not values:+ raise CliError("provide at least one --smiles or --input line")+ if len(values) > max_molecules:+ raise CliError(+ f"received {len(values)} molecules; --max-molecules is {max_molecules}"+ )+ if any(len(value) > 4096 for value in values):+ raise CliError("each SMILES string is limited to 4096 characters")+ return values+++def score_plan(+ *,+ oracle: str,+ category: str,+ smiles_count: int,+ runtime_dir: Path,+ package_version: str,+ download_acknowledged: bool,+) -> dict[str, Any]:+ return {+ "action": "plan",+ "acknowledgement_required": (+ "--execute"+ if category == "local_scalar"+ else "--execute --download (only supported checkpoint oracles)"+ ),+ "download_acknowledged": download_acknowledged,+ "download_performed": False,+ "oracle": oracle,+ "oracle_category": category,+ "package": "PyTDC",+ "package_version": package_version,+ "runtime_directory": str(runtime_dir),+ "score_direction": "not assumed; consult the exact oracle documentation",+ "smiles_count": smiles_count,}- # Test molecule- test_smiles = 'CC(C)Cc1ccc(cc1)C(C)C(O)=O'- print(f"\nEvaluating: {test_smiles}")- print("-" * 60)-- scores = {}- for name, oracle in oracles.items():- score = oracle(test_smiles)- scores[name] = score- print(f"{name:10s}: {score:.4f}")-- # Multi-objective score (weighted combination)- print("\n--- Multi-Objective Scoring ---")-- # Invert SA (lower is better, so we invert for maximization)- sa_score = 1.0 / (1.0 + scores['SA'])-- # Weighted combination- weights = {'QED': 0.3, 'SA': 0.2, 'GSK3B': 0.4, 'LogP': 0.1}- multi_score = (- weights['QED'] * scores['QED'] +- weights['SA'] * sa_score +- weights['GSK3B'] * scores['GSK3B'] +- weights['LogP'] * (scores['LogP'] / 5.0) # Normalize LogP- )-- print(f"Multi-objective score: {multi_score:.4f}")- print(f"Weights: {weights}")---def batch_evaluation_example():- """- Example: Batch evaluation of multiple molecules- """- print("\n" + "=" * 60)- print("Example 3: Batch Evaluation")- print("=" * 60)-- # Generate sample molecules- molecules = [- 'CC(C)Cc1ccc(cc1)C(C)C(O)=O',- 'CC(=O)Oc1ccccc1C(=O)O',- 'Cn1c(=O)c2c(ncn2C)n(C)c1=O',- 'CN1C=NC2=C1C(=O)N(C(=O)N2C)C',- 'CC(C)NCC(COc1ccc(cc1)COCCOC(C)C)O'- ]-- # Initialize oracle- oracle = Oracle(name='DRD2')-- print(f"\nBatch evaluating {len(molecules)} molecules with DRD2 oracle...")-- # Batch evaluation (more efficient than individual calls)- scores = oracle(molecules)-- print("\nResults:")- print("-" * 60)- for smiles, score in zip(molecules, scores):- print(f"{smiles[:40]:40s}... Score: {score:.4f}")-- # Statistics- print(f"\nStatistics:")- print(f" Mean score: {np.mean(scores):.4f}")- print(f" Std score: {np.std(scores):.4f}")- print(f" Min score: {np.min(scores):.4f}")- print(f" Max score: {np.max(scores):.4f}")---def goal_directed_generation_template():- """- Template for goal-directed molecular generation- """- print("\n" + "=" * 60)- print("Example 4: Goal-Directed Generation Template")- print("=" * 60)-- template = '''-# Template for goal-directed molecular generation--from tdc.generation import MolGen-from tdc import Oracle-import numpy as np--# 1. Load training data-data = MolGen(name='ChEMBL_V29')-train_smiles = data.get_split()['train']['Drug'].tolist()--# 2. Initialize oracle(s)-oracle = Oracle(name='GSK3B')--# 3. Initialize your generative model-# model = YourGenerativeModel()-# model.fit(train_smiles)--# 4. Generation loop-num_iterations = 100-num_molecules_per_iter = 100-best_molecules = []--for iteration in range(num_iterations):- # Generate candidate molecules- # candidates = model.generate(num_molecules_per_iter)-- # Evaluate with oracle- scores = oracle(candidates)-- # Select top molecules- top_indices = np.argsort(scores)[-10:]- top_molecules = [candidates[i] for i in top_indices]- top_scores = [scores[i] for i in top_indices]-- # Store best molecules- best_molecules.extend(zip(top_molecules, top_scores))-- # Optional: Fine-tune model on top molecules- # model.fine_tune(top_molecules)-- # Print progress- print(f"Iteration {iteration}: Best score = {max(scores):.4f}")--# Sort and display top molecules-best_molecules.sort(key=lambda x: x[1], reverse=True)-print("\\nTop 10 molecules:")-for smiles, score in best_molecules[:10]:- print(f"{smiles}: {score:.4f}")-'''-- print("\nGoal-Directed Generation Template:")- print("=" * 60)- print(template)---def distribution_learning_example(train_smiles):- """- Example: Distribution learning evaluation- """- print("\n" + "=" * 60)- print("Example 5: Distribution Learning")- print("=" * 60)-- # Use subset for demonstration- train_subset = train_smiles[:1000]-- # Initialize oracle- oracle = Oracle(name='QED')-- print("\nEvaluating property distribution...")-- # Evaluate training set- print("Computing training set distribution...")- train_scores = oracle(train_subset)-- # Simulate generated molecules (in practice, use your generative model)- # For demo: add noise to training molecules- print("Computing generated set distribution...")- generated_scores = train_scores + np.random.normal(0, 0.1, len(train_scores))- generated_scores = np.clip(generated_scores, 0, 1) # QED is [0, 1]-- # Compare distributions- print("\n--- Distribution Statistics ---")- print(f"Training set (n={len(train_subset)}):")- print(f" Mean: {np.mean(train_scores):.4f}")- print(f" Std: {np.std(train_scores):.4f}")- print(f" Median: {np.median(train_scores):.4f}")-- print(f"\nGenerated set (n={len(generated_scores)}):")- print(f" Mean: {np.mean(generated_scores):.4f}")- print(f" Std: {np.std(generated_scores):.4f}")- print(f" Median: {np.median(generated_scores):.4f}")-- # Distribution similarity metrics- from scipy.stats import ks_2samp- ks_statistic, p_value = ks_2samp(train_scores, generated_scores)-- print(f"\nKolmogorov-Smirnov Test:")- print(f" KS statistic: {ks_statistic:.4f}")- print(f" P-value: {p_value:.4f}")-- if p_value > 0.05:- print(" → Distributions are similar (p > 0.05)")- else:- print(" → Distributions are significantly different (p < 0.05)")---def available_oracles_info():- """- Display information about available oracles- """- print("\n" + "=" * 60)- print("Example 6: Available Oracles")- print("=" * 60)-- oracle_info = {- 'Biochemical Targets': [- 'DRD2', 'GSK3B', 'JNK3', '5HT2A', 'ACE',- 'MAPK', 'CDK', 'P38', 'PARP1', 'PIK3CA'- ],- 'Physicochemical Properties': [- 'QED', 'SA', 'LogP', 'MW', 'Lipinski'+def execute_scores(+ *,+ oracle_name: str,+ category: str,+ smiles: list[str],+ runtime_dir: Path,+ download_acknowledged: bool,+ package_version: str,+) -> dict[str, Any]:+ if category == "checkpoint_download" and not download_acknowledged:+ raise CliError(+ f"{oracle_name} may download a model checkpoint; pass --download "+ "together with --execute to acknowledge this"+ )+ if category not in {"local_scalar", "checkpoint_download"}:+ raise CliError(+ "this helper executes only local QED or the explicitly acknowledged "+ "LogP/SA/DRD2/GSK3B/JNK3/CYP3A4_Veith checkpoint-backed oracles; "+ "remote services, docking, distribution, and composite oracles are "+ "intentionally not called"+ )++ from tdc import Oracle # Lazy optional import.++ with _working_directory(runtime_dir):+ oracle = Oracle(name=oracle_name)+ scores = oracle(smiles)+ if not isinstance(scores, list) or len(scores) != len(smiles):+ raise CliError("PyTDC returned an unexpected oracle result shape")++ return {+ "action": "executed",+ "download_acknowledged": download_acknowledged,+ "oracle": oracle_name,+ "oracle_category": category,+ "package": "PyTDC",+ "package_version": package_version,+ "results": [+ {"score": truncate_value(score), "smiles": truncate_value(smiles_value)}+ for smiles_value, score in zip(smiles, scores)],- 'Composite Metrics': [- 'Isomer_Meta', 'Median1', 'Median2',- 'Rediscovery', 'Similarity', 'Uniqueness', 'Novelty'- ],- 'Specialized': [- 'ASKCOS', 'Docking', 'Vina'- ]+ "runtime_directory": str(runtime_dir),+ "score_direction": "not assumed; results preserve input order",}- print("\nAvailable Oracle Categories:")- print("-" * 60)-- for category, oracles in oracle_info.items():- print(f"\n{category}:")- for oracle_name in oracles:- print(f" - {oracle_name}")-- print("\nFor detailed oracle documentation, see:")- print(" references/oracles.md")--def constraint_satisfaction_example():- """- Example: Molecular generation with constraints- """- print("\n" + "=" * 60)- print("Example 7: Constraint Satisfaction")- print("=" * 60)-- # Define constraints- constraints = {- 'QED': (0.5, 1.0), # Drug-likeness >= 0.5- 'SA': (1.0, 5.0), # Easy to synthesize- 'MW': (200, 500), # Molecular weight 200-500 Da- 'LogP': (0, 3) # Lipophilicity 0-3+def dataset_plan(+ *,+ dataset: str,+ data_dir: Path,+ seed: int,+ fractions: tuple[float, float, float],+ package_version: str,+ download_acknowledged: bool,+) -> dict[str, Any]:+ return {+ "action": "plan",+ "acknowledgement_required": "--execute --download",+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_acknowledged": download_acknowledged,+ "download_performed": False,+ "network_and_storage": (+ "MolGen construction may download a complete, potentially very large "+ "molecule corpus to data_directory."+ ),+ "package": "PyTDC",+ "package_version": package_version,+ "split": {+ "fractions": list(fractions),+ "method": "random",+ "seed": seed,+ },}- # Initialize oracles- oracles = {name: Oracle(name=name) for name in constraints.keys()}-- # Test molecules- test_molecules = [- 'CC(C)Cc1ccc(cc1)C(C)C(O)=O',- 'CC(=O)Oc1ccccc1C(=O)O',- 'Cn1c(=O)c2c(ncn2C)n(C)c1=O'- ]-- print("\nConstraints:")- for prop, (min_val, max_val) in constraints.items():- print(f" {prop}: [{min_val}, {max_val}]")-- print("\n" + "-" * 60)- print("Evaluating molecules against constraints:")- print("-" * 60)-- for smiles in test_molecules:- print(f"\nSMILES: {smiles}")-- satisfies_all = True- for prop, (min_val, max_val) in constraints.items():- score = oracles[prop](smiles)- satisfies = min_val <= score <= max_val-- status = "✓" if satisfies else "✗"- print(f" {prop:10s}: {score:7.2f} [{min_val:5.1f}, {max_val:5.1f}] {status}")-- satisfies_all = satisfies_all and satisfies- result = "PASS" if satisfies_all else "FAIL"- print(f" Overall: {result}")---def main():- """- Main function to run all molecular generation examples- """- print("\n" + "=" * 60)- print("TDC Molecular Generation with Oracles Examples")- print("=" * 60)-- # Load generation dataset- train_smiles = load_generation_dataset()-- # Example 1: Single oracle- single_oracle_example()-- # Example 2: Multiple oracles- multiple_oracles_example()-- # Example 3: Batch evaluation- batch_evaluation_example()-- # Example 4: Goal-directed generation template- goal_directed_generation_template()+def execute_dataset(+ *,+ dataset: str,+ data_dir: Path,+ seed: int,+ fractions: tuple[float, float, float],+ preview: int,+ package_version: str,+) -> dict[str, Any]:+ from tdc.generation import MolGen # Lazy optional import.++ loader = MolGen(name=dataset, path=str(data_dir))+ split = loader.get_split(method="random", seed=seed, frac=list(fractions))+ expected = {"train", "valid", "test"}+ if not isinstance(split, dict) or not expected.issubset(split):+ raise CliError("PyTDC returned an unexpected MolGen split structure")++ partitions: dict[str, Any] = {}+ for name in ("train", "valid", "test"):+ frame = split[name]+ summary: dict[str, Any] = {+ "columns": [str(column) for column in list(frame.columns)[:100]],+ "rows": len(frame),+ }+ if preview:+ summary["preview"] = truncate_value(+ frame.head(preview).to_dict(orient="records")+ )+ partitions[name] = summary++ return {+ "action": "executed",+ "data_directory": str(data_dir),+ "dataset": dataset,+ "download_acknowledged": True,+ "package": "PyTDC",+ "package_version": package_version,+ "partitions": partitions,+ "split": {+ "fractions": list(fractions),+ "method": "random",+ "seed": seed,+ },+ }- # Example 5: Distribution learning- distribution_learning_example(train_smiles)- # Example 6: Available oracles- available_oracles_info()+def _add_output_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--output", help="write JSON to a relative workspace path")+ parser.add_argument(+ "--force", action="store_true", help="replace an existing --output file"+ )- # Example 7: Constraint satisfaction- constraint_satisfaction_example()- print("\n" + "=" * 60)- print("Molecular generation examples completed!")- print("=" * 60)- print("\nNext steps:")- print("1. Implement your generative model")- print("2. Use oracles to guide generation")- print("3. Evaluate generated molecules")- print("4. Iterate and optimize")- print("=" * 60)+def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ description=(+ "Plan or explicitly execute bounded PyTDC molecular workflows. This "+ "helper does not generate molecules and never calls remote-service or "+ "docking oracles."+ )+ )+ subparsers = parser.add_subparsers(dest="command", required=True)++ score = subparsers.add_parser(+ "score",+ help="plan or run bounded scalar-oracle scoring",+ description=(+ "Score bounded user-supplied SMILES. QED is local. LogP, SA, and four "+ "model-backed oracles require --download because they can fetch an "+ "artifact/checkpoint."+ ),+ )+ score.add_argument("--oracle", default="QED", help="exact package oracle name")+ score.add_argument(+ "--smiles", action="append", help="SMILES string; repeat for multiple inputs"+ )+ score.add_argument(+ "--input", help="relative UTF-8 file with one SMILES string per line"+ )+ score.add_argument(+ "--max-molecules",+ type=bounded_int(1, 500),+ default=100,+ help="maximum accepted molecules (default: 100; max: 500)",+ )+ score.add_argument(+ "--runtime-dir",+ default=".pytdc-oracles",+ help="relative directory for any acknowledged checkpoint (default: .pytdc-oracles)",+ )+ score.add_argument(+ "--execute", action="store_true", help="execute the bounded scoring call"+ )+ score.add_argument(+ "--download",+ action="store_true",+ help="acknowledge a supported model-checkpoint download",+ )+ _add_output_arguments(score)++ dataset = subparsers.add_parser(+ "dataset",+ help="plan or load/split a MolGen corpus",+ description=(+ "Plan a MolGen random split. Execution requires both --execute and "+ "--download because these corpora can be large."+ ),+ )+ dataset.add_argument("--dataset", required=True, help="exact MolGen registry name")+ dataset.add_argument(+ "--frac",+ nargs=3,+ type=float,+ metavar=("TRAIN", "VALID", "TEST"),+ default=(0.7, 0.1, 0.2),+ help="split fractions summing to 1 (default: 0.7 0.1 0.2)",+ )+ dataset.add_argument(+ "--seed",+ type=bounded_int(0, 4_294_967_295),+ default=42,+ help="non-negative random split seed (default: 42)",+ )+ dataset.add_argument(+ "--data-dir",+ default=".pytdc-molgen",+ help="relative dataset cache directory (default: .pytdc-molgen)",+ )+ dataset.add_argument(+ "--preview",+ type=bounded_int(0, 5),+ default=0,+ help="include at most this many bounded rows per partition (default: 0)",+ )+ dataset.add_argument(+ "--execute", action="store_true", help="construct and split the MolGen loader"+ )+ dataset.add_argument(+ "--download",+ action="store_true",+ help="acknowledge potentially large dataset download/storage",+ )+ _add_output_arguments(dataset)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ try:+ metadata, package_version = load_pytdc_metadata()+ if args.command == "score":+ smiles = load_smiles(+ args.smiles, args.input, max_molecules=args.max_molecules+ )+ oracle, category = classify_oracle(metadata, args.oracle)+ runtime_dir = safe_directory(+ args.runtime_dir,+ label="oracle runtime directory",+ create=args.execute,+ )+ if args.execute:+ result = execute_scores(+ oracle_name=oracle,+ category=category,+ smiles=smiles,+ runtime_dir=runtime_dir,+ download_acknowledged=args.download,+ package_version=package_version,+ )+ else:+ result = score_plan(+ oracle=oracle,+ category=category,+ smiles_count=len(smiles),+ runtime_dir=runtime_dir,+ package_version=package_version,+ download_acknowledged=args.download,+ )+ else:+ fractions = validate_fractions(args.frac)+ registry_key = canonical_name("MolGen", metadata.dataset_names, "task")+ dataset = canonical_name(+ args.dataset, metadata.dataset_names[registry_key], "MolGen dataset"+ )+ data_dir = safe_directory(+ args.data_dir,+ label="MolGen data directory",+ create=args.execute,+ )+ if args.execute:+ if not args.download:+ raise CliError(+ "MolGen execution may download a large corpus; pass "+ "--download together with --execute to acknowledge it"+ )+ result = execute_dataset(+ dataset=dataset,+ data_dir=data_dir,+ seed=args.seed,+ fractions=fractions,+ preview=args.preview,+ package_version=package_version,+ )+ else:+ result = dataset_plan(+ dataset=dataset,+ data_dir=data_dir,+ seed=args.seed,+ fractions=fractions,+ package_version=package_version,+ download_acknowledged=args.download,+ )+ emit_json(result, args.output, force=args.force)+ except (CliError, ImportError, OSError, TypeError, ValueError) as exc:+ print(f"error: {exc}", file=sys.stderr)+ return 2+ return 0if __name__ == "__main__":- main()+ raise SystemExit(main())diff --git a/skills/pytdc/tests/test_scripts.py b/skills/pytdc/tests/test_scripts.pynew file mode 100644index 00000000..a340ad5a--- /dev/null+++ b/skills/pytdc/tests/test_scripts.py@@ -0,0 +1,222 @@+#!/usr/bin/env python3+"""Synthetic, network-free tests for the bundled PyTDC command-line helpers."""++from __future__ import annotations++import json+import os+import sys+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+++SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"+sys.path.insert(0, str(SCRIPTS))++import _common as common # noqa: E402+import benchmark_evaluation as benchmark # noqa: E402+import cache_audit # noqa: E402+import discover_metadata as discover # noqa: E402+import load_and_split_data as loader # noqa: E402+import molecular_generation as molecular # noqa: E402+++class WorkingDirectoryTestCase(unittest.TestCase):+ def setUp(self) -> None:+ self._previous = Path.cwd()+ self._temporary = tempfile.TemporaryDirectory()+ os.chdir(self._temporary.name)++ def tearDown(self) -> None:+ os.chdir(self._previous)+ self._temporary.cleanup()+++class CommonTests(WorkingDirectoryTestCase):+ def test_safe_paths_reject_escape_and_absolute_paths(self) -> None:+ with self.assertRaises(common.CliError):+ common.safe_relative_path("../escape.json", label="output")+ with self.assertRaises(common.CliError):+ common.safe_relative_path("/tmp/escape.json", label="output")++ def test_emit_json_writes_atomically_and_refuses_overwrite(self) -> None:+ common.emit_json({"ok": True}, "reports/result.json")+ result = json.loads(Path("reports/result.json").read_text(encoding="utf-8"))+ self.assertEqual(result, {"ok": True})+ with self.assertRaises(common.CliError):+ common.emit_json({"ok": False}, "reports/result.json")++ def test_fraction_validation(self) -> None:+ self.assertEqual(+ common.validate_fractions([0.7, 0.1, 0.2]), (0.7, 0.1, 0.2)+ )+ with self.assertRaises(common.CliError):+ common.validate_fractions([0.7, 0.1, 0.3])+++class DiscoveryTests(unittest.TestCase):+ def test_dataset_registry_is_bounded_without_loader(self) -> None:+ metadata = SimpleNamespace(+ dataset_names={"ADME": ["caco2_wang", "hia_hou"]},+ benchmark_names={"admet_group": {"ADME": ["caco2_wang"]}},+ evaluator_name=["mae", "roc-auc"],+ oracle_names=["qed", "sa"],+ )+ result = discover.collect_metadata(+ metadata,+ "1.1.15",+ kind="datasets",+ task="adme",+ offset=0,+ limit=1,+ )+ self.assertFalse(result["download_performed"])+ self.assertEqual(result["task_filter"], "ADME")+ self.assertEqual(result["datasets"]["returned"], 1)+ self.assertTrue(result["datasets"]["truncated"])+++class LoaderTests(unittest.TestCase):+ def setUp(self) -> None:+ self.metadata = SimpleNamespace(+ dataset_names={+ "ADME": ["caco2_wang"],+ "DTI": ["bindingdb_patent"],+ "DrugSyn": ["drugcomb"],+ "MolGen": ["moses"],+ }+ )++ def test_scaffold_request_uses_exact_registry_name(self) -> None:+ task, dataset = loader.validate_request(+ task_query="adme",+ dataset_query="Caco2_Wang",+ method="scaffold",+ columns=[],+ time_column=None,+ metadata=self.metadata,+ )+ self.assertEqual((task, dataset), ("ADME", "caco2_wang"))++ def test_cold_split_requires_columns(self) -> None:+ with self.assertRaises(common.CliError):+ loader.validate_request(+ task_query="DTI",+ dataset_query="bindingdb_patent",+ method="cold_split",+ columns=[],+ time_column=None,+ metadata=self.metadata,+ )++ def test_verified_time_split(self) -> None:+ task, dataset = loader.validate_request(+ task_query="DTI",+ dataset_query="BindingDB_Patent",+ method="time",+ columns=[],+ time_column="Year",+ metadata=self.metadata,+ )+ self.assertEqual((task, dataset), ("DTI", "bindingdb_patent"))+++class BenchmarkTests(unittest.TestCase):+ def test_many_run_prediction_schema(self) -> None:+ payload = {+ "runs": [+ {"seed": seed, "predictions": {"caco2_wang": [0.1, 0.2]}}+ for seed in range(1, 6)+ ]+ }+ runs, seeds = benchmark.normalize_predictions(+ payload,+ mode="many",+ available=["caco2_wang"],+ selected_dataset="caco2_wang",+ )+ self.assertEqual(len(runs), 5)+ self.assertEqual(seeds, [1, 2, 3, 4, 5])++ def test_many_run_requires_five_runs(self) -> None:+ with self.assertRaises(common.CliError):+ benchmark.normalize_predictions(+ [{"caco2_wang": [0.1]}] * 4,+ mode="many",+ available=["caco2_wang"],+ selected_dataset=None,+ )++ def test_non_finite_predictions_are_rejected(self) -> None:+ with self.assertRaises(common.CliError):+ benchmark.normalize_predictions(+ {"caco2_wang": [float("nan")]},+ mode="single",+ available=["caco2_wang"],+ selected_dataset=None,+ )+++class MolecularTests(WorkingDirectoryTestCase):+ def setUp(self) -> None:+ super().setUp()+ self.metadata = SimpleNamespace(+ oracle_names=[+ "qed",+ "sa",+ "drd2",+ "fpscores",+ "novelty",+ "askcos",+ "3pbl_docking",+ ],+ download_oracle_names=["drd2", "fpscores"],+ distribution_oracles=["novelty"],+ download_receptor_oracle_name=["3pbl_docking"],+ synthetic_oracle_name=["askcos"],+ )++ def test_oracle_classification_is_explicit(self) -> None:+ self.assertEqual(+ molecular.classify_oracle(self.metadata, "QED"),+ ("qed", "local_scalar"),+ )+ self.assertEqual(+ molecular.classify_oracle(self.metadata, "DRD2"),+ ("drd2", "checkpoint_download"),+ )+ self.assertEqual(+ molecular.classify_oracle(self.metadata, "SA"),+ ("sa", "checkpoint_download"),+ )+ self.assertEqual(+ molecular.classify_oracle(self.metadata, "ASKCOS"),+ ("askcos", "remote_service"),+ )++ def test_smiles_input_is_bounded(self) -> None:+ self.assertEqual(+ molecular.load_smiles(["CCO"], None, max_molecules=1), ["CCO"]+ )+ with self.assertRaises(common.CliError):+ molecular.load_smiles(["CCO", "CCC"], None, max_molecules=1)+++class CacheAuditTests(WorkingDirectoryTestCase):+ def test_manifest_is_bounded_and_skips_symlinks(self) -> None:+ root = Path("data")+ root.mkdir()+ (root / "small.csv").write_bytes(b"123")+ (root / "large.pkl").write_bytes(b"123456")+ (root / "link").symlink_to(root / "small.csv")+ result = cache_audit.audit_cache(root.resolve(), max_files=10, largest_limit=1)+ self.assertEqual(result["file_count"], 2)+ self.assertEqual(result["total_bytes"], 9)+ self.assertEqual(result["largest_files"][0]["path"], "large.pkl")+ self.assertEqual(result["symlink_count_skipped"], 1)+++if __name__ == "__main__":+ unittest.main()