API Reference¶
- class cosmolkit.Atom¶
Read-only atom feature record returned by
Molecule.atoms().The methods on this object expose common atom properties such as atomic number, formal charge, aromaticity, chiral tag, hydrogen counts, and valence values.
- class cosmolkit.BatchError¶
A per-record batch processing error.
Batch methods can keep invalid records when
errors="keep"is used. In that case,MoleculeBatch.errors()returnsBatchErrorobjects describing the input index, operation, and message.- as_dict()¶
Return the error as key-value pairs.
- index()¶
Return the zero-based input index that produced the error.
- message()¶
Return the human-readable error message.
- operation()¶
Return the operation name.
- class cosmolkit.BatchErrorMode(value)¶
- class cosmolkit.BatchExportReport¶
Summary returned by batch export methods.
The report records how many inputs were processed successfully and includes structured errors for records that could not be exported.
- errors()¶
Return structured errors for failed records.
- failed()¶
Return the number of records that failed during export.
- success()¶
Return the number of records exported successfully.
- total()¶
Return the total number of records considered for export.
- exception cosmolkit.BatchValidationError(message, error_count=0, reason=None, record_errors=None)¶
- class cosmolkit.Bond¶
Read-only bond feature record returned by
Molecule.bonds().The methods on this object expose atom endpoints, bond type, direction, stereo labels, stereo atom indices, and aromaticity.
- class cosmolkit.BondDirection(value)¶
- class cosmolkit.BondOrder(value)¶
- class cosmolkit.BondStereo(value)¶
- class cosmolkit.ChiralTag(value)¶
- class cosmolkit.Element(value)¶
- class cosmolkit.ElementInfo¶
Source-aligned periodic-table metadata used by COSMolKit.
The
valences()values preserve the source periodic-table sentinels and are not an exhaustive oxidation-state table.
- exception cosmolkit.InchiAllocationError(message, operation, kind, detail)¶
- exception cosmolkit.InchiDiagnosticWarning(level, message)¶
- exception cosmolkit.InchiError(message, operation, kind, detail)¶
- exception cosmolkit.InchiUnsupportedStateError(message, operation, kind, detail)¶
- class cosmolkit.Molecule¶
A molecule value.
Moleculestores atoms, bonds, stereochemistry, and optional coordinate data. Transformation methods such aswith_hydrogens(),without_hydrogens(),with_kekulized_bonds(), andwith_2d_coordinates()return new molecule values. The original molecule is left unchanged.Internally COSMolKit uses copy-on-write storage to share unchanged molecular data efficiently, but the public Python contract is value semantics.
In-place methods mutate the receiver and always end with
_. COSMolKit reserves the trailing underscore for this single publicMoleculemeaning.Examples
Create molecules with
Molecule.from_smiles(), transform them with value methods such aswith_2d_coordinates(), then export strings, arrays, or depiction files.- add_3d_conformer_(coords, *, is_3d=True)¶
Add one 3D conformer in place and return its conformer id.
coordsmust be a numeric array-like object with shape(num_atoms, 3).
- add_hydrogens_()¶
Add explicit hydrogens in place.
This is the in-place version of
with_hydrogens().All public in-place
Moleculemethods end with_. If this method returns an error, it does not roll back and may retain partial changes, but its internal storage remains complete. Usewith_hydrogens()when failure-preserving value semantics are required.
- align_conformers_(params=None)¶
Align selected or all conformers in place and return the ordered source RMS report.
- align_to_(reference, params=None)¶
Align this molecule to
referencein place and return the applied result.
- alignment_transform_to(reference, params=None)¶
Compute the transform aligning this molecule to
referencewithout mutation.The returned result contains the RMSD, 4x4 transform, and selected atom map. Use
with_alignment_to()oralign_to_()to apply the transform.
- all_conformer_best_rmsds(params=None)¶
Return best RMSD values for every ordered triangular conformer pair without mutation.
- analyze_potential_stereo(clean=False, flag_possible=True)¶
Analyze potential stereochemistry without mutating this molecule.
The returned analysis contains the isolated molecule state produced by the source-defined cleanup mode and ordered typed potential-stereo records.
- assign_chiral_tags_from_structure_(conf_id=-1, replace_existing_tags=True)¶
Assign atom chiral tags from 3D coordinates in place.
This is the in-place form of
with_chiral_tags_from_structure(). All public in-placeMoleculemethods end with_. It has the same stable, pinned-RDKit parity scope as the value-style form. Failures are transactional and leave the molecule unchanged.
- assign_cip_labels_(atoms=None, bonds=None, max_recursive_iterations=0)¶
Assign source-backed modern CIP labels in place.
The operation follows COSMolKit’s explicit in-place policy. On an error, the source-backed operation may retain partial source state; internal storage remains complete and the error is raised to Python.
- atoms()¶
Return read-only atom feature records.
- avalon_fingerprint(n_bits=512, is_query=False, bit_flags=15761407)¶
Return the source-backed Avalon explicit bit fingerprint.
The parameters follow the pinned RDKit Python adapter:
n_bitscontrols the public vector size,is_queryselects query-molecule preprocessing, andbit_flagsselects the Avalon feature families. The result does not mutate the source molecule.
- best_alignment_to(reference, params=None)¶
Return the best source-compatible alignment result without mutating either molecule.
- best_rmsd_to(reference, params=None)¶
Return the best aligned RMSD without changing either molecule’s coordinates.
- bonds()¶
Return read-only bond feature records.
- cip_computed()¶
Return whether the molecule has modern CIP assignment state.
- clear_3d_conformers_()¶
Remove all 3D conformers in place.
This is the in-place version of
with_cleared_3d_conformers().
- compute_2d_coordinates_()¶
Compute 2D coordinates in place.
This is the in-place version of
with_2d_coordinates().
- coordinate_rmsd_to(reference, params=None)¶
Measure RMSD in the existing coordinate frame without alignment or mutation.
This method corresponds to RDKit
CalcRMSsemantics, including map enumeration and optional terminal-group symmetrization.
- coordinates_2d()¶
Return 2D coordinates as a NumPy array with shape
(num_atoms, 3).The z column is zero-filled.
- coordinates_3d(conformer_index=0)¶
Return 3D coordinates as a NumPy array with shape
(num_atoms, 3).
- dg_bounds_matrix()¶
Return the distance-geometry bounds matrix as a NumPy array.
The returned array uses shape
(num_atoms, num_atoms).
- edit()¶
Create an explicit edit context for this molecule.
The edit context is useful when several changes should be staged and committed as one new molecule value.
- embed_3d_conformer_(params=None)¶
Generate one 3D conformer in place.
This is the in-place version of
with_3d_conformer().
- embed_3d_conformer_result_(params=None)¶
Generate one 3D conformer in place and return the embedding result object.
This is the in-place version of
with_3d_conformer_result().
- embed_3d_conformers_(num_confs, params=None)¶
Generate multiple 3D conformers in place.
This is the in-place version of
with_3d_conformers().
- embed_3d_conformers_result_(num_confs, params=None)¶
Generate multiple 3D conformers in place and return the embedding result object.
This is the in-place version of
with_3d_conformers_result().
- find_chiral_centers(include_unassigned=True)¶
Return chiral center labels.
- Parameters:
include_unassigned (bool, default True) – Include atoms with unspecified tetrahedral chirality.
- fingerprint_atom_pair(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None)¶
Return the explicit-bit AtomPair fingerprint.
The implementation follows the pinned source generator for 2D or conformer distances, chirality, count simulation, atom filters, and custom invariants. The molecule is not mutated.
- fingerprint_atom_pair_count(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None)¶
Return the folded-count AtomPair fingerprint.
- fingerprint_atom_pair_sparse_bits(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None)¶
Return the sparse-bit AtomPair fingerprint.
- fingerprint_atom_pair_sparse_count(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None)¶
Return the source-width sparse-count AtomPair fingerprint.
- fingerprint_atom_pair_with_output(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None)¶
Return the explicit-bit AtomPair fingerprint with exact provenance output.
- fingerprint_layered(layers=4294967295, min_path=1, max_path=7, fp_size=2048, atom_counts=None, set_only_bits=None, branched_paths=True, from_atoms=None)¶
Return the source-backed RDKit Layered fingerprint.
layersretains the sourceunsigned intflag value, including inactive high bits.set_only_bitsmasks projected bits with another explicit bit vector.from_atoms=Noneuses the unrooted source branch, while an empty list is a present empty root selection and therefore yields no paths. The source molecule is never mutated.
- fingerprint_layered_with_output(layers=4294967295, min_path=1, max_path=7, fp_size=2048, atom_counts=None, set_only_bits=None, branched_paths=True, from_atoms=None)¶
Return a source-backed Layered fingerprint and the optional updated atom counts.
When
atom_countsis provided its values seed the source count vector and the returned counts contain the source increments. Omitting it preserves the source null-pointer branch and returnsNoneforatom_counts().
- fingerprint_morgan(radius=2, n_bits=2048, include_chirality=False, use_bond_types=True, count_simulation=False, count_bounds=None, only_nonzero_invariants=False, include_redundant_environments=False, from_atoms=None, ignore_atoms=None, custom_atom_invariants=None, custom_bond_invariants=None, atom_invariants_generator=None, atom_invariants_include_ring_membership=True, bond_invariants_generator=None, bond_invariants_use_bond_types=True, bond_invariants_use_chirality=False, num_bits_per_feature=1)¶
Return a Morgan fingerprint for the supported RDKit bit-identical branches.
The exposed Morgan branches are checked against RDKit exact-bit parity. A 99.9% match, similarity correlation, or structurally similar hashing is not a passing state.
- Parameters:
radius (int, default 2) – Morgan neighborhood radius.
n_bits (int, default 2048) – Output bit vector size.
include_chirality (bool, default False) – Include atom chirality in invariant updates.
use_bond_types (bool, default True) – Include bond order in invariant updates.
count_simulation (bool, default False) – Apply RDKit count-simulation bit expansion.
count_bounds (list[int], optional) – Count-simulation thresholds. Defaults to
[1, 2, 4, 8].only_nonzero_invariants (bool, default False) – Skip atoms whose starting invariant is zero.
include_redundant_environments (bool, default False) – Retain duplicate environments instead of applying RDKit redundancy checks.
from_atoms (list[int], optional) – Restrict environments to these root atoms.
ignore_atoms (list[int], optional) – Passed through to the RDKit source-backed generator path.
custom_atom_invariants (list[int], optional) – Per-atom starting invariants.
custom_bond_invariants (list[int], optional) – Per-bond invariants.
atom_invariants_generator ({"connectivity", "morgan", "feature", "fcfp"}, optional) – Explicit atom invariant generator.
Noneuses the Morgan connectivity default.atom_invariants_include_ring_membership (bool, default True) – Include ring membership for the connectivity invariant generator.
bond_invariants_generator ({"morgan", "default", "bond"}, optional) – Explicit Morgan bond invariant generator.
Noneuses the fingerprint defaults.bond_invariants_use_bond_types (bool, default True) – Include bond order in the explicit bond invariant generator.
bond_invariants_use_chirality (bool, default False) – Include bond stereo in the explicit bond invariant generator.
num_bits_per_feature (int, default 1) – Number of bits set for each feature.
- fingerprint_morgan_with_output(radius=2, n_bits=2048, include_chirality=False, use_bond_types=True, count_simulation=False, count_bounds=None, only_nonzero_invariants=False, include_redundant_environments=False, from_atoms=None, ignore_atoms=None, custom_atom_invariants=None, custom_bond_invariants=None, atom_invariants_generator=None, atom_invariants_include_ring_membership=True, bond_invariants_generator=None, bond_invariants_use_bond_types=True, bond_invariants_use_chirality=False, num_bits_per_feature=1)¶
Return a Morgan fingerprint with RDKit bit-identical provenance output.
The fingerprint and exposed AdditionalOutput fields are checked against RDKit exact-bit and exact-field parity for the supported branches.
- fragments()¶
Return the connected fragments as separate molecules.
- classmethod from_inchi(inchi, *, sanitize=True, remove_hs=True)¶
Create a molecule from an InChI string.
Returns
Nonewhen the source API returns no graph or molecule sanitization rejects the parsed graph.
- classmethod from_mmcif_block(text, *, sanitize=True, remove_hs=True, flavor=0, proximity_bonding=True)¶
Create a molecule from an mmCIF block.
This uses COSMolKit’s mmCIF structure reader, then applies the same RDKit-compatible molecule conversion profile used by
Molecule.from_pdb_block. RDKit does not provide a directChem.MolFromMMCIFBlockoracle; this API is a COSMolKit mmCIF structural reader layered into the RDKit-compatible PDB molecule conversion state.- Parameters:
text (str) – mmCIF block text.
sanitize (bool) – Whether to sanitize after molecule construction.
remove_hs (bool) – Whether sanitization should remove hydrogens.
flavor (int) – RDKit-compatible PDB parser flavor bit mask applied during molecule conversion.
proximity_bonding (bool) – Whether to add proximity bonds using RDKit’s PDB proximity-bond algorithm.
- Returns:
Parsed molecule.
- Return type:
- classmethod from_pdb_block(text, *, sanitize=True, remove_hs=True, flavor=0, proximity_bonding=True)¶
Create a molecule from a PDB block.
This follows the COSMolKit core PDB molecule conversion profile, which is designed to match RDKit
Chem.MolFromPDBBlockfor modeled molecule state. Structural parsing is handled by COSMolKit’s structure reader before molecule conversion.- Parameters:
text (str) – PDB block text.
sanitize (bool) – Whether to sanitize after PDB molecule construction.
remove_hs (bool) – Whether sanitization should remove hydrogens.
flavor (int) – RDKit-compatible PDB parser flavor bit mask.
proximity_bonding (bool) – Whether to add proximity bonds using RDKit’s PDB proximity-bond algorithm.
- Returns:
Parsed molecule.
- Return type:
- classmethod from_rdkit(rdmol, sanitize=None)¶
Create a molecule from an RDKit molecule object.
- Parameters:
rdmol (object) – An object exposing RDKit’s molecule API.
sanitize (bool, optional) – By default, preserve the copied RDKit graph and prepare its valence cache. Pass
Trueto run full sanitization orFalseto retain an unprepared graph without a computed valence cache.
- Returns:
COSMolKit molecule copied from the input object.
- Return type:
- classmethod from_smiles(smiles, sanitize=None)¶
Create a molecule from a SMILES string.
- Parameters:
smiles (str) – Input SMILES string.
sanitize (bool, optional) – Optional molecule preparation flag. COSMolKit applies the available preparation behavior during construction.
- Returns:
Parsed molecule.
- Return type:
Examples
Use
Molecule.from_smiles("CCO")to create a molecule andmol.to_smiles()to write it back.
- classmethod from_xyz_block(text)¶
Create a molecule from an XYZ block.
XYZ contains atom identities and Cartesian coordinates only. This follows COSMolKit core’s RDKit-aligned
MolFromXYZBlockbehavior: atoms and one 3D conformer are parsed, and bonds are not inferred.The returned molecule is coordinate-only. Topology-dependent operations such as adding hydrogens or ETKDG conformer generation require a trusted bond graph.
- Parameters:
text (str) – XYZ block text.
- Returns:
Parsed molecule with zero bonds and a 3D conformer when the atom count is nonzero.
- Return type:
- has_2d_coordinates()¶
Return whether the molecule has 2D coordinates.
- has_mmff_params()¶
Return whether MMFF94 parameters are available for this molecule.
- has_uff_params()¶
Return whether UFF parameters are available for every atom in this molecule.
- hash()¶
Return a hash of the molecule.
- hash_with_ranks(ranks)¶
Return a hash of the molecule using the provided atom ranks.
- kekulize_(clear_aromatic_flags=None)¶
Convert aromatic bonds to an explicit Kekule form in place.
This is the in-place version of
with_kekulized_bonds().
- largest_fragment()¶
Return the largest connected fragment.
- maccs_fingerprint(n_bits=166)¶
Return a MACCS fingerprint using RDKit bit-identical key generation.
COSMolKit exposes the public 166-bit projection of RDKit’s raw 167-bit MACCS vector, where RDKit bit 0 is unused and raw bits 1..166 map to public bits 0..165.
- classmethod mol_from_binary(data)¶
Deserialize a molecule from COSMolKit binary data.
- mol_to_binary()¶
Serialize the molecule to COSMolKit binary form.
- murcko_scaffold()¶
Return the Murcko scaffold.
- net_scaffold()¶
Return the net scaffold.
- num_atoms()¶
Return the number of atoms.
- num_bonds()¶
Return the number of bonds.
- num_conformers()¶
Return the number of stored 3D conformers.
- pattern_fingerprint(n_bits=2048, tautomeric=False)¶
Return the source-backed Pattern fingerprint without mutating the molecule.
tautomeric=Trueenables the pinned source’s tautomer-aware structural hashing.n_bitsmust be greater than zero. Query-bearing molecules follow the source’s Pattern-specific query suppression rules, and all calls reuse one compile-once table of 13 built-in SMARTS queries.RDKit identifies Pattern fingerprint version 1.0.0 as experimental. COSMolKit preserves that upstream metadata while validating this ordinary-molecule boundary exactly. The source’s inert
atomCountsandsetOnlyBitsarguments are intentionally omitted, and the distinctMolBundleintersection overload is not represented by this scalar API.
- perceive_stereochemistry()¶
Perceive stereochemistry and validate stereo processing for this molecule.
- classmethod read_mol(path, sanitize=None, coordinate_dim='auto', *, remove_hs=None, strict_parsing=None)¶
Read one molecule from an MDL molfile.
The parser follows RDKit
MolFromMolBlockrecord boundaries: it reads the molfile CTAB through the firstM ENDline and ignores unread trailing text, including SDF data fields and$$$$record separators. Useread_sdf()orSdfDatasetwhen SDF data fields must be parsed.- Parameters:
path (str) – Molfile path.
sanitize (bool, optional) – Optional molecule preparation flag.
remove_hs (bool, optional) – Optional hydrogen removal flag.
strict_parsing (bool, optional) – Optional strict molfile parsing flag.
coordinate_dim ({"auto", "2d", "3d"}, optional) – Coordinate interpretation mode.
"auto"preserves the molfile header.
- classmethod read_mol2(path, *, sanitize=True, remove_hs=True, variant='corina', cleanup_substructures=True)¶
Read one molecule from a Tripos MOL2 file.
The reader follows the source-ported RDKit
Mol2FileToMol/MolFromMol2Fileprofile. The exposed parameters map to RDKitMol2ParserParams:sanitize,removeHs,variant, andcleanupSubstructures. The only currently supported variant is"corina", matching RDKit’s public enum.- Parameters:
path (str) – MOL2 file path.
sanitize (bool, optional) – Run RDKit-style MOL2 sanitization after parsing.
remove_hs (bool, optional) – Remove explicit hydrogens during MOL2 finalization.
variant ({"corina"}, optional) – MOL2 atom-type definition profile.
cleanup_substructures (bool, optional) – Run RDKit-style cleanup of common MOL2 substructures before charge assignment when formal charges are not present.
- classmethod read_mol2_from_str(mol2_text, *, sanitize=True, remove_hs=True, variant='corina', cleanup_substructures=True)¶
Read one molecule from a Tripos MOL2 string.
The reader follows the source-ported RDKit
Mol2BlockToMol/MolFromMol2Blockprofile. The exposed parameters map to RDKitMol2ParserParams:sanitize,removeHs,variant, andcleanupSubstructures. The only currently supported variant is"corina", matching RDKit’s public enum.
- classmethod read_mol_from_str(mol_text, sanitize=None, coordinate_dim='auto', *, remove_hs=None, strict_parsing=None)¶
Read one molecule from an MDL molfile string.
The parser follows RDKit
MolFromMolBlockrecord boundaries: it reads the molfile CTAB through the firstM ENDline and ignores unread trailing text, including SDF data fields and$$$$record separators. Useread_sdf_from_str()when SDF data fields must be parsed.
- classmethod read_sdf(path, sanitize=None, coordinate_dim='auto', *, remove_hs=None, strict_parsing=None)¶
Read the first molecule record from an SDF file.
This uses the SDF reader, so SDF data fields after the molfile
M ENDline are parsed as record metadata. Useread_mol()for RDKitMolFromMolBlock-style molfile-only parsing.- Parameters:
path (str) – SDF file path.
sanitize (bool, optional) – Optional molecule preparation flag.
remove_hs (bool, optional) – Optional hydrogen removal flag.
strict_parsing (bool, optional) – Optional strict SDF parsing flag.
coordinate_dim ({"auto", "2d", "3d"}, optional) – Coordinate interpretation mode.
"auto"preserves the molfile header.
- classmethod read_sdf_from_str(sdf_text, sanitize=None, coordinate_dim='auto', *, remove_hs=None, strict_parsing=None)¶
Read one molecule from an SDF record string.
This uses the SDF reader, so data fields after the molfile
M ENDline are parsed as SDF record metadata. Useread_mol_from_str()for RDKitMolFromMolBlock-style molfile-only parsing that ignores trailing SDF text.
- remove_hydrogens_(sanitize=None)¶
Remove explicit hydrogens in place.
This is the in-place version of
without_hydrogens().
- set_2d_coordinates_(coords, *, z_policy='ignore')¶
Set 2D coordinates in place.
coordsmust be a numeric array-like object with shape(num_atoms, 2)or(num_atoms, 3). Three-column input follows the samez_policyvalues aswith_2d_coordinates(coords=...).
- set_3d_coordinates_(coords, conformer_index=0)¶
Replace an existing 3D conformer’s coordinates in place.
coordsmust be a numeric array-like object with shape(num_atoms, 3).
- set_only_3d_conformer_(coords, *, is_3d=True)¶
Replace all 3D conformers in place with exactly one conformer.
coordsmust be a numeric array-like object with shape(num_atoms, 3).
- stereoisomer_count(options=None)¶
Return the source-defined upper-bound stereoisomer count.
- stereoisomers(options=None)¶
Return a lazy iterator over source-ordered stereoisomers.
The source molecule remains unchanged.
optionsdefaults toStereoisomerOptions(). Arandom.Randominstance or subclass supplied throughoptions.randis consumed lazily through itsgetrandbits()method; other seed objects follow Pythonrandom.Random(seed)semantics.
- tetrahedral_stereo()¶
Return ordered tetrahedral stereo ligand records.
Each record is
(center_atom_index, ordered_ligands). The ligand order is the stereochemical value, not a plain adjacency listing: opposite tetrahedral configurations can have the same ligand set but different ligand order. Equivalent even permutations are canonicalized to one numeric representative; odd permutations remain distinct because they encode the opposite handedness.Nonedoes not mean that a ligand is absent. It represents a hydrogen ligand that exists chemically but is implicit in the current molecule graph and therefore has no atom index.Specification: https://github.com/cosmol-studio/COSMolKit/blob/main/dev/tetrahedral_stereo.md
- to_2d_sdf_string(format=None, include_stereo=True, kekulize=True)¶
Return the molecule as a 2D SDF record string.
If the molecule does not already have 2D coordinates, they are generated for this export. The original
Moleculevalue is left unchanged.
- to_3d_sdf_string(format=None, include_stereo=True, kekulize=True)¶
Return the molecule as a 3D SDF record string.
The molecule must already have a 3D conformer, for example from a 3D SDF record.
- to_cx_smarts(isomeric_smarts=True)¶
Return a CXSMARTS string for this molecule or compiled query.
- to_inchi(options='')¶
Return the molecule’s InChI without mutating the molecule.
- to_inchi_key(options='')¶
Return the molecule’s InChIKey without mutating the molecule.
- to_pdb_block(conf_id=Ellipsis, flavor=0)¶
Return a PDB block string.
- to_png(width=300, height=300)¶
Render the molecule to PNG bytes.
- to_smarts(isomeric_smarts=True, rooted_at_atom=None)¶
Return a SMARTS string for this molecule or compiled query.
rooted_at_atomselects the traversal root when provided.
- to_smiles(isomeric_smiles=True, canonical=True, kekule=False, clean_stereo=True, all_bonds_explicit=False, all_hs_explicit=False, include_dative_bonds=True, ignore_atom_map_numbers=False, rooted_at_atom=None)¶
Return a SMILES string.
- Parameters:
isomeric_smiles (bool, default True) – Include stereochemical and isotopic information when available.
canonical (bool, default True) – Return a canonical SMILES when supported.
kekule (bool, default False) – Write aromatic systems using Kekule bond notation.
clean_stereo (bool, default True) – Normalize stereo annotations before writing.
all_bonds_explicit (bool, default False) – Write explicit bond symbols.
all_hs_explicit (bool, default False) – Write explicit hydrogens.
include_dative_bonds (bool, default True) – Include dative bond notation.
ignore_atom_map_numbers (bool, default False) – Omit atom map numbers from canonical decisions.
rooted_at_atom (int, optional) – Start traversal from a selected atom index.
- to_svg(width=300, height=300)¶
Render the molecule to an SVG string.
- topological_fingerprint(min_path=1, max_path=7, fp_size=2048, num_bits_per_feature=2, use_hs=True, target_density=0.0, min_size=128, branched_paths=True, use_bond_order=True, atom_invariants=None, from_atoms=None)¶
Return the source-backed RDKit topological fingerprint.
The parameters and bit ordering follow the pinned
RDKFingerprintMolboundary. Unsupported argument ranges raiseValueError.
- topological_fingerprint_with_output(min_path=1, max_path=7, fp_size=2048, num_bits_per_feature=2, use_hs=True, target_density=0.0, min_size=128, branched_paths=True, use_bond_order=True, atom_invariants=None, from_atoms=None, atom_bits=False, bit_info=False)¶
Return an RDKit topological fingerprint with typed optional provenance.
atom_bitsandbit_inforequest the corresponding sourceAdditionalOutputbranches. Provenance bit identifiers retain the source pre-folding values when density folding is enabled.
- with_2d_coordinates(coords=None, *, z_policy='ignore')¶
Return a new molecule with 2D coordinates.
When
coordsis omitted, COSMolKit computes 2D coordinates. Whencoordsis provided, it must be a numeric array-like object with shape(num_atoms, 2)or(num_atoms, 3). Three-column input usesz_policy:"ignore"Use x/y columns and ignore z values.
"require_zero"Require all z values to be zero.
"error"Reject three-column input.
- with_3d_conformer(params=None)¶
Return a new molecule with one generated 3D conformer.
- Parameters:
params (EmbedParameters, optional) – Distance-geometry embedding parameters. The default is
EmbedParameters.etkdg_v3().- Returns:
A new molecule value containing one additional 3D conformer.
- Return type:
- with_3d_conformer_result(params=None)¶
Return an embedding result object for one generated 3D conformer.
The result keeps the embedded molecule, the returned conformer id, and the final parameter snapshot so callers can inspect status and failure counters without relying on side effects on the input
EmbedParametersobject.
- with_3d_conformers(num_confs, params=None)¶
Return a new molecule with multiple generated 3D conformers.
- Parameters:
num_confs (int) – Number of conformers to request.
params (EmbedParameters, optional) – Distance-geometry embedding parameters.
- Returns:
A new molecule value containing the generated 3D conformers.
- Return type:
- with_3d_conformers_result(num_confs, params=None)¶
Return an embedding result object for multiple generated 3D conformers.
The result keeps the embedded molecule, the kept conformer ids, and the final parameter snapshot so callers can inspect pruning and tracked failures without reconstructing that state manually.
- with_3d_coordinates(coords, conformer_index=0)¶
Return a new molecule with an existing 3D conformer’s coordinates replaced.
coordsmust be a numeric array-like object with shape(num_atoms, 3). The source molecule must already have a conformer atconformer_index.
- with_added_3d_conformer(coords, *, is_3d=True)¶
Return a new molecule with one additional 3D conformer.
coordsmust be a numeric array-like object with shape(num_atoms, 3).
- with_aligned_conformers(params=None)¶
Return a molecule with aligned conformers and the ordered source RMS report.
- with_alignment_to(reference, params=None)¶
Return a new molecule aligned to
referencetogether with its alignment result.The source and reference molecules remain unchanged.
- with_chiral_tags_from_structure(conf_id=-1, replace_existing_tags=True)¶
Return a new molecule with atom chiral tags assigned from 3D coordinates.
The selected conformer, atom and bond ordering, coordinates, and unrelated properties are preserved.
conf_id=-1selects the default conformer. Existing atom chiral tags are replaced unlessreplace_existing_tagsis false. The original molecule is left unchanged, including on error.This stable API has exact full-state parity with RDKit 2026.03.1
assignChiralTypesFrom3Dacross all 77 fixed oracle records. The covered surface includes tetrahedral C/S/Se centers, enabled square-planar, trigonal-bipyramidal, and octahedral centers, property updates, no-op paths, and defined errors. It does not performassignStereochemistryFrom3D, 3D double-bond direction or E/Z assignment, CIP orchestration, or distinct-substituent validation.
- with_cip_labels(atoms=None, bonds=None, max_recursive_iterations=0)¶
Return a new molecule with source-backed modern CIP labels assigned.
When both
atomsandbondsare omitted or empty, the full molecule is labeled. Once either selection is non-empty, an omitted or empty category selects no entries, matching the pinned RDKit wrapper dispatch. Assignment is molecular-context dependent; query descriptors frommol.atoms()[i]ormol.bonds()[i]after this call.
- with_cleared_3d_conformers()¶
Return a new molecule with all 3D conformers removed.
2D coordinates, topology, and properties are preserved.
- with_hydrogens()¶
Return a new molecule with explicit hydrogens added.
The original
Moleculevalue is left unchanged.
- with_kekulized_bonds(clear_aromatic_flags=None)¶
Return a new molecule with aromatic bonds converted to an explicit Kekule form.
The original
Moleculevalue is left unchanged.
- with_mmff_optimized(mmff_variant='MMFF94', max_iters=200, non_bonded_thresh=100.0, conf_id=Ellipsis, ignore_interfrag_interactions=True)¶
Return an MMFF optimization result with a new optimized molecule value.
The source molecule is not mutated. The molecule must already contain a 3D conformer. Supported variants follow the Rust core parser, including
"MMFF94"and"MMFF94S".
- with_mmff_optimized_confs(num_threads=1, max_iters=1000, mmff_variant='MMFF94', non_bonded_thresh=10.0, ignore_interfrag_interactions=True)¶
Return MMFF optimization results for all 3D conformers as a new molecule value.
- with_only_3d_conformer(coords, *, is_3d=True)¶
Return a new molecule with exactly one 3D conformer.
Existing 3D conformers are removed before
coordsis stored. This is the COSMolKit equivalent of RDKitRemoveAllConformers(); AddConformer(...)for manual coordinate assignment.
- with_uff_optimized(max_iters=1000, vdw_thresh=10.0, conf_id=Ellipsis, ignore_interfrag_interactions=True)¶
Return a UFF optimization result with a new optimized molecule value.
The source molecule is not mutated. The molecule must already contain a 3D conformer, for example from a 3D SDF, MOL, MOL2, or XYZ input.
- with_uff_optimized_confs(num_threads=1, max_iters=1000, vdw_thresh=10.0, ignore_interfrag_interactions=True)¶
Return UFF optimization results for all 3D conformers as a new molecule value.
- without_hydrogens(sanitize=None)¶
Return a new molecule with explicit hydrogens removed.
The original
Moleculevalue is left unchanged.
- write_png(path, width=300, height=300)¶
Write a PNG depiction to a file.
- write_sdf(path, format=None, include_stereo=True, kekulize=True)¶
Write the molecule as one SDF record.
- write_sdf_to_directory(directory, file_name=None, format=None, include_stereo=True, kekulize=True)¶
Write the molecule as one SDF record inside a directory.
- Returns:
The output path.
- Return type:
str
- write_svg(path, width=300, height=300)¶
Write an SVG depiction to a file.
- class cosmolkit.MoleculeBatch¶
An ordered collection of molecules for batch workflows.
MoleculeBatchkeeps input order and supports construction, transformation, filtering, rendering, and SDF export across many molecules. Methods that transform molecules return a new batch.Parameters such as
errorscontrol invalid-record handling:"raise"raises an exception when any record fails."keep"keeps failed records and exposes them througherrors(). Export methods write valid records and count invalid records as skipped in the returned report.
Examples
Construct a batch with
MoleculeBatch.from_smiles_list(), choose anerrorsmode for invalid records, and usewith_parallel_jobs()when the same worker count should apply to later batch operations.- dg_bounds_matrix_list(n_jobs=None, progress_bar=None)¶
Return distance-geometry bounds matrices for all valid records.
- errors()¶
Return structured errors collected for invalid records.
- filter_valid()¶
Return a batch containing only valid molecules.
- fingerprint_atom_pair_list(n_bits=2048, min_distance=1, max_distance=30, use_2d=True, include_chirality=False, count_simulation=True, count_bounds=None, num_bits_per_feature=1, from_atoms=None, ignore_atoms=None, conformer_id=Ellipsis, custom_atom_invariants=None, n_jobs=None, progress_bar=None)¶
Return ordered explicit-bit AtomPair fingerprints for valid batch records.
Invalid input records remain
Noneat their original positions.
- fingerprint_layered_list(layers=4294967295, min_path=1, max_path=7, fp_size=2048, atom_counts=None, set_only_bits=None, branched_paths=True, from_atoms=None, n_jobs=None, progress_bar=None)¶
Return ordered Layered fingerprints for valid batch records.
Invalid input records remain
Noneat their original positions. All fingerprints delegate to the same Rust scalar core.
- fingerprint_layered_with_output_list(layers=4294967295, min_path=1, max_path=7, fp_size=2048, atom_counts=None, set_only_bits=None, branched_paths=True, from_atoms=None, n_jobs=None, progress_bar=None)¶
Return ordered Layered fingerprints and optional updated atom counts.
Invalid input records remain
Noneat their original positions.
- fingerprint_morgan_list(radius=2, n_bits=2048, include_chirality=False, use_bond_types=True, count_simulation=False, count_bounds=None, only_nonzero_invariants=False, include_redundant_environments=False, from_atoms=None, ignore_atoms=None, custom_atom_invariants=None, custom_bond_invariants=None, atom_invariants_generator=None, atom_invariants_include_ring_membership=True, bond_invariants_generator=None, bond_invariants_use_bond_types=True, bond_invariants_use_chirality=False, num_bits_per_feature=1, n_jobs=None, progress_bar=None)¶
Return Morgan fingerprints for valid batch records.
Invalid records are returned as
Nonein their original positions.
- fingerprint_morgan_with_output_list(radius=2, n_bits=2048, include_chirality=False, use_bond_types=True, count_simulation=False, count_bounds=None, only_nonzero_invariants=False, include_redundant_environments=False, from_atoms=None, ignore_atoms=None, custom_atom_invariants=None, custom_bond_invariants=None, atom_invariants_generator=None, atom_invariants_include_ring_membership=True, bond_invariants_generator=None, bond_invariants_use_bond_types=True, bond_invariants_use_chirality=False, num_bits_per_feature=1, n_jobs=None, progress_bar=None)¶
Return Morgan fingerprints and additional output for valid batch records.
Invalid records are returned as
Nonein their original positions.
- classmethod from_smiles_list(smiles, sanitize=None, errors=None, n_jobs=None)¶
Create a batch from a list of SMILES strings.
- Parameters:
smiles (list[str]) – Input SMILES strings.
sanitize (bool, optional) – Optional molecule preparation flag. COSMolKit applies the available preparation behavior during construction.
errors ({"raise", "keep"}, optional) – Invalid-record handling mode. The default is
"raise".n_jobs (int, optional) – Number of worker threads to use.
Noneuses the default scheduler.
- Returns:
A batch preserving the input order for valid and kept records.
- Return type:
- invalid_count()¶
Return the number of invalid records.
- invalid_mask()¶
Return a boolean mask indicating which records are invalid.
- parallel_jobs()¶
Return the batch-level default worker count, or
Nonewhen unset.
- pattern_fingerprint_list(n_bits=2048, tautomeric=False, n_jobs=None, progress_bar=None)¶
Return ordered Pattern fingerprints for valid batch records.
Invalid input records remain
Noneat their original positions. The fingerprints use the same source-backed core and compile-once Pattern query table asMolecule.pattern_fingerprint. This ordered batch operation returns one result per input; it is not RDKit’s distinctMolBundleintersection overload.
- progress_bar()¶
Return the batch-level progress-bar default, or
Nonewhen unset.
- classmethod read_sdf(path, errors=None, n_jobs=None, progress_bar=False, coordinate_dim='auto', *, sanitize=None, remove_hs=None, strict_parsing=None)¶
Read all molecule records from an SDF file into a batch.
- Parameters:
path (str) – SDF file path.
errors ({"raise", "keep"}, optional) – Invalid-record handling mode. The default is
"raise".n_jobs (int, optional) – Number of worker threads to use for batch construction.
progress_bar (bool, optional) – Show a Rust-side progress bar while records are parsed. This builds a lightweight record index first so the total is known.
coordinate_dim ({"auto", "2d", "3d"}, optional) – Coordinate interpretation mode.
"auto"preserves the molfile header.
- classmethod read_sdf_records_from_str(sdf_text, errors=None, n_jobs=None, coordinate_dim='auto', *, sanitize=None, remove_hs=None, strict_parsing=None)¶
Read all molecule records from an SDF string.
- Parameters:
sdf_text (str) – SDF text containing one or more records.
errors ({"raise", "keep"}, optional) – Invalid-record handling mode. The default is
"raise".n_jobs (int, optional) – Number of worker threads to use.
coordinate_dim ({"auto", "2d", "3d"}, optional) – Coordinate interpretation mode.
"auto"preserves the molfile header.
- sanitize(strict=None, errors=None, n_jobs=None, progress_bar=None)¶
Return a sanitized batch.
- Parameters:
strict (bool, optional) – Optional strictness flag for available validation steps.
errors ({"raise", "keep"}, optional) – Invalid-record handling mode.
n_jobs (int, optional) – Number of worker threads to use.
- to_images(out_dir, format=None, size=None, n_jobs=None, errors=None, report_path=None, filenames=None, progress_bar=None)¶
Write molecule depictions to a directory.
- Parameters:
out_dir (str) – Output directory.
format ({"png", "svg"}, optional) – Image format. The default is
"png".size (tuple[int, int], optional) – Output image size as
(width, height).n_jobs (int, optional) – Number of worker threads to use.
errors ({"raise", "keep"}, optional) – Export error handling mode.
report_path (str, optional) – Write a JSON or CSV error report.
filenames (list[str | None], optional) – Per-record output filenames. Names are relative to
out_dir; missing extensions are filled fromformat.
- Returns:
Export summary.
- Return type:
- to_list()¶
Return batch records as a Python list.
Valid records become
Moleculeobjects and invalid records becomeNone.
- to_sdf(path, format=None, errors=None, n_jobs=None, report_path=None, progress_bar=None)¶
Write valid molecules to an SDF file.
- Parameters:
path (str) – Output SDF path.
format ({"auto", "v2000", "v3000"}, optional) – SDF output format.
errors ({"raise", "keep"}, optional) – Export error handling mode.
n_jobs (int, optional) – Number of worker threads to use.
report_path (str, optional) – Write a JSON or CSV error report.
- to_sdf_files(out_dir, format=None, errors=None, n_jobs=None, report_path=None, filenames=None, progress_bar=None)¶
Write each valid molecule to its own SDF file in a directory.
- Parameters:
out_dir (str) – Output directory.
format ({"auto", "v2000", "v3000"}, optional) – SDF output format.
errors ({"raise", "keep"}, optional) – Export error handling mode.
n_jobs (int, optional) – Number of worker threads to use.
report_path (str, optional) – Write a JSON or CSV error report.
filenames (list[str | None], optional) – Per-record output filenames. Names are relative to
out_dir; missing extensions are written as.sdf.
- to_smiles_list(isomeric_smiles=True, canonical=True, kekule=False, clean_stereo=True, all_bonds_explicit=False, all_hs_explicit=False, include_dative_bonds=True, ignore_atom_map_numbers=False, rooted_at_atom=None, n_jobs=None, progress_bar=None)¶
Return one SMILES string per record.
Invalid records are returned as
Nonewhen they are kept in the batch.- Parameters:
isomeric_smiles (bool, default True) – Include stereochemical and isotopic information when available.
canonical (bool, default True) – Return canonical SMILES when enabled.
kekule (bool, default False) – Write aromatic systems in Kekule form.
clean_stereo (bool, default True) – Normalize stereo output where possible.
all_bonds_explicit (bool, default False) – Write explicit bond symbols.
all_hs_explicit (bool, default False) – Write explicit hydrogens.
include_dative_bonds (bool, default True) – Include dative bond notation.
ignore_atom_map_numbers (bool, default False) – Omit atom map numbers from canonical decisions.
rooted_at_atom (int, optional) – Start traversal from a selected atom index.
n_jobs (int, optional) – Number of worker threads to use.
- to_svg_list(width=300, height=300, n_jobs=None, progress_bar=None)¶
Render each valid molecule to an SVG string.
- valid_count()¶
Return the number of valid records.
- valid_mask()¶
Return a boolean mask indicating which records are valid.
- with_2d_coordinates(errors=None, n_jobs=None, progress_bar=None)¶
Return a new batch with 2D coordinates computed for each valid molecule.
- with_hydrogens(errors=None, n_jobs=None, progress_bar=None)¶
Return a new batch with explicit hydrogens added to each valid molecule.
- with_kekulized_bonds(clear_aromatic_flags=None, errors=None, n_jobs=None, progress_bar=None)¶
Return a new batch with aromatic bonds converted to an explicit Kekule form.
- with_parallel_jobs(n_jobs)¶
Return a new batch configured to use this worker count by default.
Pass
Noneto clear the batch-level default and let rayon decide. Method-leveln_jobsarguments still override this setting for that one call.
- with_progress_bar(progress_bar)¶
Return a new batch configured to show Rust-side progress bars by default.
Pass
Noneto clear the batch-level default. Method-levelprogress_bararguments still override this setting for that one call.
- without_hydrogens(errors=None, n_jobs=None, progress_bar=None)¶
Return a new batch with explicit hydrogens removed from each valid molecule.
- class cosmolkit.MoleculeEdit¶
An explicit molecule editing context.
Use
Molecule.edit()to create an editor, apply changes, and callcommit()to receive a newMolecule.Examples
Create an editor with
mol.edit(), apply atom and bond changes, then callcommit()to produce a newMolecule.- add_atom(element)¶
Add an atom by element symbol and return its atom index.
- add_bond(begin, end, order)¶
Add a bond between two atom indices.
- Parameters:
begin (int) – Begin atom index.
end (int) – End atom index.
order ({"single", "double", "triple", "aromatic", "dative", "unspecified"}) – Bond order.
- commit(sanitize=None)¶
Commit staged edits and return a new molecule.
- set_atom_charge(atom_index, charge)¶
Set an atom formal charge.
- class cosmolkit.ResidueCode(value)¶
- class cosmolkit.ResidueInfo¶
Gemmi-derived tabulated residue information.
Use
ResidueInfo.code()andResidueInfo.kind()for enum matching instead of matching raw residue-name strings.- code()¶
Return the tabulated residue code as
ResidueCode.
- kind()¶
Return the Gemmi residue-info kind as
ResidueInfoKind.
- kind_name()¶
Return the Gemmi residue-info kind name.
- name()¶
Return the tabulated residue name.
- class cosmolkit.ResidueInfoKind(value)¶
- class cosmolkit.SdfDataset¶
Indexed, seekable SDF dataset.
SdfDatasetbuilds a lightweight in-memory index of record byte ranges first. After opening,len(dataset)is cheap,dataset[i]parses only that record,dataset[:n]returns aMoleculeBatch, anddataset.batches(size=...)yields boundedMoleculeBatchchunks.Use
MoleculeBatch.read_sdf()when you intentionally want the whole file in memory. UseSdfDatasetfor large seekable files where random access, metadata inspection, or chunked processing matter.
- class cosmolkit.SdfReader¶
Forward-only SDF reader for one-pass workflows.
Use
SdfReaderfor non-indexed stream-style processing. For seekable files where random access or accurate record-count progress matters, preferSdfDataset.
- class cosmolkit.SdfRecord¶
One parsed SDF record returned by
SdfDataset.The record exposes the parsed molecule plus SDF data fields.
- class cosmolkit.SdfRecordMetadata¶
Lightweight metadata for one indexed SDF record.
Metadata is available from
SdfDatasetwithout parsing the molecule graph.
- cosmolkit.calc_chi_0(molecule)¶
Return the graph-degree Chi0 descriptor.
- cosmolkit.calc_chi_1(molecule)¶
Return the graph-degree Chi1 descriptor.
- cosmolkit.calc_chi_nn(molecule, order, force=False)¶
Return the order-N principal-quantum connectivity descriptor.
- cosmolkit.calc_chi_nv(molecule, order, force=False)¶
Return the order-N valence connectivity descriptor.
- cosmolkit.calc_crippen_descriptors(molecule, include_hs=True, force=False)¶
Return
(logp, molar_refractivity)using the RDKit Crippen descriptor path.The chemical graph and user-visible molecule properties are not mutated. The source-compatible computed Crippen descriptor cache may be populated on the input molecule, matching RDKit’s property-cache behavior.
- cosmolkit.calc_exact_mol_wt(molecule, only_heavy=False)¶
Return the RDKit-aligned exact molecular weight.
Set
only_heavy=Trueto omit hydrogen atoms and implicit hydrogen mass. The input molecule is not mutated.
- cosmolkit.calc_fraction_csp3(molecule)¶
Return the RDKit-aligned fraction of carbon atoms that are sp3 without mutating the molecule.
- cosmolkit.calc_hall_kier_alpha(molecule)¶
Return the Hall-Kier alpha descriptor.
- cosmolkit.calc_hall_kier_alpha_with_contributions(molecule)¶
Return Hall-Kier alpha and atom-index-aligned contributions.
- cosmolkit.calc_kappa_1(molecule)¶
Return the first Kappa shape index.
- cosmolkit.calc_kappa_2(molecule)¶
Return the second Kappa shape index.
- cosmolkit.calc_kappa_3(molecule)¶
Return the third Kappa shape index.
- cosmolkit.calc_labute_asa(molecule, include_hydrogens=True, force=False)¶
Return the Labute approximate surface area.
- cosmolkit.calc_labute_asa_contributions(molecule, include_hydrogens=True, force=False)¶
Return Labute ASA, atom-index-aligned contributions, and the hydrogen contribution.
- cosmolkit.calc_lipinski_hba(molecule)¶
Return the direct Lipinski nitrogen/oxygen acceptor count.
- cosmolkit.calc_lipinski_hbd(molecule)¶
Return the direct Lipinski nitrogen/oxygen donor-site count.
- cosmolkit.calc_mol_formula(molecule, separate_isotopes=False, abbreviate_h_isotopes=True)¶
Return the RDKit-aligned molecular formula.
separate_isotopesemits isotope-specific terms. When enabled,abbreviate_h_isotopeswrites hydrogen-2 and hydrogen-3 as D and T. The input molecule is not mutated.
- cosmolkit.calc_mol_wt(molecule, only_heavy=False)¶
Return the RDKit-aligned average molecular weight.
Set
only_heavy=Trueto omit hydrogen atoms and implicit hydrogen mass. The input molecule is not mutated.
- cosmolkit.calc_mqns(molecule)¶
Return the fixed-order 42-component molecular quantum number vector.
- cosmolkit.calc_num_aliphatic_carbocycles(molecule)¶
Return the aliphatic carbocycle count.
- cosmolkit.calc_num_aliphatic_heterocycles(molecule)¶
Return the aliphatic heterocycle count.
- cosmolkit.calc_num_aliphatic_rings(molecule)¶
Return the aliphatic-ring count.
- cosmolkit.calc_num_amide_bonds(molecule)¶
Return the amide-bond count.
- cosmolkit.calc_num_aromatic_carbocycles(molecule)¶
Return the aromatic carbocycle count.
- cosmolkit.calc_num_aromatic_heterocycles(molecule)¶
Return the aromatic heterocycle count.
- cosmolkit.calc_num_aromatic_rings(molecule)¶
Return the RDKit-aligned aromatic-ring count without mutating the molecule.
- cosmolkit.calc_num_atom_stereo_centers(molecule)¶
Return the number of possible atom stereocenters.
- cosmolkit.calc_num_atoms(molecule)¶
Return the total atom count including implicit hydrogens.
- cosmolkit.calc_num_bridgehead_atoms(molecule)¶
Return the bridgehead-atom count.
- cosmolkit.calc_num_hba(molecule)¶
Return the RDKit-aligned hydrogen-bond acceptor count without mutating the molecule.
- cosmolkit.calc_num_hbd(molecule)¶
Return the RDKit-aligned hydrogen-bond donor count without mutating the molecule.
- cosmolkit.calc_num_heavy_atoms(molecule)¶
Return the heavy-atom count.
- cosmolkit.calc_num_heteroatoms(molecule)¶
Return the heteroatom count.
- cosmolkit.calc_num_heterocycles(molecule)¶
Return the heterocycle count.
- cosmolkit.calc_num_rings(molecule)¶
Return the SSSR ring count.
- cosmolkit.calc_num_rotatable_bonds(molecule, mode='default')¶
Return the RDKit-aligned rotatable-bond count.
modemust be"default","non_strict","strict", or"strict_linkages". The input molecule is not mutated.
- cosmolkit.calc_num_saturated_carbocycles(molecule)¶
Return the saturated carbocycle count.
- cosmolkit.calc_num_saturated_heterocycles(molecule)¶
Return the saturated heterocycle count.
- cosmolkit.calc_num_saturated_rings(molecule)¶
Return the saturated-ring count.
- cosmolkit.calc_num_spiro_atoms(molecule)¶
Return the spiro-atom count.
- cosmolkit.calc_num_unspecified_atom_stereo_centers(molecule)¶
Return the number of possible atom stereocenters without a specified chiral tag.
- cosmolkit.calc_phi(molecule)¶
Return the molecular flexibility Phi descriptor.
- cosmolkit.calc_qed(molecule)¶
Return the RDKit-aligned quantitative estimate of drug-likeness without mutating the molecule.
- cosmolkit.calc_slogp_vsa(molecule, bins=None, force=False)¶
Return the SlogP-VSA vector using default or caller-provided bin boundaries.
- cosmolkit.calc_slogp_vsa_1(molecule)¶
Return SlogP-VSA bin 1.
- cosmolkit.calc_slogp_vsa_10(molecule)¶
Return SlogP-VSA bin 10.
- cosmolkit.calc_slogp_vsa_11(molecule)¶
Return SlogP-VSA bin 11.
- cosmolkit.calc_slogp_vsa_12(molecule)¶
Return SlogP-VSA bin 12.
- cosmolkit.calc_slogp_vsa_2(molecule)¶
Return SlogP-VSA bin 2.
- cosmolkit.calc_slogp_vsa_3(molecule)¶
Return SlogP-VSA bin 3.
- cosmolkit.calc_slogp_vsa_4(molecule)¶
Return SlogP-VSA bin 4.
- cosmolkit.calc_slogp_vsa_5(molecule)¶
Return SlogP-VSA bin 5.
- cosmolkit.calc_slogp_vsa_6(molecule)¶
Return SlogP-VSA bin 6.
- cosmolkit.calc_slogp_vsa_7(molecule)¶
Return SlogP-VSA bin 7.
- cosmolkit.calc_slogp_vsa_8(molecule)¶
Return SlogP-VSA bin 8.
- cosmolkit.calc_slogp_vsa_9(molecule)¶
Return SlogP-VSA bin 9.
- cosmolkit.calc_smr_vsa(molecule, bins=None, force=False)¶
Return the SMR-VSA vector using default or caller-provided bin boundaries.
- cosmolkit.calc_smr_vsa_1(molecule)¶
Return SMR-VSA bin 1.
- cosmolkit.calc_smr_vsa_10(molecule)¶
Return SMR-VSA bin 10.
- cosmolkit.calc_smr_vsa_2(molecule)¶
Return SMR-VSA bin 2.
- cosmolkit.calc_smr_vsa_3(molecule)¶
Return SMR-VSA bin 3.
- cosmolkit.calc_smr_vsa_4(molecule)¶
Return SMR-VSA bin 4.
- cosmolkit.calc_smr_vsa_5(molecule)¶
Return SMR-VSA bin 5.
- cosmolkit.calc_smr_vsa_6(molecule)¶
Return SMR-VSA bin 6.
- cosmolkit.calc_smr_vsa_7(molecule)¶
Return SMR-VSA bin 7.
- cosmolkit.calc_smr_vsa_8(molecule)¶
Return SMR-VSA bin 8.
- cosmolkit.calc_smr_vsa_9(molecule)¶
Return SMR-VSA bin 9.
- cosmolkit.calc_tpsa(molecule, force=False, include_sandp=False)¶
Return the RDKit-aligned topological polar surface area.
Set
include_sandp=Trueto include sulfur and phosphorus contributions. The input molecule is not mutated.
- cosmolkit.element_from_symbol(symbol)¶
Return the element represented by a canonical or source-recognized symbol.
- cosmolkit.expand_one_letter(code, kind)¶
Expand a one-letter amino-acid, RNA, or DNA residue code using Gemmi’s table.
- cosmolkit.expand_one_letter_sequence(seq, kind)¶
Expand a one-letter amino-acid, RNA, or DNA residue sequence using Gemmi’s table.
- cosmolkit.expand_protein_one_letter(code)¶
Expand a deprecated Gemmi protein one-letter residue code alias.
- cosmolkit.expand_protein_one_letter_string(seq)¶
Expand a deprecated Gemmi protein one-letter residue sequence alias.
- cosmolkit.find_tabulated_residue(name)¶
Return Gemmi-derived tabulated residue information for a residue name.
- cosmolkit.find_tabulated_residue_idx(name)¶
Return the Gemmi tabulated residue index for a residue name.
- cosmolkit.get_element_info(atomic_number)¶
Return source-aligned periodic-table metadata for an atomic number.
- cosmolkit.get_residue_info(idx)¶
Return Gemmi-derived tabulated residue information by table index.
- cosmolkit.get_substruct_match(mol, query, use_chirality=False, use_query_query_matches=False)¶
Return the first molecule-query substructure match, if present.
The ordinary-molecule SMARTS and substructure boundary is covered by the pinned RDKit parity corpus. Reaction and database/container SMARTS remain outside this API.
- cosmolkit.get_substruct_matches(mol, query, uniquify=True, use_chirality=False, use_query_query_matches=False, max_matches=1000)¶
Return molecule-query substructure matches.
The ordinary-molecule SMARTS and substructure boundary is covered by the pinned RDKit parity corpus. Reaction and database/container SMARTS remain outside this API.
- cosmolkit.get_substruct_matches_with_params(mol, query, max_matches=1000, uniquify=True, final_match=None, atom_match=None, bond_match=None)¶
Return molecule-query substructure matches with explicit limits.
The ordinary-molecule SMARTS and substructure boundary is covered by the pinned RDKit parity corpus. Reaction and database/container SMARTS remain outside this API.
- cosmolkit.has_substruct_match(mol, query, recursion_possible=True, use_chirality=False, use_query_query_matches=False)¶
Return whether a molecule contains a molecule-query substructure.
The query must be the canonical query-bearing
Moleculereturned byparse_smarts. The ordinary-molecule SMARTS and substructure boundary is covered by the pinned RDKit parity corpus; reaction and database/container SMARTS remain outside this API.
- cosmolkit.inchi_to_key(inchi)¶
Generate an InChIKey directly from an InChI string.
- cosmolkit.mmff_has_all_molecule_params(mol)¶
Return whether MMFF94 parameters are available for a molecule.
- cosmolkit.mmff_optimize_molecule(mol, mmff_variant='MMFF94', max_iters=200, non_bonded_thresh=100.0, conf_id=Ellipsis, ignore_interfrag_interactions=True)¶
Optimize one existing 3D conformer with MMFF and return a result object.
The input molecule is not mutated. Supported variants include
"MMFF94"and"MMFF94S".
- cosmolkit.mmff_optimize_molecule_confs(mol, num_threads=1, max_iters=1000, mmff_variant='MMFF94', non_bonded_thresh=10.0, ignore_interfrag_interactions=True)¶
Optimize all existing 3D conformers with MMFF and return a result object.
The input molecule is not mutated. Supported variants include
"MMFF94"and"MMFF94S".
- cosmolkit.mol_from_binary(data)¶
Deserialize a molecule from COSMolKit binary bytes.
- cosmolkit.mol_to_binary(mol)¶
Serialize a molecule to COSMolKit binary bytes.
Use
mol_to_binary()/mol_from_binary()or the matchingMoleculemethods when you need an exact COSMolKit round-trip format instead of text IO.
- cosmolkit.parse_smarts(smarts, merge_hs=False, replacements=None)¶
Compile SMARTS text into a query-bearing
Molecule.
- cosmolkit.residue_code_from_name(name)¶
Return the Gemmi tabulated residue code for a residue name.
- cosmolkit.uff_has_all_molecule_params(mol)¶
Return whether UFF parameters are available for every atom in a molecule.
- cosmolkit.uff_optimize_molecule(mol, max_iters=1000, vdw_thresh=10.0, conf_id=Ellipsis, ignore_interfrag_interactions=True)¶
Optimize one existing 3D conformer with UFF and return a result object.
The input molecule is not mutated.
- cosmolkit.uff_optimize_molecule_confs(mol, num_threads=1, max_iters=1000, vdw_thresh=10.0, ignore_interfrag_interactions=True)¶
Optimize all existing 3D conformers with UFF and return a result object.
The input molecule is not mutated.
InChI API¶
The public InChI surface is limited to four scalar calls. Nonfatal source
diagnostics are emitted as cosmolkit.InchiDiagnosticWarning instances
with level and message fields. Failures expose operation, kind,
and detail through cosmolkit.InchiError; allocation and unsupported
state failures use dedicated subclasses.
Exact parity applies to behavior defined by pinned official InChI v1.07.5 and
RDKit 2026.03.1. The official C NormalizeAndCompare initial-buffer
allocation-failure path is undefined; COSMolKit returns a deterministic
InchiAllocationError instead of claiming an exact C result. MolBlock,
SDF/V3000, IXA, AuxInfo, INCHIGEN, version-query, and extended-polymer InChI
entry points are not part of this public surface.
Typical usage keeps molecule conversion on cosmolkit.Molecule:
.. code-block:: python
from cosmolkit import Molecule, inchi_to_key
molecule = Molecule.from_smiles(“CCO”) inchi = molecule.to_inchi() key = molecule.to_inchi_key() assert inchi_to_key(inchi) == key
restored = Molecule.from_inchi(inchi) assert restored is not None
- cosmolkit.Molecule.to_inchi(options='')¶
Return the molecule’s InChI string without mutating it.
- cosmolkit.Molecule.to_inchi_key(options='')¶
Return the molecule’s InChIKey without mutating it.
- cosmolkit.inchi_to_key(inchi)¶
Return the InChIKey for an InChI string, or
Nonewhen the source API rejects the input.
- classmethod cosmolkit.Molecule.from_inchi(inchi, *, sanitize=True, remove_hs=True)¶
Return a
cosmolkit.Molecule, orNonewhen the source API returns no graph.
Structural API¶
- class cosmolkit.MmcifOutputGroups(all=True)¶
Category switches for BioStructure mmCIF output; all categories are enabled by default.
- class cosmolkit.MmcifWriteOptions¶
Options for canonical Gemmi-aligned BioStructure mmCIF serialization.
- class cosmolkit.BioStructure¶
A complete biomolecular structural value.
BioStructureretains all modeled models, chains, residues, atoms, entities, ligands, waters, nucleic acids, assemblies, and crystallographic metadata. UseProteinonly when an amino-acid-only projection is intended, and useMoleculewhen the desired result is a cheminformatics graph.- atoms()¶
Return all atoms as shared read-only views.
- chains()¶
Return all chains as shared read-only views.
- entities()¶
Return all structural entities as shared read-only views.
- classmethod from_mmcif(path)¶
Read an mmCIF file into the complete biomolecular structural model.
- classmethod from_mmcif_str(text, path='input.cif')¶
Read mmCIF text into the complete biomolecular structural model.
- classmethod from_pdb(path)¶
Read a PDB file into the complete biomolecular structural model.
- classmethod from_pdb_str(text)¶
Read PDB text into the complete biomolecular structural model.
- classmethod from_structure_str(text, path='input')¶
Read structural text after detecting PDB, mmCIF, or mmJSON format.
- input_format()¶
Return the detected input format name.
- models()¶
Return all coordinate models as shared read-only views.
- name()¶
Return the structure name or input data-block name.
- num_atoms()¶
Return the number of atoms of every modeled kind.
- num_chains()¶
Return the number of chains across all models.
- num_entities()¶
Return the number of structural entities.
- num_models()¶
Return the number of coordinate models.
- num_residues()¶
Return the number of residues of every modeled kind.
- protein()¶
Return an amino-acid-only
Proteinprojection.The returned value intentionally excludes ligands, waters, and nucleic acids; the source
BioStructureremains unchanged.
- residues()¶
Return all residues, including ligands, waters, and nucleic acids.
- to_mmcif(options=None)¶
Serialize this complete structural model as Gemmi-aligned mmCIF without mutating it.
- to_molecule(sanitize=True, remove_hs=True, flavor=0, proximity_bonding=True)¶
Convert the structural rows to a cheminformatics
Molecule.This is an explicit, potentially lossy model conversion. It follows the same RDKit-compatible graph construction options as
Molecule.from_pdb_block().
- write_mmcif(path, options=None)¶
Write this complete structural model as Gemmi-aligned mmCIF without mutating it.
- class cosmolkit.StructureModel¶
- class cosmolkit.StructureChain¶
- class cosmolkit.StructureResidue¶
- class cosmolkit.StructureAtom¶
- class cosmolkit.StructureEntity¶
Protein Projection API¶
- class cosmolkit.Protein¶
A protein-focused structural value.
Proteinis the default high-level protein API. It keeps amino-acid residues and excludes ligands, nucleic acids, and waters by default.Use
Protein.from_pdb()for PDB files,Protein.from_pdb_str()for PDB text,Protein.from_mmcif()for mmCIF files, andProtein.from_mmcif_str()for mmCIF text.- atoms()¶
Return all protein atoms as
ProteinAtomviews.
- chains()¶
Return the protein chains as
ProteinChainviews.
- classmethod from_mmcif(path)¶
Read an mmCIF file as a protein-focused structural value.
The result uses the same protein projection as
Protein.from_pdb().
- classmethod from_mmcif_str(text, path)¶
Read mmCIF text as a protein-focused structural value.
pathis used for format context and diagnostic messages.
- classmethod from_pdb(path)¶
Read a PDB file as a protein-focused structural value.
The returned
Proteinkeeps amino-acid residues and exposes chain, residue, and atom traversal. UseMolecule.from_pdb_block()instead when the desired result is a RDKit-compatible molecule conversion.
- classmethod from_pdb_str(text)¶
Read PDB text as a protein-focused structural value.
This is the in-memory counterpart to
Protein.from_pdb().
- num_atoms()¶
Return the number of protein atoms.
- num_chains()¶
Return the number of protein chains.
- num_models()¶
Return the number of coordinate models in the protein structure.
- num_residues()¶
Return the number of protein residues.
- residues()¶
Return all protein residues as
ProteinResidueviews.
- class cosmolkit.ProteinChain¶
- atoms()¶
Return atoms belonging to this chain.
- index()¶
Return the zero-based chain index.
- kind()¶
Return the chain kind, for example
Protein.
- residues()¶
Return residues belonging to this chain.
- class cosmolkit.ProteinResidue¶
- atoms()¶
Return atoms belonging to this residue.
- canonical_one_letter_code()¶
Return the canonical one-letter amino-acid code, if table-defined.
- code()¶
Return the Gemmi tabulated residue code as
ResidueCode.
- fasta_code()¶
Return Gemmi’s FASTA code for this residue.
- index()¶
Return the zero-based residue index.
- info()¶
Return the Gemmi-derived tabulated residue information.
- is_modified_amino_acid()¶
Return whether this is a non-standard amino acid in the residue table.
- is_standard()¶
Return whether Gemmi marks this residue as standard.
- kind()¶
Return the residue kind.
- name()¶
Return the residue name, for example
ALA.
- one_letter_code()¶
Return Gemmi’s one-letter code for this residue.
- parent_standard_code()¶
Return the table-defined standard parent residue code, if available.
- class cosmolkit.ProteinAtom¶
- atomic_num()¶
Return the atomic number.
- element()¶
Return the atom’s element as
Element.
- element_symbol()¶
Return the canonical element symbol.
- index()¶
Return the zero-based atom index.
- name()¶
Return the atom name, for example
CA.
- position()¶
Return
(x, y, z)coordinates, orNonewhen absent.