chemoinformatics/molecular-standardization/SKILL.md
Standardizes molecular structures using the ChEMBL structure pipeline for normalization and parent selection plus RDKit rdMolStandardize for explicit custom steps such as tautomer canonicalization, salt/solvent stripping, charge handling, stereochemistry handling, mixture selection, and isotope normalization. Explicitly compares ChEMBL, canSARchem, RDKit, and PubChem standardization choices. Use when preparing libraries for QSAR training, joining datasets across sources, deduplicating compound collections, or building canonical compound registries.
npx skillsauth add GPTomics/bioSkills bio-molecular-standardizationInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Reference examples tested with: RDKit 2024.09+ and chembl_structure_pipeline 1.2+. MolVS 0.1.1 is a legacy package; use RDKit's maintained rdMolStandardize module for custom pipelines.
Before using code patterns, verify installed versions match. If versions differ:
pip show <package> then help(module.function) to check signaturesIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.
Convert raw molecular structures into a consistent form for ML training data, deduplication, registry, and cross-database joining. Skipping standardization can create data leakage when alternate representations of one compound enter different splits, distort QSAR inputs, and cause database join misses. The ChEMBL structure pipeline (Bento et al. 2020) is built on RDKit and applies ChEMBL-specific normalization and parent-selection rules. canSARchem (Dolciami et al. 2022) adds canonical-tautomer selection before parent extraction. RDKit's maintained rdMolStandardize module provides primitives for building an explicit custom pipeline.
For format-level I/O and aromaticity perception, see chemoinformatics/molecular-io. For descriptor calculation after standardization, see chemoinformatics/molecular-descriptors.
| Stage | RDKit Tool | Operation | Common errors caught |
|-------|-----------|-----------|----------------------|
| 1. Sanitization | Chem.SanitizeMol | Kekulize, assign aromaticity, fix valences | Wrong valence on N/O |
| 2. Salt stripping | rdMolStandardize.FragmentRemover or LargestFragmentChooser | Remove counterions | Cl-, Na+, K+, OH- |
| 3. Mixture choice | LargestFragmentChooser | Pick parent fragment | Co-crystals, hydrates |
| 4. Charge neutralization | Uncharger | Neutralize while preserving net charge | Permanent charges preserved (quaternary N+) |
| 5. Tautomer canonicalization | TautomerEnumerator.Canonicalize | Pick canonical tautomer | Keto/enol; amide/imidate |
| 6. Stereo standardization | Chem.AssignStereochemistry | Consistent stereo descriptors | Lost wedges, ambiguous R/S |
| 7. Isotope normalization | Explicitly set selected atom isotope labels to 0 | Remove 13C, 2H labels | Tracer studies; preserve labels when scientifically meaningful |
| 8. Output canonicalization | Chem.MolToSmiles(canonical=True) | Canonical SMILES + InChIKey | Round-trip stability |
| Pipeline | Origin | Tautomer canonicalization | Salt definition | Use case |
|----------|--------|---------------------------|-----------------|----------|
| ChEMBL pipeline | EBI ChEMBL | Not performed by standardize_mol or get_parent_mol | ChEMBL salt list (extensive) | ChEMBL-compatible registration |
| canSARchem | ICR Cancer Research UK | Canonical tautomer BEFORE parent extraction | Extended salt list | Cancer drug discovery |
| PubChem (OpenEye) | NIH NCBI | OpenEye QUACPAC tautomer | PubChem salt list | Bioassay data, large-scale |
| RDKit rdMolStandardize default | Greg Landrum | RDKit TautomerEnumerator | RDKit default | General purpose, open source |
Key difference (canSARchem vs ChEMBL):
This difference matters when alternate tautomeric inputs must be registered as one parent. Do not describe ChEMBL output as tautomer-canonical unless an explicit tautomer step is added and documented.
ChEMBL's standardization is the most widely-used reference. The Python package chembl_structure_pipeline exposes the validated pipeline.
Goal: Apply the industry-reference ChEMBL standardization pipeline to a SMILES.
Approach: Parse SMILES with RDKit, run standardize_mol (sanitize, normalize, and standardize charges), then get_parent_mol (strip salts/counter-ions), and emit canonical SMILES. Add rdMolStandardize.TautomerEnumerator separately only when the project requires tautomer canonicalization.
from chembl_structure_pipeline import standardize_mol, get_parent_mol
from rdkit import Chem
def chembl_pipeline(smi):
mol = Chem.MolFromSmiles(smi)
if mol is None:
return None, 'parse_failure'
standardized = standardize_mol(mol)
parent, exclude = get_parent_mol(standardized)
if exclude:
return None, 'excluded_by_chembl'
return Chem.MolToSmiles(parent), 'ok'
standardize_mol: sanitize, normalize functional groups, and standardize charges; returns one RDKit molecule.
get_parent_mol: strip salts/counter-ions and choose the parent; returns (parent_mol, exclude_flag).
Output: canonical SMILES of the selected parent after the ChEMBL transformations, or an explicit excluded_by_chembl status when the parent carries ChEMBL's exclusion flag. Neutralizable acid/base sites may be normalized, but permanent or otherwise non-removable charges can remain; do not assume every emitted parent is neutral.
For more granular control or non-ChEMBL workflows.
Goal: Execute each standardization step explicitly to control salt stripping, charge handling, tautomer canonicalization, and isotope normalization.
Approach: Run the 8-stage pipeline (sanitize, largest fragment, normalize, uncharge, tautomer canonicalize, isotope strip, stereo standardize, canonical SMILES) sequentially with rdMolStandardize primitives.
from rdkit import Chem
from rdkit.Chem.MolStandardize import rdMolStandardize
def full_standardize(smi, keep_isotopes=False):
mol = Chem.MolFromSmiles(smi)
if mol is None:
return None
Chem.SanitizeMol(mol)
largest = rdMolStandardize.LargestFragmentChooser(preferOrganic=True)
mol = largest.choose(mol)
normalizer = rdMolStandardize.Normalizer()
mol = normalizer.normalize(mol)
uncharger = rdMolStandardize.Uncharger(canonicalOrder=True)
mol = uncharger.uncharge(mol)
enumerator = rdMolStandardize.TautomerEnumerator()
mol = enumerator.Canonicalize(mol)
if not keep_isotopes:
for atom in mol.GetAtoms():
atom.SetIsotope(0)
Chem.AssignStereochemistry(mol, cleanIt=True, force=True)
return Chem.MolToSmiles(mol)
canonicalOrder=True makes the uncharger choose neutralization sites in canonical order when more than one equivalent site is available. It does not itself decide whether a permanent charge is retained; inspect charge-sensitive structures and keep force=False unless a documented policy requires otherwise.
| Salt form | Action | Example |
|-----------|--------|---------|
| Mono-salt | Strip counter-ion | [Na+].CC(=O)[O-] -> CC(=O)O |
| Di-salt | Strip both | [Na+].[Na+].CC(=O)[O-].CC(=O)[O-] -> CC(=O)O |
| Mixed salt | Largest organic fragment | CCO.CC(=O)O -> CCO (or CC(=O)O depending on rule) |
| Co-crystal | Hardest case | CC(=O)O.CCOC(C)=O -- both organic; default returns largest |
| Hydrate | Strip waters | CC(=O)O.O -> CC(=O)O |
| Solvate | Strip solvents | CC(=O)O.CO -> CC(=O)O |
| Quaternary ammonium | Preserve charge | [N+](C)(C)(C)C (permanent charge; do NOT neutralize) |
LargestFragmentChooser(preferOrganic=True) prefers organic fragments over inorganic counter-ions even if smaller; for co-crystals, default rule picks largest organic fragment.
Tautomer canonicalization is the most controversial standardization step. There is no universally-correct canonical tautomer for many drug-like molecules.
| Tautomer pair | Why the policy matters | |---------------|------------------------| | Keto/enol | Canonicalization can select a representation different from the experimentally relevant bound or solution form | | Lactam/lactim | Heterocycle scoring rules and toolkit versions may choose different representatives | | Amidine/iminol | Proton placement changes donor/acceptor annotations and downstream matching | | Phenol/keto (e.g., naphthol/naphthalenone) | Aromaticity and functional-group perception can change with the selected representation | | 2H-pyrazole / 1H-pyrazole | Nitrogen identity and donor/acceptor assignments depend on proton placement |
Treat the enumerator's canonical result as a reproducible representation chosen by its configured scoring rules, not as a prediction of the dominant tautomer in vivo. Record the RDKit version and any custom transforms or scoring changes.
Practical rules:
obabel input.sdf -O output.sdf -p 7.4; validate generated states because its rule-based protonation is not a substitute for project-specific pKa analysis.from rdkit.Chem.MolStandardize import rdMolStandardize
def canonical_tautomer(smi):
mol = Chem.MolFromSmiles(smi)
enumerator = rdMolStandardize.TautomerEnumerator()
canon = enumerator.Canonicalize(mol)
return Chem.MolToSmiles(canon)
from rdkit import Chem
def standardize_stereo(mol, remove_undefined=False):
Chem.AssignStereochemistry(mol, cleanIt=True, force=True)
if remove_undefined:
Chem.RemoveStereochemistry(mol)
return mol
Cases:
@ / \ / / -> preservedFor ML, remove stereochemistry only when the endpoint, data curation, and model representation justify treating stereoisomers as equivalent; record that policy and test its effect. For docking and FEP, preserve the intended stereoisomer and reject unintended stereo changes.
Goal: Build a standardized + deduplicated training set with replicate-averaged activity for QSAR or ADMET model training.
Approach: Standardize every SMILES through the ChEMBL pipeline, compute InChIKey as canonical identity, group by InChIKey, and mean-aggregate activities; report replicate count for confidence weighting.
import pandas as pd
from chembl_structure_pipeline import standardize_mol, get_parent_mol
def prepare_qsar_data(df, smiles_col='smiles', activity_col='pIC50'):
standardized = []
for i, row in df.iterrows():
mol = Chem.MolFromSmiles(row[smiles_col])
if mol is None:
continue
try:
mol = standardize_mol(mol)
mol, exclude = get_parent_mol(mol)
if exclude:
continue
standardized.append({
'smiles': Chem.MolToSmiles(mol),
'inchikey': Chem.MolToInchiKey(mol),
'activity': row[activity_col],
})
except Exception:
continue
df_std = pd.DataFrame(standardized)
if df_std.empty:
return pd.DataFrame(columns=['inchikey', 'smiles', 'activity', 'n_replicates'])
df_std = df_std.groupby('inchikey').agg(
smiles=('smiles', 'first'),
activity=('activity', 'mean'),
n_replicates=('activity', 'count'),
).reset_index()
return df_std
Standard InChIKey may collapse some mobile-hydrogen tautomer representations, but this is not a substitute for an explicitly chosen tautomer policy. Replicate count signals measurement reliability.
Trigger: Molecule is genuinely an inorganic salt (e.g., NaCl, K2SO4).
Mechanism: get_parent_mol chooses largest organic; falls back to largest fragment for fully inorganic.
Symptom: Returns the salt itself (not a drug).
Fix: Pre-filter to compounds with ≥1 carbon atom.
Trigger: A molecule combines a non-removable charge, such as quaternary ammonium, with other neutralizable sites, or the desired physiological ionization state differs from a structure-normalization rule.
Mechanism: Uncharger adds or removes hydrogens from neutralizable acids and bases. It cannot remove a permanent charge that has no corresponding hydrogen edit; by default it may preserve an opposite neutralizable charge when a non-removable charge is present so that the total charge remains balanced. force=True instead neutralizes all sites that can be neutralized even if the remaining permanent charge leaves a nonzero total charge.
Symptom: The permanent charge remains, but other sites or the total charge differ from the protonation state intended for docking or modeling.
Fix: Choose force according to the documented total-charge policy, keep force=False when balanced countercharges should be preserved, and inspect/prepare physiological protonation states separately.
Trigger: Molecule with many tautomerizable groups (polyhydroxylated heterocycle).
Mechanism: TautomerEnumerator.Enumerate generates all possible tautomers; can produce thousands.
Symptom: OOM or hour-long compute on single molecule.
Fix: Use Canonicalize when only the configured canonical representation is needed. Before Enumerate, call enumerator.SetMaxTransforms(limit) (and, when appropriate, SetMaxTautomers(limit)) to cap the search.
Trigger: Code still using legacy from molvs import Standardizer.
Mechanism: The standalone MolVS package is legacy and may not support current Python/RDKit versions. RDKit's maintained rdMolStandardize module remains available.
Symptom: ImportError or AttributeError on newer RDKit.
Fix: Migrate deliberately to from rdkit.Chem.MolStandardize import rdMolStandardize; compare outputs because RDKit functions are not drop-in aliases for every MolVS workflow.
Trigger: Records were processed with different standardization settings or entered in different salt, charge, isotope, stereo, or tautomer forms.
Mechanism: The pipelines did not apply the same explicitly versioned transformations before identity generation.
Symptom: Apparently equivalent records produce different InChIKeys, or an expected database join fails.
Fix: Record and apply the same toolkit version, standardization stages, tautomer policy, and InChI options to both datasets; compare full standardized structures when results still differ.
| Symptom | Cause | Fix |
|---------|-------|-----|
| ImportError from standalone molvs | Legacy package incompatible with current environment | Use maintained rdkit.Chem.MolStandardize.rdMolStandardize APIs and validate output |
| standardize_mol raises or input parsing returns None | Invalid or unsanitizable input | Capture the exception/input index and inspect sanitization deliberately; do not silently accept a partially sanitized structure |
| Stripped wrong fragment | LargestFragmentChooser ambiguity | Manually inspect; consider custom logic |
| Tautomer differs between datasets | Different tautomer rules or toolkit versions | Pin and record the same TautomerEnumerator settings and version |
| Unexpected charge distribution with permanent ions | Uncharger total-charge policy does not match the intended protonation workflow | Review non-removable and neutralizable sites; choose force deliberately and prepare physiological states separately |
| Same InChIKey for apparently different records | Standard-InChI normalization or a rare hash collision | Compare full InChI and standardized structures; InChIKey has no longer form |
| Pipeline slow on large library | Per-molecule Python overhead | Process independent molecules in validated chunks or worker processes; chembl_structure_pipeline itself is a per-molecule API |
rdkit.Chem.MolStandardize.rdMolStandardize API documentation. https://www.rdkit.org/docs/source/rdkit.Chem.MolStandardize.rdMolStandardize.htmlobabel documentation -- pH-dependent hydrogen-addition CLI. https://openbabel.org/docs/Command-line_tools/babel.htmltools
End-to-end CLIP-seq pipeline from FASTQ to ENCODE-compliant binding sites, single-nucleotide crosslink maps, annotation, motifs, and (optionally) differential binding. Use when running the full Yeo lab eCLIP / iCLIP / iCLIP2 / iCLIP3 / irCLIP / PAR-CLIP analysis with SMInput control, protocol-specific UMI extraction, ENCODE STAR parameters, CLIPper or Skipper peak calling with stringent log2 FC and -log10 p thresholds, IDR rescue and self-consistency QC, and downstream motif registration with mCross or PEKA.
development
Detect, date, and contextualize whole-genome duplication (WGD / paleopolyploidy) events using wgd v2 (Chen et al 2024), KsRates (Sensalari 2022 substitution-rate-corrected Ks dating), DupGen_finder (Qiao 2019), MAPS (Li 2018 phylogenomic), POInT (Conant 2008 ordered-block), SLEDGe (2024 ML-based), Whale.jl (Bayesian DL+WGD), and synteny-anchored paranome construction. Use when identifying ancient polyploidy from Ks distributions and synteny block analysis, positioning WGD events relative to speciation, distinguishing tandem from segmental from WGD duplications, dating the 2R/3R vertebrate / fish / salmonid WGDs, building paranome and Ks-age mixture models, applying KsRates substitution-rate correction across lineages, or testing alternative biased-fractionation / dosage-balance models post-WGD.
tools
Build whole-genome alignments using Progressive Cactus (Armstrong 2020 reference-free clade-level WGA), Minigraph-Cactus (Hickey 2024 pangenome-aware), LASTZ chain/net (UCSC pipeline), MUMmer4 (Marçais 2018 pairwise), minimap2 -x asm5/10/20 (Li 2018 fast pairwise), AnchorWave (Song 2022 WGD-aware), and Mauve / progressiveMauve (bacterial). Operates the HAL toolkit (Hickey 2013) for downstream extraction including halSynteny, halLiftover, halBranchMutations, and hal2maf. Use when constructing multi-species alignments for comparative-annotation projection (TOGA), synteny detection, conservation analyses (phyloP / PhastCons), or pangenome graph construction; selecting between reference-free (Cactus) and reference-anchored (LASTZ chains/nets) approaches; tuning sensitivity for closely vs distantly related genomes; or producing HAL files for genome-wide downstream tools.
development
Detect syntenic blocks and structural rearrangements between genomes using MCScanX (Wang 2012), JCVI/MCScan (Tang 2008 Python), GENESPACE (Lovell 2022) for orthology-anchored riparian visualization, SyRI for structural variation, AnchorWave for sequence-level synteny, i-ADHoRe 3.0 for highly diverged species, SynNet for synteny networks, and ntSynt for multi-genome macrosynteny. Use when identifying collinear gene blocks across species, distinguishing macrosynteny from microsynteny, detecting inversions/translocations/duplications, anchoring orthology in WGD lineages, producing publication riparian plots, computing synteny block age via Ks (cross-references whole-genome-duplication), or running synteny-aware ortholog inference in polyploids.