COSMolKit — Rust-native cheminformatics toolkit
COSMolKit is a Rust-native cheminformatics and structural biology toolkit with first-class Python bindings. It provides molecular graph operations, SMILES/SMARTS and molecular file workflows, 2D depiction, native 3D conformer generation, UFF/MMFF optimization, fingerprints, molecular descriptors, InChI, batch processing, and protein structure APIs.
For supported cheminformatics operations, RDKit-compatible behavior is treated as the correctness floor. Implementations are validated with fixed parity oracles and source-defined tests where applicable, while unsupported behavior fails explicitly instead of being approximated through silent fallbacks.
COSMolKit combines a native Rust API with Python interfaces designed for array-oriented scientific and machine-learning workflows. Molecular graphs, coordinates, fingerprints, bounds matrices, and structural data are exposed in forms suitable for NumPy, PyTorch, dataset processing, and model-building pipelines.
Documentation
- Python documentation: https://kit.cosmol.org/
- Rust crate notes:
crates/cosmolkit/README.md - Feature parity scope:
dev/parity_scope.md
Validation Status
COSMolKit validates its supported cheminformatics surface with strict operation contracts, fixed reference oracles, source-backed parity tests, and committed validation corpora. Coverage CI instruments cosmolkit-core, cosmolkit-inchi, and cosmolkit-ringdecomposer, rejects mismatched LLVM profile data, and runs the committed 5000-row InChI parity corpus in addition to the default test suites.
The four public scalar InChI operations match pinned official InChI v1.07.5 and RDKit 2026.03.1 output exactly for all currently validated source-defined cases. Official-C undefined behavior is represented by a structured Rust error instead of an implementation-dependent result.
The public with_chiral_tags_from_structure() operation is stable with pinned
RDKit 2026.03.1 parity for its documented assignChiralTypesFrom3D scope. All
77 fixed full-state oracle records match exactly, including conformer
selection, replacement control, tetrahedral and enabled non-tetrahedral atom
tags, properties, no-op paths, and defined errors. The value-style and in-place
forms preserve caller state on failure.
Installation
pip install cosmolkit
Core Concepts
- Value-style molecules: methods such as
with_hydrogens(),without_hydrogens(),with_kekulized_bonds(), andwith_2d_coordinates()return new molecule values. - Explicit mutation: in-place
Moleculeoperations always end with_. The trailing underscore has no other publicMoleculemeaning. - Explicit errors: invalid input and unsupported behavior are surfaced as errors instead of silent fallbacks.
- Batch-native processing:
MoleculeBatchkeeps input order, supports structured per-record failures, and can run batch transforms and exports with configurable parallelism. - Array-friendly data access: coordinates, bounds matrices, fingerprints, and graph features are exposed in forms that fit Python numerical workflows.
- Source-backed 3D workflows: conformer generation and UFF/MMFF optimization are available through the public Python API, and atom chiral tags can be assigned from a selected 3D conformer with pinned-RDKit parity.
Value-Style Transformations
Normal molecule operations return new objects and do not mutate their inputs. This follows the same explicit-dataflow direction as modern dataframe libraries: users can reason about each transformation as a new value while COSMolKit can share unchanged internal storage efficiently.
from cosmolkit import Molecule
mol = Molecule.from_smiles("CCO")
mol_h = mol.with_hydrogens()
assert mol is not mol_h
Python Quick Start
from cosmolkit import Molecule, MoleculeBatch
mol = Molecule.from_smiles("c1ccccc1O")
mol_2d = mol.with_2d_coordinates()
print(mol_2d.to_smiles())
print(mol_2d.coordinates_2d())
mol_3d = mol.with_hydrogens().with_3d_conformer()
print(mol_3d.coordinates_3d().shape)
svg = mol_2d.to_svg(width=400, height=300)
mol_2d.write_png("phenol.png", width=400, height=300)
fp = mol.fingerprint_morgan(radius=2, n_bits=2048)
print(fp.on_bits())
batch = (
MoleculeBatch.from_smiles_list(
["CCO", "c1ccccc1", "CC(=O)O"],
sanitize=True,
errors="keep",
)
.with_parallel_jobs(8)
.with_progress_bar(False)
)
prepared = batch.with_hydrogens(errors="keep").with_2d_coordinates(errors="keep")
print(prepared.valid_mask())
print(prepared.to_smiles_list())
prepared.to_images(
"molecule_images",
format="png",
size=(300, 300),
errors="keep",
filenames=["ethanol", "benzene", "acetate"],
)
Protein Structures
Use Protein when the workflow is focused on protein chains rather than the
full structural table.
from cosmolkit import Protein
protein = Protein.from_pdb("1crn.pdb")
print(protein.num_chains())
print(protein.num_residues())
print(protein.num_atoms())
for chain in protein.chains():
print(chain.index(), chain.kind(), len(chain))
for residue in chain.residues():
print(residue.name(), residue.kind(), len(residue))
SDF and Dataset Workflows
SdfDataset builds a lightweight index of SDF record byte ranges, so individual
records and chunks can be read without loading an entire file into memory.
Molfile-only readers such as Molecule.read_mol() follow RDKit
MolFromMolBlock boundaries: they stop after the first M END line and leave
trailing SDF data fields to the SDF APIs.
from cosmolkit import SdfDataset
dataset = SdfDataset.open("library.sdf")
print(len(dataset))
record = dataset[0]
mol = record.molecule()
for batch in dataset.batches(size=1024, errors="keep", n_jobs=8):
smiles = batch.to_smiles_list()
Conformer Generation And Optimization
from cosmolkit import EmbedParameters, Molecule
mol = Molecule.from_smiles("CC(=O)NC").with_hydrogens()
params = EmbedParameters.etkdg_v3()
params.random_seed = 0xF00D
params.num_threads = 1
params.track_failures = True
embedded = mol.with_3d_conformer(params)
print(embedded.num_conformers())
print(embedded.coordinates_3d().shape)
print(params.failures)
multi = mol.with_3d_conformers(5, params)
print(multi.num_conformers())
if embedded.has_uff_params():
uff = embedded.with_uff_optimized(max_iters=200)
print(uff.energy())
if embedded.has_mmff_params():
mmff = embedded.with_mmff_optimized(max_iters=200)
print(mmff.needs_more())
with_3d_conformer() follows RDKit's ETKDG behavior for trusted molecular
graphs: molecules without explicit hydrogens are embedded as heavy-atom-only
conformers instead of failing or automatically adding hydrogens. Calling
with_hydrogens() first is recommended for all-atom geometry, force-field
optimization, and hydrogen-bond-sensitive workflows. Coordinate-only inputs
such as XYZ blocks do not contain a bond topology and are not valid ETKDG
inputs until a trusted graph has been constructed.
Feature Areas
- Molecular graph construction and inspection
- SMILES parsing and writing
- MOL/SDF reading and writing
- MOL2 reading with RDKit-style
Mol2ParserParams - XYZ block reading
- Four scalar InChI APIs with exact source-defined official-C/RDKit parity and structured errors
- Stable 3D atom-chiral-tag assignment with exact pinned-RDKit full-state parity
- Hydrogen transforms and Kekulization
- Sanitization and chemistry problem detection
- 2D coordinate generation and SVG/PNG depiction
- Native 3D conformer generation with DG/KDG/ETDG/ETKDG parameter presets
- UFF/MMFF optimization of generated or imported 3D conformers
- Morgan and MACCS fingerprints for the validated exact-parity branches
- Distance-geometry bounds matrices
- Substructure matching and SMARTS parse metadata
- Ordered batch transforms and exports
- Python pickle round-tripping for
Molecule - PDB/mmCIF molecule-block parsing and protein projection APIs
- Support-status metadata for public features
Design Principles
COSMolKit aims to be Python-friendly, batch-friendly, and suitable for model-building workflows.
- Correctness comes before breadth.
- Public transforms use value semantics.
- Mutation-capable workflows are explicit.
- Unsupported chemistry should fail clearly.
- RDKit-parity behavior is the correctness floor for supported cheminformatics features.
- High-throughput APIs should preserve input order and expose per-record failures.
Examples
Python examples live in python/examples/.
Development
Small focused Rust test filters may use the default debug profile while iterating:
cargo test -p cosmolkit-core --features op-contracts-strict <test-filter>
Large local runs, parity suites, and CI tests should use release mode with the same strict feature set:
cargo test -p cosmolkit-core --release --features op-contracts-strict
Release-mode testing keeps operation contracts and runtime invariants enabled
through op-contracts-strict; optimized release builds for distribution use
default features unless explicit runtime checks are requested.
Roadmap
Status labels:
- ✅ stable public functionality within its documented supported scope
- 🧪 public experimental feature; available, but its behavior or API may change
- 🚧 planned or not yet public
The ✅ status applies to the documented COSMolKit scope. It does not claim that every API or input branch from an upstream reference library is implemented; behavior outside that scope must continue to fail explicitly.
Chemistry Core
Goal: keep the supported molecular core correct before expanding breadth.
- ✅ Molecule, atom, and bond graph model
- ✅ SMILES parsing
- ✅ SMILES writing with RDKit-style writer options for supported branches
- ✅ Ring perception, valence handling, aromaticity, and Kekulization
- ✅ Hydrogen addition and removal
- ✅ Sanitization for supported chemistry workflows
- ✅ Stereochemistry inspection for supported atom and bond states
- ✅ Atom chiral-tag assignment from selected 3D conformers, with exact
pinned-RDKit
assignChiralTypesFrom3Dparity across 77 fixed full-state oracle records - ✅ Distance-geometry bounds matrices
- ✅ Native 3D conformer generation and UFF/MMFF post-optimization for supported molecules
- ✅
Chem.MolToInchi,Chem.MolToInchiKey,InchiToInchiKey, andChem.MolFromInchifor source-defined behavior; official-C undefined allocation behavior returns a structured error - ✅ Morgan fingerprints and Tanimoto similarity for the validated exact-parity branches
- ✅ MACCS fingerprints for the validated exact raw/public projection
- 🚧 RDKFingerprint/topological and Avalon fingerprints fail closed until the source-exact follow-up plan is completed with exact-bit parity
- ✅ Substructure matching and Python SMARTS parse metadata
- ✅ Molecular descriptors: average/exact molecular weight, formula, H-bond donor/acceptor counts, fraction Csp3, Crippen logP/MR, TPSA, aromatic-ring count, rotatable-bond modes, and QED for the documented parameter space
File I/O and Depiction
Goal: make common molecule import, export, and visualization workflows usable from Python.
- ✅ MOL/SDF reading
- ✅ MOL2 reading
- ✅ XYZ block reading
- ✅ SDF dataset indexing for large files
- ✅ SDF writing for supported V2000/V3000 branches
- ✅ PDB block to molecule conversion
- ✅ mmCIF block to molecule conversion through the same molecule-conversion profile
- ✅ 2D coordinate generation
- ✅ SVG drawing
- ✅ PNG export
- ✅ RDKit-style visual parity testing for supported depiction output
- 🚧 Annotation overlays and richer drawing customization
- ✅ 3D conformer generation and embedding APIs
Batch-Native Workflows
Goal: make high-throughput molecule preparation and export a core product identity.
- ✅ Ordered
MoleculeBatch.from_smiles_list() - ✅ Batch transforms for sanitization, hydrogens, Kekulization, and 2D coordinates
- ✅ Configurable parallelism with
with_parallel_jobs() - ✅ Configurable progress display with
with_progress_bar() - ✅ Per-record errors, valid masks, and error reports
- ✅ Batch SMILES, image, and SDF export paths
- ✅ Golden parity tests for parallel batch behavior
- 🚧 More streaming and chunked dataset workflows
Protein and Structural Biology
Goal: provide practical Biopython-like structure workflows without forcing users through low-level structural tables.
- ✅
Protein.from_pdb()/Protein.from_mmcif()high-level entry points - ✅ Protein chain, residue, and atom iteration
- ✅ Protein-only projection from broader structural data
- ✅ PDB/mmCIF structural parsing
- 🚧 Selection utilities for chains, residues, atoms, and neighborhoods
- 🚧 Ligand, nucleic-acid, and mixed-structure ergonomic APIs
Python API and ML Readiness
Goal: expose verified molecular behavior through a practical Python interface.
- ✅ Stable value-style mutation contract for public molecule transformations
- ✅ Graph, coordinate, fingerprint, descriptor, and bounds-matrix accessors
- ✅ Python examples for drawing, SDF-to-SMILES, pickle round-tripping, batch processing, and proteins
- ✅ Type stubs and documentation coverage
- 🚧 Stable model-ready graph exports
- 🚧 NumPy / PyTorch oriented adapters
- 🚧 Molecular tokenization and AI-native geometry helpers
Browser and Deployment
Goal: support lightweight chemistry workflows outside native Python processes.
- 🚧 WASM compilation target
- 🚧 JavaScript bindings
- 🚧 Browser-native SMILES/SDF parsing and depiction
Respect for RDKit
COSMolKit is developed with deep respect for RDKit and the broader open-source cheminformatics community. The goal is an independent Rust-native implementation that preserves interoperability and RDKit-parity behavior where appropriate, while offering a deterministic Python API and AI-native extension surface.
License
COSMolKit is licensed under the MIT License. Vendored sources and externally derived test fixtures retain their upstream copyright and license terms as documented beside those files.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cosmolkit-0.2.11.tar.gz.
File metadata
- Download URL: cosmolkit-0.2.11.tar.gz
- Upload date:
- Size: 5.0 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7a0a681f8264fcee0343be0126c735832582c982f49d3d9b326692b6a358edf2
|
|
| MD5 |
e187a329d25f15df22b2847c529ab679
|
|
| BLAKE2b-256 |
b7b70ad61e6b9be70a47843c2a5bcfdc3b612e8300f460b6201ddb1f48606e49
|
File details
Details for the file cosmolkit-0.2.11-cp39-abi3-win_amd64.whl.
File metadata
- Download URL: cosmolkit-0.2.11-cp39-abi3-win_amd64.whl
- Upload date:
- Size: 5.7 MB
- Tags: CPython 3.9+, Windows x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
32933e3d4ff9f9a5f4d370159732294fab372fdf1c8daa50b970eac72612380b
|
|
| MD5 |
c71810bb66cbbabce4a430190a526d2d
|
|
| BLAKE2b-256 |
6e80bf5edaff744e18f9da1b4f6458fc6c6fbed8bf73b4cf81a213104d2bc104
|
File details
Details for the file cosmolkit-0.2.11-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.
File metadata
- Download URL: cosmolkit-0.2.11-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
- Upload date:
- Size: 5.9 MB
- Tags: CPython 3.9+, manylinux: glibc 2.17+ x86-64
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
633023056b4924d1fb00b6a912d06548485ce15cd0db9f2d4bf698ee6d3d8375
|
|
| MD5 |
4a8d9c0ca72785a0d386a018744994d4
|
|
| BLAKE2b-256 |
2aabeb9ebced1f787a3cea5d241a86469aa55ec006983e7daa0eaee43e88e19c
|
File details
Details for the file cosmolkit-0.2.11-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.
File metadata
- Download URL: cosmolkit-0.2.11-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
- Upload date:
- Size: 5.6 MB
- Tags: CPython 3.9+, manylinux: glibc 2.17+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ab8d88cda6b2b6a69031acda0f4fdb7b04daff0877978998811d7e49fc8c4862
|
|
| MD5 |
996d2efadc0a3605b4a8d7550e7c789c
|
|
| BLAKE2b-256 |
ec4e89a87cde0393b771947eba55aebde7d6c9d1922ca926beafa21b896796d5
|
File details
Details for the file cosmolkit-0.2.11-cp39-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl.
File metadata
- Download URL: cosmolkit-0.2.11-cp39-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl
- Upload date:
- Size: 11.1 MB
- Tags: CPython 3.9+, macOS 10.12+ universal2 (ARM64, x86-64), macOS 10.12+ x86-64, macOS 11.0+ ARM64
- Uploaded using Trusted Publishing? No
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
422057c49fd9193690edb1090c955fd309d51fdadfa4908744d6940f543d8cfb
|
|
| MD5 |
2e81bbfbe142dc66540b16bc735da42c
|
|
| BLAKE2b-256 |
c17fc15cb4269c566e7495f9880dcfa32d4716ad9ff46c4afece58608e75037c
|