RDMolecule
A simple interchange format for RDKit molecules
NullContext: NullContext
default_new_coord_alignment_method: str
implicit_hydrogen_to_conformer_method: str
default_fragment_placement_method: str
different_fragment_embedding_distance: int
draw_options_mapping: dict
drawing_defaults: dict
default_draw_options: dict
default_up_vector: tuple
default_right_vector: tuple
default_view_vector: tuple
default_conformer_compression: str
default_tag_byte_size: int
default_tag_byte_encoding: int
__init__(self, rdconf, charge=None):
LLM Docstring
Wrap an RDKit conformer (and its owning mol) as an RDMolecule.
rdconf:Chem.Conformerthe RDKit conformer
charge:int | Nonethe molecular charge
@property
rdmol(self):
LLM Docstring
The underlying RDKit Mol object (recovered from the conformer if needed).
:returns:Chem.Molthe RDKit mol
@property
atoms(self):
LLM Docstring
The element symbols of the atoms, in order.
:returns:list[str]the atom symbols
@property
isotopes(self):
Isotope mass numbers, parallel to atoms; 0 denotes an unlabeled atom.
@property
atom_labels(self):
Atom labels with isotope identity, including D, T, C13 and explicit C12.
@property
masses(self):
AtomData masses with isotope identity preserved (in atomic mass units).
@classmethod
to_rdkit_atom(cls, atom, isotope=None):
Convert an element/isotope label, atomic number or RDKit atom to an Atom.
Explicit isotope values override the label: None retains/infers its isotope, 0 clears the isotope label, and positive integers specify a mass number. Plain element symbols/names remain unlabeled.
@staticmethod
from_rdkit_atom(atom):
Return an isotope-aware atom label without discarding explicit primary isotopes.
@classmethod
get_bonds(cls, mol):
@property
bonds(self):
LLM Docstring
The bonds as [begin_atom, end_atom, order] triples.
:returns:list[list]the bond list
@property
coords(self):
LLM Docstring
The atomic Cartesian coordinates (Angstroms). Setting this writes new positions onto the conformer.
:returns:np.ndarraythe coordinates
@property
rings(self):
LLM Docstring
The atom-index tuples of the rings found by RDKit’s ring perception.
:returns:tuplethe ring atom indices
@property
meta(self):
LLM Docstring
The molecule’s RDKit properties as a dict.
:returns:dictthe property dict
copy(self):
LLM Docstring
Return a copy of this molecule, carrying over the current conformer and charge.
:returns:RDMoleculethe copied molecule
@property
charges(self):
LLM Docstring
The per-atom Gasteiger partial charges (computed on access).
:returns:list[float]the partial charges
@property
formal_charges(self):
LLM Docstring
The per-atom formal charges.
:returns:list[int]the formal charges
@classmethod
quiet_errors(cls, verbose=False):
LLM Docstring
Return a context manager that suppresses RDKit’s C++ log output, unless
verbose is set (in which case a no-op context is returned).
verbose:booldon’t suppress logging
:returns:_the (log-blocking or no-op) context manager
@classmethod
chem_api(cls):
LLM Docstring
Return the RDKit Chem submodule.
:returns:modulethe
Chemmodule
@classmethod
guess_rdmol_bonds(cls, rdmol, charge=None, determine_orders=True, in_place=False):
LLM Docstring
Perceive the bonds (and, optionally, bond orders) of a mol from its atomic coordinates, falling back to connectivity-only perception when order determination fails.
rdmol:Chem.Molthe mol
charge:int | Nonethe molecular charge (inferred if omitted)
determine_orders:boolalso perceive bond orders
in_place:boolmodify the mol in place rather than copying
:returns:Chem.Molthe mol with perceived bonds
@classmethod
sanitize_rdkit_mol(cls, rdmol, sanitize_ops=None):
@classmethod
from_rdmol(cls, rdmol, conf_id=0, charge=None, guess_bonds=False, sanitize=True, add_implicit_hydrogens=False, sanitize_ops=None, allow_generate_conformers=False, num_confs=1, optimize=False, take_min=True, force_field_type='mmff'):
LLM Docstring
Build an RDMolecule from an RDKit mol, adding hydrogens and optionally guessing
bonds, sanitizing, and generating conformers.
rdmol:Chem.Molthe source mol
conf_id:intthe conformer id to use
charge:int | Nonethe molecular charge (inferred if omitted)
guess_bonds:boolperceive bonds from geometry
sanitize:boolrun RDKit sanitization
add_implicit_hydrogens:booladd implicit (not just explicit) hydrogens
sanitize_ops:Anysanitization operation flags
allow_generate_conformers:boolgenerate conformers if none exist
num_confs:intnumber of conformers to generate
optimize:boolforce-field optimize generated conformers
take_min:boolkeep only the lowest-energy generated conformer
force_field_type:strthe force field for optimization
:returns:RDMoleculethe wrapped molecule
@classmethod
resolve_bond_type(cls, t):
LLM Docstring
Map a numeric bond order to the corresponding RDKit BondType (handling the
aromatic/half-integer cases).
t:floatthe numeric bond order
:returns:Chem.BondTypethe RDKit bond type
@classmethod
from_coords(cls, atoms, coords, bonds=None, charge=None, formal_charges=None, guess_bonds=None, add_implicit_hydrogens=False, implicit_hydrogen_method=None, distance_matrix_tol=0.05, num_confs=None, optimize=False, take_min=None, force_field_type='mmff', confgen_opts=None, sanitize=False, rdmol=None, isotopes=None, **opts):
LLM Docstring
Build an RDMolecule from atoms, coordinates, and (optional) bonds, optionally
adding implicit hydrogens (placed by conformer generation) and guessing bonds.
atoms:Sequence[str | int | Chem.Atom]element/isotope labels (including D/T), atomic numbers or RDKit atoms
isotopes:Sequence[int | None] | Noneoptional mass numbers parallel to atoms; None entries infer from the atom, 0 clears its isotope label, and positive integers override it
coords:np.ndarraythe Cartesian coordinates
bonds:Sequence | Nonethe bonds as
[i, j(, order)]charge:int | Nonethe molecular charge
formal_charges:Sequence | Noneper-atom formal charges
guess_bonds:bool | Noneperceive bonds from geometry (defaults to when no bonds given)
add_implicit_hydrogens:booladd implicit hydrogens
implicit_hydrogen_method:str | Nonehow to place added hydrogens (
'align'/'initial'/'builtin')distance_matrix_tol:floattolerance for distance constraints when aligning
num_confs:int | Nonenumber of conformers to generate
optimize:boolforce-field optimize generated conformers
take_min:bool | Nonekeep only the lowest-energy conformer
force_field_type:strthe force field for optimization
confgen_opts:dict | Noneextra conformer-generation options
sanitize:boolrun sanitization
rdmol:Chem.Mol | Noneoptional RDKit molecular graph to copy without losing atom/bond metadata; atoms, supplied bonds and formal charges must agree
:returns:RDMolecule | listthe wrapped molecule (or a list, when multiple conformers are kept)
@classmethod
from_mol(cls, mol, coord_unit='Angstroms', guess_bonds=None):
LLM Docstring
Build an RDMolecule from a generic molecule object, converting its coordinates
to Angstroms.
mol:Anythe source molecule
coord_unit:strthe source coordinate unit
guess_bonds:bool | Noneperceive bonds from geometry
:returns:RDMoleculethe wrapped molecule
@classmethod
from_sdf(cls, sdf_string, which=0):
LLM Docstring
Build an RDMolecule from an SDF file path or string.
sdf_string:strthe SDF file path or content
which:intthe index of the entry to read
:returns:RDMoleculethe wrapped molecule
@classmethod
get_confgen_opts(cls, version='v3', use_experimental_torsion_angle_prefs=True, use_basic_knowledge=True, **opts):
LLM Docstring
Build an RDKit ETKDG conformer-generation parameter object of the requested version, applying the torsion/knowledge flags and any extra options.
version:strthe ETKDG version (
'v1'/'v2'/'v3')use_experimental_torsion_angle_prefs:booluse experimental torsion prefs
use_basic_knowledge:booluse basic chemical knowledge
opts:Anyextra parameters set on the params object (camel-cased)
:returns:objectthe parameter object
@classmethod
parse_smiles(cls, smiles, sanitize=False, parse_name=True, allow_cxsmiles=True, strict_cxsmiles=True, remove_hydrogens=False, add_implicit_hydrogens=None, reorder_from_atom_map=False, replacements=None, quiet=False, **opts):
LLM Docstring
Parse a SMILES (or CXSMILES) string into an RDKit mol, with control over sanitization, hydrogen handling, and atom-map-based reordering.
smiles:strthe SMILES string
sanitize:boolrun sanitization
parse_name:boolparse a trailing molecule name
allow_cxsmiles:boolallow CXSMILES extensions
strict_cxsmiles:boolfail on bad CXSMILES rather than ignoring
remove_hydrogens:boolremove explicit hydrogens
add_implicit_hydrogens:bool | str | Noneadd hydrogens (or
'full'to also re-enable implicit Hs)reorder_from_atom_map:boolrenumber atoms by their atom-map numbers
replacements:dict | NoneSMILES token replacements
quiet:boolsuppress RDKit logging
:returns:Chem.Mol | Nonethe parsed mol, or
Noneon failure
@classmethod
from_smiles(cls, smiles, sanitize=False, parse_name=True, allow_cxsmiles=True, strict_cxsmiles=True, remove_hydrogens=False, replacements=None, add_implicit_hydrogens=False, call_add_hydrogens=True, conf_id=None, num_confs=None, optimize=False, take_min=True, force_field_type='mmff', reorder_from_atom_map=True, confgen_opts=None, check_tag=True, coords=None, conf_tag=None, conformer_encoder=None, **opts):
LLM Docstring
Build an RDMolecule from a SMILES string (or file), embedding a conformer
(generated, or decoded from a conformer tag / supplied coordinates).
smiles:strthe SMILES string or file path
sanitize:boolrun sanitization
parse_name:boolparse a trailing molecule name
allow_cxsmiles:boolallow CXSMILES extensions
strict_cxsmiles:boolfail on bad CXSMILES
remove_hydrogens:boolremove explicit hydrogens
replacements:dict | NoneSMILES token replacements
add_implicit_hydrogens:booladd implicit hydrogens
call_add_hydrogens:boolcall
AddHsbefore embeddingconf_id:int | Nonethe conformer id to use
num_confs:int | Nonenumber of conformers to generate
optimize:boolforce-field optimize generated conformers
take_min:boolkeep only the lowest-energy conformer
force_field_type:strthe force field for optimization
reorder_from_atom_map:boolrenumber atoms by atom-map number
confgen_opts:dict | Noneextra conformer-generation options
check_tag:boolsplit off a trailing
_-delimited conformer tagcoords:np.ndarray | Noneexplicit coordinates to use instead of generating a conformer
conf_tag:str | Nonean explicit conformer tag to decode
:returns:RDMolecule | listthe wrapped molecule (or list, for multiple conformers)
@classmethod
from_base_mol(cls, mol, conf_id=None, num_confs=None, optimize=False, take_min=None, force_field_type='mmff', confgen_opts=None, **mol_opts):
LLM Docstring
Build an RDMolecule from an RDKit mol, using an existing conformer when
available and otherwise generating one.
mol:Chem.Molthe source mol
conf_id:int | Nonethe conformer id to use
num_confs:int | Nonenumber of conformers to generate
optimize:boolforce-field optimize generated conformers
take_min:bool | Nonekeep only the lowest-energy conformer
force_field_type:strthe force field for optimization
confgen_opts:dict | Noneextra conformer-generation options
mol_opts:Anyextra options forwarded to
from_rdmol:returns:RDMolecule | listthe wrapped molecule (or list)
@classmethod
generate_conformers_for_mol(cls, mol, *, num_confs=1, optimize=False, take_min=True, force_field_type='mmff', add_implicit_hydrogens=False, distance_constraints=None, initial_coordinates=None, fragment_placement_method=None, fragments=None, embedding_mol=None, verbose=False, **opts):
LLM Docstring
Generate one or more conformers for a mol via RDKit’s ETKDG embedding, handling disconnected fragments (embedded separately and placed), distance constraints, fixed initial coordinates, optional force-field optimization, and lowest-energy selection.
mol:Chem.Molthe mol to embed (modified in place; conformers are added)
num_confs:intnumber of conformers to generate
optimize:boolforce-field optimize the conformers
take_min:boolreturn only the lowest-energy conformer id
force_field_type:strthe force field for optimization/selection
add_implicit_hydrogens:booladd implicit hydrogens before embedding
distance_constraints:dict | list | Nonepairwise distance bounds (or a full bounds matrix)
initial_coordinates:dict | Sequence | Nonefixed starting coordinates for some/all atoms
fragment_placement_method:str | Callable | Nonehow to place disconnected fragments
fragments:list | Noneprecomputed fragment atom groups
embedding_mol:Chem.Mol | Nonea hydrogen-added mol to embed into
verbose:booldon’t suppress RDKit logging
:returns:int | listthe generated conformer id (or list of ids)
@classmethod
from_no_conformer_molecule(cls, mol, *, conf_id=None, num_confs=1, optimize=False, take_min=True, force_field_type='mmff', add_implicit_hydrogens=False, confgen_opts=None, **etc):
LLM Docstring
Generate conformer(s) for a mol that has none, then wrap the result(s) as
RDMolecule(s).
mol:Chem.Molthe source mol
conf_id:int | Nonea specific conformer id to keep (disables optimization)
num_confs:intnumber of conformers to generate
optimize:boolforce-field optimize the conformers
take_min:boolkeep only the lowest-energy conformer
force_field_type:strthe force field for optimization
add_implicit_hydrogens:booladd implicit hydrogens
confgen_opts:dict | Noneextra conformer-generation options
etc:Anyextra options forwarded to
from_rdmol:returns:RDMolecule | listthe wrapped molecule (or list)
to_smiles(self, remove_hydrogens=None, remove_implicit_hydrogens=None, include_tag=False, canonical=False, compute_stereo=False, remove_stereo=False, preserve_atom_order=False, return_reordering=False, binary=False, conformer_encoder=None, coords=None, mol=None, **opts):
LLM Docstring
Serialize the molecule to a SMILES string, with options for hydrogen/stereo handling, atom-order preservation, and appending a conformer tag encoding the 3D geometry.
remove_hydrogens:bool | Noneremove explicit hydrogens
remove_implicit_hydrogens:bool | Noneremove only implicit hydrogens
include_tag:boolappend a
_-delimited conformer tagcanonical:boolemit canonical SMILES
compute_stereo:boolassign stereochemistry from the 3D coordinates first
remove_stereo:boolstrip stereochemistry
preserve_atom_order:boolkeep the current atom ordering
binary:boolreturn/encode the tag in binary form
coords:np.ndarray | Nonecoordinates to encode in the tag (defaults to the current ones)
mol:Chem.Mol | Nonean explicit mol to serialize (defaults to this one)
:returns:str | bytesthe SMILES string (optionally with a conformer tag)
to_inchi(self, remove_hydrogens=None, remove_implicit_hydrogens=None, include_tag=False, canonical=False, compute_stereo=False, remove_stereo=False, preserve_atom_order=False, return_reordering=False, binary=False, conformer_encoder=None, coords=None, mol=None, options='', log_level=None, treat_warning_as_error=False, **opts):
Serialize the molecule to a standard InChI string.
remove_implicit_hydrogens:AnyNone/Truekeep the default behavior, where a conformer tag only encodes the heavy atoms InChI numbers;Falsealso encodes the hydrogens in the tag
to_inchi_key(self, options='', mol=None):
Serialize the molecule as a standard InChIKey.
options:strcommand-line options forwarded to the InChI library
mol:Chem.Mol | Nonean explicit mol to serialize (defaults to this one)
:returns:strthe standard InChIKey
find_substructure(self, query):
LLM Docstring
Return all substructure matches of a SMARTS query in the molecule.
query:strthe SMARTS query
:returns:tuplethe matching atom-index tuples
get_automorphisms(self, use_chirality=True, max_automorphisms=100000, include_identity=True):
LLM Docstring
Enumerate this molecule’s graph automorphisms: every atom-index permutation
under which the molecule maps onto itself (same elements, same bonds, and –
when use_chirality – the same stereocenters/bond stereo). Obtained via
RDKit’s self-substructure-match trick (mol.GetSubstructMatches(mol,
uniquify=False)); uniquify=False is essential here, since the whole point
is to get every internally-symmetric relabeling, not just one representative
per atom set.
use_chirality=True (the default) is what keeps this from pairing an atom
with its mirror-image position at a stereocenter – an achiral match would
happily call a molecule “automorphic” onto its own enantiomer/diastereomer at
a stereocenter, which then silently produces the wrong labeling. This only
does anything useful if stereochemistry has actually been perceived on the
mol (e.g. via Chem.AssignStereochemistryFrom3D for a 3D-derived structure,
or already set from a stereo SMILES) – if it hasn’t, this filters nothing.
Molecules with many independent local symmetries (several free-rotor methyls,
several equivalent branches, …) can have very large automorphism groups
(the factors multiply: three equivalent methyls alone contribute a factor of
3! x (3!)*3 = 1296 if graph symmetry alone is considered). max_automorphisms
is a hard cap so that case fails loudly instead of silently truncating the
search (RDKit’s own maxMatches truncates *silently by default, which would
otherwise bias the result towards whatever RDKit happened to enumerate first).
use_chirality:boolrespect stereocenters/bond stereo when matching
max_automorphisms:intraise rather than silently truncate if the automorphism group is larger than this
include_identity:boolmake sure the identity permutation is included (it always should be mathematically; this just guards against RDKit corner cases so callers can rely on “no permutation” always being tried)
:returns:np.ndarraythe automorphisms, shape
(n_automorphisms, n_atoms)
match_atoms(self, other, use_chirality=True):
LLM Docstring
Find one atom map from other onto this molecule via substructure matching
(self.rdmol.GetSubstructMatch(other.rdmol)), i.e. the RDKit index that this
molecule’s graph assigns to each atom of other.
This is only one valid map when the two molecules have any internal graph
symmetry – e.g. it might match other’s first methyl hydrogen against any
of the three symmetric hydrogens in a corresponding methyl on self. That’s
fine: composing this single map with the automorphism group of self (see
get_automorphisms/get_alignment_permutation_candidates) recovers every
other equally-valid map, so there’s no need to search for “the right” base
match here.
other:RDMoleculethe molecule to map onto this one
use_chirality:boolrespect stereocenters/bond stereo when matching
:returns:np.ndarraythe atom map,
map[i]= this molecule’s atom index forother’s atomi
get_alignment_permutation_candidates(self, other, use_chirality=True, max_automorphisms=100000):
LLM Docstring
Build the full set of graph-consistent atom maps from other onto this
molecule, suitable for McUtils.Numputils.eckart_permutation’s
permutation_candidates=.
One base map is found with match_atoms, then composed with every
automorphism of this molecule (get_automorphisms): if base[i] is a valid
label in this molecule’s numbering for other’s atom i, and aut is any
automorphism of this molecule, then aut[base[i]] is also a valid label
for other’s atom i – composing an isomorphism with an automorphism of
its codomain gives another isomorphism. This is exactly the full set of valid
atom maps between the two molecules (it’s the coset Aut(self) . base), so
nothing is missed and nothing invalid is included.
other:RDMoleculethe molecule to map onto this one
use_chirality:boolrespect stereocenters/bond stereo when matching
max_automorphisms:intforwarded to
get_automorphisms:returns:np.ndarraycandidate atom maps, shape
(n_candidates, n_atoms)
find_alignment_permutation(self, other, masses=None, use_chirality=True, max_automorphisms=100000, return_rmsd=False, **eckart_opts):
LLM Docstring
Find the atom permutation of other that best superimposes it onto this
molecule under an Eckart embedding, searching every graph-automorphism-
consistent atom map rather than trusting whichever one RDKit’s substructure
matcher happens to return first.
This is McUtils.Numputils.eckart_permutation driven with
permutation_candidates from get_alignment_permutation_candidates, so the
search is exact for whatever automorphisms RDKit finds (bounded by
max_automorphisms), rather than the approximate per-group Hungarian
matching eckart_permutation falls back to without an explicit candidate set.
other:RDMoleculethe molecule to permute/align
masses:np.ndarray | Noneper-atom masses (defaults to this molecule’s own)
use_chirality:boolrespect stereocenters/bond stereo when matching
max_automorphisms:intforwarded to
get_automorphismsreturn_rmsd:boolalso return the winning Eckart RMSD
eckart_opts:Anyextra options forwarded to
eckart_permutation(e.g.proper_rotation):returns:np.ndarray | tuplethe optimal permutation of
other’s atoms (and, if requested, the RMSD);perm[j]is the index, inother’s current numbering, of the atom that belongs at positionjto match this molecule’s atomj– i.e.other.coords[perm]is the reordered structure – matchingPsience.Molecools.Molecule.permute_atoms’s convention directly
align_to(self, ref, masses=None, use_chirality=True, max_automorphisms=100000, proper_rotation=False, return_rmsd=False):
LLM Docstring
Return a copy of this molecule renumbered into ref’s atom order and
rigid-body aligned onto it, using whichever graph-automorphism-consistent
atom map gives the best Eckart RMSD (see find_alignment_permutation).
Both the atom/bond bookkeeping (via RDKit’s RenumberAtoms) and the
coordinates are updated, so the result is a fully self-consistent
RDMolecule in ref’s numbering – not just reordered coordinates next to
a stale, unrenumbered graph.
ref:RDMoleculethe reference molecule to align onto
masses:np.ndarray | Noneper-atom masses (defaults to
ref’s own)use_chirality:boolrespect stereocenters/bond stereo when matching
max_automorphisms:intforwarded to
get_automorphismsproper_rotation:boolrestrict the final rigid-body fit to proper rotations
return_rmsd:boolalso return the achieved Eckart RMSD
:returns:RDMolecule | tuplethe aligned, renumbered copy (and, if requested, the RMSD)
@classmethod
apply_smarts_to_mol(cls, mol, pattern, remove_hydrogens=True, readd_hydrogens=True):
LLM Docstring
Apply a SMARTS reaction transform to a mol, running the reaction and reassembling the products while preserving atom mapping and re-adding hydrogens consistently.
mol:Chem.Molthe reactant mol
pattern:str | objectthe SMARTS reaction (string or reaction object)
remove_hydrogens:boolstrip hydrogens before reacting
readd_hydrogens:boolre-add hydrogens to the products
:returns:list[Chem.Mol]the product mols
permute(self, perm):
apply_smarts(self, tf):
LLM Docstring
Apply a SMARTS reaction transform to this molecule, returning the products as
RDMolecules carrying the current coordinates.
tf:str | objectthe SMARTS reaction
:returns:list[RDMolecule]the product molecules
@classmethod
take_mol_fragment(cls, mol, inds, conf_id=None):
LLM Docstring
Build a sub-mol from the given atom indices (with the bonds among them), optionally carrying over a conformer’s coordinates.
mol:Chem.Molthe source mol
inds:Sequence[int]the atom indices to keep
conf_id:int | Nonea conformer id whose coordinates to copy
:returns:Chem.Molthe sub-mol
break_bonds(self, bonds, add_dummies=False, reguess_bonds=True, new_charge=None, return_fragments=False):
LLM Docstring
Break the given bonds and return the resulting (fragmented) molecule, carrying over coordinates and optionally re-perceiving bond orders.
bonds:Sequencethe
(i, j)bonds to breakadd_dummies:booladd dummy atoms at the broken bonds
reguess_bonds:boolre-perceive bond orders afterward
return_fragments:boolunused flag
:returns:RDMoleculethe fragmented molecule
add_bonds(self, bonds, new_charge=None, sanitize=False, adjust_charges=False, compute_stereo=False, reguess_bonds=True):
LLM Docstring
Add the given bonds and return the resulting (merged) molecule, carrying over coordinates and optionally re-perceiving bond orders.
bonds:Sequencethe
(i, j)bonds to add, or(i, j, order)if you want to specify a bond order/type per-bond (overridesbond_typefor that bond)reguess_bonds:boolre-perceive bond orders afterward
return_fragments:boolunused flag
:returns:RDMoleculethe molecule with new bonds added
@classmethod
fragment_rdmol(cls, mol, inds):
LLM Docstring
Build a sub-mol from the given atom indices and the bonds among them.
mol:Chem.Molthe source mol
inds:Sequence[int]the atom indices to keep
:returns:Chem.Molthe sub-mol
@classmethod
fragment_rdmol_on_bonds(cls, mol, bonds, addDummies=True):
LLM Docstring
Fragment a mol by breaking the given bonds, returning a mapping from each fragment’s atom-index tuple to its sub-mol (with atom maps restored).
mol:Chem.Molthe source mol
bonds:Sequencethe
(i, j)bonds to break (by atom-map number)addDummies:booladd dummy atoms at the broken bonds
:returns:dictthe
{fragment_indices: sub_mol}mapping
get_atom_neighbors(self, i, n=1, mol=None, graph=None):
LLM Docstring
Return the labels of the atoms within n bonds of a given atom.
i:intthe central atom index
n:intthe neighborhood radius (in bonds)
mol:Chem.Mol | Nonean explicit mol (defaults to this one)
graph:Anya precomputed edge graph
:returns:listthe neighbor atom labels
draw(self, figure=None, background=None, atom_palette=None, remove_atom_numbers=None, remove_hydrogens=True, display_atom_numbers=False, format='svg', drawer=None, coords=None, use_coords=False, align_2d=None, view_settings=None, plot_range=None, atom_labels=None, atom_label_placement='auto', bond_labels=None, blend_mixed_bonds=True, highlight_atoms=None, highlight_bonds=None, highlight_atom_colors=None, highlight_bond_colors=None, highlight_atom_radii=None, highlight_bond_radii=None, highlight_bond_width_multiplier=None, atom_radii=None, bond_radius=None, allow_radius_rescaling=True, draw_coords=None, label_offset=1, conf_id=None, include_save_buttons=False, no_free_type=None, postdraw=None, return_splits=None, radius_to_range_scaling=None, **draw_opts):
LLM Docstring
Draw the molecule in 2D (SVG/PNG), with extensive control over hydrogen removal, 2D-coordinate generation and alignment, atom/bond labels and highlights, ring highlighting, and save buttons.
figure:Anyan existing figure/drawer to draw into
background:Anythe background color
remove_atom_numbers:bool | Nonestrip atom-map numbers from the drawing
remove_hydrogens:boolhide hydrogens
display_atom_numbers:boolannotate atoms with their indices
format:str'svg'or'png'drawer:Anyan explicit drawing function
coords:np.ndarray | Noneexplicit 2D coordinates to draw at
use_coords:booldraw using the molecule’s own coordinates (projected)
align_2d:bool | Nonealign the generated 2D coordinates to the view
view_settings:dict | None3D view settings for coordinate alignment
plot_range:tuple | Nonea fixed drawing range
atom_labels:Anyper-atom label overrides
atom_label_placement:Any'auto'places dictionary labels with nokeyat RDKit’s native atom-note positions.'rdkit'forces that placement;'coords'keeps coordinate annotations.bond_labels:Anyper-bond label overrides
blend_mixed_bonds:boolblend colors on bonds between differently colored atoms
highlight_atoms:Anyatoms to highlight
highlight_bonds:Anybonds to highlight
highlight_atom_colors:Anyper-atom highlight colors
highlight_bond_colors:Anyper-bond highlight colors
highlight_atom_radii:Anyper-atom highlight radii
highlight_bond_radii:Anyper-bond highlight radii
highlight_bond_width_multiplier:Anyhighlight bond-width multiplier
atom_radii:Anyper-atom radii
bond_radius:Anythe bond radius
allow_radius_rescaling:boolallow radii to rescale with the plot range
draw_coords:Anyextra coordinate annotations
highlight_rings:Anyrings to highlight
label_offset:Anythe annotation label offset
conf_id:int | Nonethe conformer id
include_save_buttons:boolinclude save buttons in the output
no_free_type:bool | Nonedisable FreeType font rendering
postdraw:Callable | Nonea callback invoked after drawing
return_splits:bool | Nonealso return drawing element split metadata
radius_to_range_scaling:Anyradius-to-range scaling factor
draw_opts:Anyextra drawing options
:returns:objectthe rendered drawing
plot(self, conf_id=None, image_size=(450, 450), **opts):
LLM Docstring
Display an interactive 3D rendering of the molecule (via RDKit’s IPython 3D console).
conf_id:int | Nonethe conformer id (defaults to the current one)
image_size:tuplethe
(width, height)of the viewopts:Anyextra drawing options
:returns:objectthe 3D display
conformer_smiles_tag(self, coords=None, graph=None, zmatrix=None, encoder=None, byte_size=None, byte_encoding=None, conformer_encoder=None, binary=False, include_zmatrix=False):
LLM Docstring
Encode the molecule’s 3D geometry into a compact string tag (a Z-matrix of the canonical-fragment internal coordinates, packed and base-N encoded) suitable for appending to a SMILES string.
coords:np.ndarray | Nonethe coordinates to encode (defaults to the current ones)
graph:Anythe molecular edge graph (built if omitted)
zmatrix:Anyan explicit Z-matrix connectivity (built if omitted)
encoder:str | Callable | Nonethe value encoder (
'plain'/'compressed'/'precision'or a callable)byte_size:int | Nonethe per-value bit width. If omitted and
conformer_encoderis given, inferred fromconformer_encoder.byte_size; otherwise falls back todefault_tag_byte_size.byte_encoding:int | Callable | Nonethe base-N text encoding (16/32/64/85)
conformer_encoder:ConformerEncoder | Nonea pre-built ConformerEncoder to use for the ‘compressed’/’precision’ encoders (e.g. one built via
ConformerEncoder.from_distribution_files, so real fitted angle/dihedral distributions are used instead of the plain uniform default). Ignored for the ‘plain’ encoder or a custom callableencoder. If omitted, a plain uniform ConformerEncoder is built fresh frombyte_sizeeach call.binary:boolreturn raw bytes rather than text
include_zmatrix:boolalso return the encoded Z-matrix connectivity
:returns:str | bytes | tuplethe conformer tag (and Z-matrix data if requested)
@classmethod
conformer_from_smiles_tag(cls, tag, graph, decoder=None, byte_size=None, byte_encoding=None, zmatrix=None, conformer_encoder=None, return_streams=False):
LLM Docstring
Decode a conformer tag back into Cartesian coordinates, using the molecular graph to reconstruct the canonical-fragment Z-matrix.
tag:strthe conformer tag
graph:Anythe molecular edge graph
decoder:str | Callable | Nonethe value decoder (
'plain'/'compressed'/'precision'or a callable)byte_size:int | Nonethe per-value bit width. If omitted and
conformer_encoderis given, inferred fromconformer_encoder.byte_size; otherwise falls back todefault_tag_byte_size.byte_encoding:int | Callable | Nonethe base-N text encoding
zmatrix:Anyan explicit Z-matrix connectivity (built if omitted)
conformer_encoder:ConformerEncoder | Nonea pre-built ConformerEncoder to use for the ‘compressed’/’precision’ decoders – must match whatever was used to encode the tag (same byte_size, ranges, and distributions), or decoding will silently produce wrong values. See
conformer_smiles_tag.:returns:np.ndarraythe decoded Cartesian coordinates
@classmethod
conformer_tag_num_atoms(cls, tag, conformer_encoder=None, **opts):
The number of atoms a conformer tag encodes, read from the tag alone (no graph needed). An empty tag is a single atom (no internal coordinates).
tag:strthe conformer tag
:returns:intthe number of encoded atoms
@classmethod
get_mol_edge_graph(cls, mol, bonds=None, reordering=None):
LLM Docstring
Build an EdgeGraph of a mol’s atom/bond connectivity.
mol:Chem.Molthe mol
:returns:EdgeGraphthe edge graph
get_edge_graph(self, mol=None, reordering=None):
LLM Docstring
Build an EdgeGraph of this molecule’s connectivity (or of a supplied mol).
mol:Chem.Mol | Nonean explicit mol (defaults to this one)
:returns:EdgeGraphthe edge graph
@classmethod
from_molblock(cls, molblock, add_implicit_hydrogens=False, sanitize=False, remove_hydrogens=False, **mol_opts):
LLM Docstring
Build an RDMolecule from a MDL molblock/.mol file or string.
molblock:strthe molblock file path or content
add_implicit_hydrogens:booladd implicit hydrogens
sanitize:boolrun sanitization
remove_hydrogens:boolremove explicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_mrv(cls, molblock, add_implicit_hydrogens=False, sanitize=False, remove_hydrogens=False, **mol_opts):
LLM Docstring
Build an RDMolecule from a Marvin .mrv file or string.
molblock:strthe MRV file path or content
add_implicit_hydrogens:booladd implicit hydrogens
sanitize:boolrun sanitization
remove_hydrogens:boolremove explicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_xyz(cls, molblock, add_implicit_hydrogens=False, guess_bonds=True, **mol_opts):
LLM Docstring
Build an RDMolecule from an XYZ file or string (perceiving bonds by default).
molblock:strthe XYZ file path or content
add_implicit_hydrogens:booladd implicit hydrogens
guess_bonds:boolperceive bonds from geometry
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_mol2(cls, molblock, add_implicit_hydrogens=False, sanitize=False, remove_hydrogens=False, **mol_opts):
LLM Docstring
Build an RDMolecule from a Tripos .mol2 file or string.
molblock:strthe mol2 file path or content
add_implicit_hydrogens:booladd implicit hydrogens
sanitize:boolrun sanitization
remove_hydrogens:boolremove explicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_cdxml(cls, molblock, add_implicit_hydrogens=True, **mol_opts):
LLM Docstring
Build an RDMolecule from a ChemDraw .cdxml file or string.
molblock:strthe CDXML file path or content
add_implicit_hydrogens:booladd implicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_pdb(cls, molblock, add_implicit_hydrogens=True, **mol_opts):
LLM Docstring
Build an RDMolecule from a PDB file or string.
molblock:strthe PDB file path or content
add_implicit_hydrogens:booladd implicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_png(cls, molblock, add_implicit_hydrogens=False, **mol_opts):
LLM Docstring
Build an RDMolecule from an RDKit-metadata-bearing PNG file or string.
molblock:strthe PNG file path or content
add_implicit_hydrogens:booladd implicit hydrogens
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_fasta(cls, molblock, add_implicit_hydrogens=True, allow_generate_conformers=True, **mol_opts):
LLM Docstring
Build an RDMolecule from a FASTA sequence (generating a conformer by default).
molblock:strthe FASTA content
add_implicit_hydrogens:booladd implicit hydrogens
allow_generate_conformers:boolgenerate a conformer
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
@classmethod
from_inchi(cls, inchi, sanitize=True, remove_hydrogens=True, add_implicit_hydrogens=True, call_add_hydrogens=True, conf_id=None, num_confs=None, optimize=False, take_min=True, force_field_type='mmff', confgen_opts=None, check_tag=True, coords=None, conf_tag=None, conformer_encoder=None, hydrogens_in_tag=None, log_level=None, treat_warning_as_error=False, **opts):
Build an RDMolecule from an InChI string, optional conformer tag,
or explicit coordinates.
hydrogens_in_tag:Anywhether the conformer tag encodes hydrogen positions (as written by
to_inchi(include_tag=True, remove_implicit_hydrogens=False)) or only heavy atoms.None(default) detects this from the number of atoms in the tag;True/Falseforce it
@classmethod
from_helm(cls, molblock, add_implicit_hydrogens=True, allow_generate_conformers=True, **mol_opts):
LLM Docstring
Build an RDMolecule from a HELM (macromolecule) string (generating a conformer
by default).
molblock:strthe HELM string
add_implicit_hydrogens:booladd implicit hydrogens
allow_generate_conformers:boolgenerate a conformer
mol_opts:Anyextra options forwarded to the reader
:returns:RDMoleculethe wrapped molecule
to_xyz(self, filename=None, conf_id=None, **opts):
LLM Docstring
Serialize the molecule to XYZ (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)conf_id:int | Nonethe conformer id
opts:Anyextra writer options
:returns:strthe file path or XYZ string
to_molblock(self, filename=None, conf_id=None, **opts):
LLM Docstring
Serialize the molecule to an MDL molblock (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)conf_id:int | Nonethe conformer id
opts:Anyextra writer options
:returns:strthe file path or molblock string
to_mrv(self, filename=None, conf_id=None, **opts):
LLM Docstring
Serialize the molecule to Marvin MRV (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)conf_id:int | Nonethe conformer id
opts:Anyextra writer options
:returns:strthe file path or MRV string
to_pdb(self, filename=None, conf_id=None, **opts):
LLM Docstring
Serialize the molecule to PDB (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)conf_id:int | Nonethe conformer id
opts:Anyextra writer options
:returns:strthe file path or PDB string
to_cml(self, filename=None, **opts):
LLM Docstring
Serialize the molecule to CML (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)opts:Anyextra writer options
:returns:strthe file path or CML string
to_sdf(self, filename=None, **opts):
LLM Docstring
Serialize the molecule to SDF (returned as a string, or written to a file).
filename:str | Nonethe output file path (or
Noneto return a string)opts:Anyextra writer options (e.g.
conf_ids):returns:strthe file path or SDF string
@classmethod
allchem_api(cls):
LLM Docstring
Return the RDKit Chem.AllChem submodule.
:returns:modulethe
AllChemmodule
@classmethod
get_force_field_type(cls, ff_type):
LLM Docstring
Resolve a force-field name to the RDKit (force_field_getter, property_generator)
pair.
ff_type:str | tuplethe force-field name (
'mmff'/'uff') or an existing pair:returns:tuplethe force-field getter (and property generator)
get_force_field(self, force_field_type='mmff', conf=None, mol=None, conf_id=None, **extra_props):
LLM Docstring
Build an RDKit force-field object for a conformer, computing any needed force-field properties.
force_field_type:str | tuplethe force-field name or getter pair
conf:Anyan explicit conformer
mol:Anyan explicit mol
conf_id:int | Nonethe conformer id
extra_props:Anyextra keyword arguments for the force-field getter
:returns:objectthe force-field object
evaluate_charges(self, coords, model='gasteiger'):
LLM Docstring
Compute the per-atom partial charges for a set of coordinates (currently only the Gasteiger model).
coords:np.ndarraythe coordinates (used to set the conformer)
model:strthe charge model
:returns:list[float]the partial charges
calculate_energy(self, geoms=None, force_field_generator=None, force_field_type='mmff', conf_id=None):
LLM Docstring
Compute the force-field energy of the current geometry, or of each geometry in a batch.
geoms:np.ndarray | Nonea batch of geometries (or
Nonefor the current one)force_field_generator:Callable | Nonea force-field factory (defaults to
get_force_field)force_field_type:strthe force-field name
conf_id:int | Nonethe conformer id
:returns:float | np.ndarraythe energy (or array of energies)
calculate_gradient(self, geoms=None, force_field_generator=None, force_field_type='mmff', conf_id=None):
LLM Docstring
Compute the force-field energy gradient of the current geometry, or of each geometry in a batch.
geoms:np.ndarray | Nonea batch of geometries (or
Nonefor the current one)force_field_generator:Callable | Nonea force-field factory (defaults to
get_force_field)force_field_type:strthe force-field name
conf_id:int | Nonethe conformer id
:returns:np.ndarraythe gradient (or batch of gradients)
calculate_hessian(self, force_field_generator=None, force_field_type='mmff', stencil=5, mesh_spacing=0.01, **fd_opts):
LLM Docstring
Compute the force-field Hessian at the current geometry by finite-differencing the analytic gradient.
force_field_generator:Callable | Nonea force-field factory
force_field_type:strthe force-field name
stencil:intthe finite-difference stencil size
mesh_spacing:floatthe finite-difference step
fd_opts:Anyextra finite-difference options
:returns:np.ndarraythe Hessian tensor
get_optimizer_params(self, maxAttempts=1000, useExpTorsionAnglePrefs=True, useBasicKnowledge=True, **etc):
LLM Docstring
Build an RDKit ETKDGv3 parameter object for structure optimization/embedding.
maxAttempts:intthe maximum embedding attempts
useExpTorsionAnglePrefs:booluse experimental torsion prefs
useBasicKnowledge:booluse basic chemical knowledge
etc:Anyextra parameters set on the params object
:returns:objectthe parameter object
optimize_structure(self, geoms=None, force_field_type='mmff', optimizer=None, maxIters=1000, **opts):
LLM Docstring
Force-field optimize the current geometry, or each geometry in a batch, returning the optimizer status and optimized coordinates.
geoms:np.ndarray | Nonea batch of geometries (or
Nonefor the current one)force_field_type:strthe force-field name
optimizer:Callable | Nonea custom optimizer callable
maxIters:intthe maximum optimization iterations
opts:Anyextra optimizer options
:returns:tuple(status, optimized_coords, extra)
show(self):
LLM Docstring
Display an interactive 3D rendering of the current conformer (via RDKit’s IPython 3D console).
:returns:objectthe 3D display