Skip to content

RDWORKS

rdworks is inspired by pandas. Many rdworks functions work like pandas and can be chained into a workflow.

Installation

rdworks requires Python 3.12 or later.

$ pip install rdworks

# or build from the source
$ pip install git+https://github.com/sunghunbae/rdworks.git

# or if you use uv package/project manager
$ uv add rdworks

The core package covers compound libraries, stereoisomers, tautomers, conformers, microstates, and torsion scans with the RDKit force fields (MMFF94, MMFF94s, UFF) or any ASE calculator.

Optional extras

pip install rdworks installs only the core dependencies (about 400 MB). The extra calculators are optional dependency groups ("extras") that are installed only when named in brackets:

Extra Enables Installs
openff 'Parsley', 'Sage', 'Rosemary' (and 'GAFF', 'GAFF2' with AmberTools, see below) openmm, openff-toolkit, openff-interchange, openff-forcefields, openff-nagl, openff-nagl-models (PyTorch via openff-nagl)
aimnet2 'AIMNet2', 'AIMNet2-B973c', ... aimnet, torch-sim-atomistic (PyTorch)
uma 'UMA' and other fairchem UMA models fairchem-core (PyTorch)
# one extra, several extras, or all of them
$ pip install "rdworks[openff]"
$ pip install "rdworks[openff,aimnet2]"
$ pip install "rdworks[openff,aimnet2,uma]"

# extras from the source repository
$ pip install "rdworks[uma] @ git+https://github.com/sunghunbae/rdworks.git"

# uv
$ uv add "rdworks[openff,aimnet2]"

# add an extra later to an existing installation
$ pip install "rdworks[aimnet2]"

Each extra pulls in PyTorch, about 4 GB with the default CUDA build on Linux (see CPU or GPU build of PyTorch). Without an extra, rdworks still imports and runs; asking for one of its calculators raises an ImportError.

Some calculators need more than a Python package:

  • 'GAFF'/'GAFF2': the openff extra plus openmmforcefields and ambertools, which are conda-forge only: conda install -c conda-forge openmmforcefields ambertools.
  • 'xTB': the xtb executable on PATH, e.g. conda install -c conda-forge xtb; there is no pip extra for it.
  • 'UMA': Hugging Face access to the gated UMA checkpoints (see below).

Optional calculators

Conf.singlepoint(), Conf.optimize(), torsion_scan(), and torsion_drive() accept the calculators below once their dependencies are installed:

calculator What it is Install
'MMFF94', 'MMFF94s', 'UFF' RDKit force fields included
ASE calculator object any ASE calculator the calculator's own package
'xTB' GFN2-xTB (supports water='gbsa' or 'alpb') xtb executable on PATH, e.g. conda install -c conda-forge xtb
'Parsley', 'Sage', 'Rosemary' OpenFF force fields with OpenMM pip install "rdworks[openff]"
'GAFF', 'GAFF2' Amber GAFF/GAFF2 with OpenMM rdworks[openff] plus conda install -c conda-forge openmmforcefields ambertools
'AIMNet2', 'AIMNet2-B973c', ... AIMNet2 neural network potential; optimizations with TorchSim pip install "rdworks[aimnet2]"
'UMA' (= uma-s-1p2p1-ft-d4rev), or another UMA model name fairchem UMA machine-learned potential, omol task for molecules; optimizations with ASE pip install "rdworks[uma]" and Hugging Face access to the UMA checkpoints (see below)

UMA checkpoints are gated. Request access at https://huggingface.co/facebook/UMA, then authenticate before the first calculation, for example:

$ export HF_TOKEN=<your Hugging Face token>
# or
$ huggingface-cli login

Notes:

  • GAFF/GAFF2 and OpenFF calculations run in the gas phase and use OpenFF NAGL AM1-BCC partial charges by default. With AmberTools installed, the functions in rdworks.openff also accept charge_method='am1bcc'.
  • AIMNet2 and UMA model files are downloaded on first use, and both use a CUDA GPU when available.
  • UMA uses the molecule's charge (conf.charge) and spin multiplicity (conf.spin) with the omol task. rdworks.uma functions also accept task= and optimizer= ('FIRE', 'LBFGS', 'BFGS').
  • torsion_drive() runs TorsionDrive (https://doi.org/10.1063/5.0009232): constrained optimizations on a periodic grid with wavefront propagation. It supports every calculator above except 'xTB'.

CPU or GPU build of PyTorch

The openff, aimnet2, and uma extras install PyTorch (openff through the NAGL charge model). On Linux, the default PyTorch wheel from PyPI is the CUDA (GPU) build, which with its NVIDIA libraries takes about 4 GB; on macOS and Windows the default is already the CPU build. The CPU and GPU builds share the package name torch and differ only by the package index they come from, so choose the build with the installer before or while installing rdworks:

# pip: install the CPU build of torch first, then rdworks keeps it
$ pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu
$ pip install "rdworks[openff,aimnet2,uma]"

# uv: select the build with --torch-backend (cpu, auto, cu126, cu128, cu130, ...)
$ uv pip install "rdworks[openff,aimnet2,uma]" --torch-backend=cpu

To switch an existing environment, replace torch with the same version from the other index:

# GPU -> CPU
$ pip uninstall -y torch
$ pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cpu

# CPU -> GPU (pick the index that matches your CUDA driver, e.g. cu126 or cu130);
# this also installs the NVIDIA libraries the GPU build needs
$ pip uninstall -y torch
$ pip install torch==2.13.0 --index-url https://download.pytorch.org/whl/cu130

Notes:

  • fairchem-core (the uma extra) requires torch~=2.13.0; keep torch at 2.13.x when switching builds. Without uma, aimnet needs torch >= 2.10 and openff-nagl torch >= 2.6.
  • After switching from GPU to CPU, pip leaves the nvidia-* and triton packages installed (about 2.7 GB); uninstall them or start from a fresh environment.
  • rdworks code is the same for both builds: AIMNet2 and UMA use a CUDA GPU when one is available and the CPU otherwise. The functions in rdworks.aimnet2 and rdworks.uma also take device='cpu' or 'cuda' to choose explicitly.

Running the tests

The tests are in the source repository, not in the installed package. pytest and the other development tools (import-linter, ruff, black, mkdocs, ...) are in the dev dependency group of pyproject.toml, which pip and uv install separately from the extras:

$ git clone https://github.com/sunghunbae/rdworks.git
$ cd rdworks

# pip: editable install, then the dev tools (--group needs a recent pip; upgrade pip if it is unknown)
$ pip install -e .
$ pip install --group dev          # or only: pip install pytest import-linter
$ pytest

# to also run the optional-calculator tests, install the extras too
$ pip install -e ".[openff,aimnet2,uma]"
$ pytest

# uv (installs the dev group by default)
$ uv run pytest                     # core only
$ uv run --all-extras pytest        # with every extra
$ uv run --extra aimnet2 pytest     # with one extra

Tests whose dependencies are missing are skipped, not failed:

Tests Skipped unless
tests/test_openforcefield.py the openff extra is installed
GAFF/GAFF2 cases in tests/test_openforcefield.py openmmforcefields is installed and antechamber (AmberTools) is on PATH
tests/test_aimnet2.py the aimnet2 extra is installed
real-model tests in tests/test_uma.py the uma extra is installed and the UMA checkpoints are accessible (HF_TOKEN); the other UMA tests run without it
import-layering check in tests/test_import_structure.py import-linter is installed
tests/test_xtb.py the xtb executable is on PATH; tests that use CPCM-X solvation or geometry optimization also need those to work with your xtb build

The torsion fragment tests in tests/test_torsion.py run either way: without xtb, create_torsion_fragment() skips its xTB bond-order filter and the tests check that it reports wbo_filtered=False.

Development with pixi

pyproject.toml also defines a pixi workspace (conda-forge) with one environment per extra; the openff environment also brings the conda-only GAFF dependencies (openmmforcefields, ambertools):

$ pixi install                     # default environment
$ pixi run -e test test            # run the test suite (core)
$ pixi run -e test lint-imports    # check the import layering contract
$ pixi run -e openff test          # with OpenFF and GAFF/GAFF2 (openmmforcefields, ambertools)
$ pixi run -e aimnet2 test         # with AIMNet2 and TorchSim
$ pixi run -e uma test             # with fairchem UMA (needs HF_TOKEN for the model tests)
$ pixi build                       # build a conda package (.conda)

The default, dev, and test environments are locked for Linux (x86-64, aarch64), macOS (Intel, Apple silicon), and Windows. The optional-calculator environments are limited by the platforms their dependencies are built for:

Environment Platforms Not available because
openff Linux x86-64 and aarch64, macOS ambertools is not built for Windows
aimnet2 Linux x86-64, macOS on Apple silicon, Windows no PyTorch >= 2.10 for Intel macOS; warp-lang needs glibc >= 2.34 on Linux aarch64
uma Linux x86-64, macOS 14+ on Apple silicon, Windows same as aimnet2; PyTorch 2.13 needs macOS 14

Usage

Process Compound Library

from rdworks import MolLibr

# initialize the library
libr = MolLibr(drug_smiles[:5], drug_names[:5])
libr = MolLibr([Chem.MolFromSmiles(_) for _ in drug_smiles[5:10]], drug_names[5:10])
libr = MolLibr([Mol(smi, name) for smi, name in zip(drug_smiles[10:15], drug_names[10:15])])

# libr will be changed by +=, -=, &= operators
libr += other_libr

# remove redundant compounds
libr_unique = libr.unique()

# select compounds satisfying ZINC druglike rules
drug_like_libr = libr.drop("~ZINC_druglike") 

# select compounds CNS compliant
cns_compliant_libr = libr.drop("~CNS") 
cns_compliant_libr = libr.drop("CNS", invert=True)

# select compounds compliant to a custom rule defined in a xml file
custom_rule_compliant_libr = libr.drop(custom_rul_xml_path, invert=True)

# select neural network potential applicable compounds
ani_2x_applicable_libr = libr.nnp_ready("ANI-2x", progress=False)

# select compounds similar to query with a threshold
sim = libr.similar(query_Mol, threshold=0.2)

Complete Stereoisomers

from rdworks import Mol, MolLibr
from rdworks.complete import complete_stereoisomers

mol = Mol(cmpd.smiles)
stereoisomers = complete_stereoisomers(mol)

Complete Tautomers

from rdworks.complete import complete_tautomers

m = Mol("Oc1c(cccc3)c3nc2ccncc12", "tautomer")
libr = complete_tautomers(m)
assert libr.count() == 3
expected_names = ["tautomer.1", "tautomer.2", "tautomer.3"]
names = [_.name for _ in libr]
assert names == expected_names
expected_canonical_smiles = [
    "O=c1c2c[nH]ccc-2nc2ccccc12",
    "O=c1c2ccccc2[nH]c2ccncc12",
    "Oc1c2ccccc2nc2ccncc12",
]
canonical_smiles = [_.smiles for _ in libr]
difference = set(expected_canonical_smiles) - set(canonical_smiles)
assert len(difference) == 0

Generate Conformer

from rdworks import Mol


mol = Mol(smiles, name)
mol = mol.make_confs(n=n, method='ETKDG')  # ranked by MMFF94 single-point energies
mol = mol.optimize_confs()                 # MMFF94 by default
# remove similar conformers (RMSD <0.3) [and stereo-flipped conformers by default]
mol = mol.drop_confs(similar=True, similar_rmsd=0.3)
# optionally re-optimize with another calculator, e.g. 'Sage', 'AIMNet2', or 'UMA'
mol = mol.optimize_confs(calculator='AIMNet2')
mol = mol.sort_confs().rename()
# cluster aligned conformers: 'QT' (default), 'Butina', or 'DQT' (torsion angles)
mol = mol.align_confs().cluster_confs(method='QT', threshold=1.0, sort='energy')

Serialize/deserialize Molecule or Conformer

Mol and Conf objects have serialize() and deserialize() functions to exchange and reproduce the exact objects.

from rdworks import Conf


mol_serialized = mol.serialize()
lowest_energy_conf_serialized = mol.confs[0].serialize() 
# lowest energy conformer
# serialized conformer is regular string can be easily exchanged
conf = Conf().deserialize(lowest_energy_conf_serialized)

Calculate Energies and Optimize Geometries

calculator can be any of the calculators listed under Optional calculators.

from rdworks import Mol


mol = Mol("CC(=O)Nc1ccc(O)cc1", "acetaminophen").make_confs(n=10)
mol = mol.optimize_confs(calculator="MMFF94")   # or 'Sage', 'GAFF2', 'AIMNet2', 'UMA', ...
mol = mol.sort_confs()

conf = mol.confs[0]
conf.singlepoint("AIMNet2")                       # sets conf.props['E_tot(kcal/mol)']
conf.optimize("Sage", fmax=0.05)                 # sets 'E_tot_init(kcal/mol)', 'E_tot(kcal/mol)', 'Converged'

Profile Torsion Angle Energies

Two scan methods store the same profile format, a list of dicts with indices, angle, E_rel(kcal/mol), and torsion_angle_idx (plus frag and frag_indices when the torsion is scanned on a fragment, simplify=True):

  • torsion_scan() sets each torsion angle and relaxes the whole structure. It is fast, but the torsion angle drifts during relaxation.
  • torsion_drive() runs TorsionDrive (https://doi.org/10.1063/5.0009232): constrained optimizations on a periodic grid with wavefront propagation, so each grid point keeps the lowest energy reachable from its neighbors and the scan has no hysteresis.
from rdworks.torsion import torsion_drive, get_torsion_plot_data


# torsion_scan on the first (lowest-energy) conformer; results in mol.props['torsion']
mol = mol.torsion_scan(calculator="MMFF94", interval=20.0)
plot_data = mol.to_plot_data_torsion_angle_vs_energy()   # {'idx', 'angle', 'E_rel(kcal/mol)'}

# TorsionDrive on a conformer; results in conf.props['torsion']
conf = mol.confs[0]
conf.get_torsion_angle_atoms()                   # [(5, 4, 3, 1)]: atom indices of each rotatable torsion
conf = torsion_drive(conf, calculator="Sage", torsion_angle_idx=0, interval=15.0)
plot_data = get_torsion_plot_data(conf.props["torsion"])
results = conf.serialize()

The notebook notebook/torsion_forcefield_comparison compares Sage, GAFF2, and MMFF94 torsion profiles with AIMNet2.

Generate Microstates

Microstates are molecular states that have defined protonation states. A molecule exists as an ensemble of microstates at a given pH condition.

import logging
import math
import numpy as np
from rdworks import State, StateNetwork


logger = logging.getLogger(__name__)
original_state = State(smiles=smiles)
num_ionizable_sites = len(original_state.sites)
logger.info(f"found {num_ionizable_sites} ionizable sites.")
state_net = StateNetwork()

if num_ionizable_sites > 6:
    state_net.build(smiles=smiles,
                    max_formal_charge=3,
                    protomer_rule='simple',
                    tautomer_rule=None)
else:
    state_net.build(smiles=smiles,
                    max_formal_charge=3,
                    protomer_rule='default',
                    tautomer_rule=None)

state_ens = state_net.get_state_ensemble()
logger.info(f'generated {state_ens.size()} microstates.')

Calculate Microstate Population with External dG Predictor

from unipka.deltaG import UniMolFreeEnergy


dG_dict = dG_predictor.predict([st.smiles for st in state_ens])

# set state energies via Uni-pKa model
# Uni-pka model specific variable for pH dependent deltaG
# Training might be conducted with a dataset in which raw pKa values
# were subtracted by the mean value (TRANSLATE_PH), 6.504894871171601.
dG = [dG_dict[st.smiles] for st in state_ens]
state_ens.set_energies(dG, ref_ph=6.504894871171601)

ph_values = np.linspace(-2, 16, 180)
p = state_ens.get_population(ph_values, C=math.log(10), beta=1.0)
state_ens = state_ens.trim(p, threshold=0.05)

# representative state(s) at pH 7.4, a subset of state_ens
ph_74 = np.array([7.4])
p_74 = state_ens.get_population(ph_74)
# p_74.shape == (self.size(), pH.shape[0] or number of pH)
ph74_pop = {state_idx: p.item() for state_idx, p in enumerate(p_74)}
dictdata = {
    'ensemble' : state_ens.serialize(), # str
    'ph74_pop' : ph74_pop, # dict
    }