openff.toolkit.topology.Molecule
- class openff.toolkit.topology.Molecule(*args, **kwargs)[source]
Mutable chemical representation of a molecule, such as a small molecule or biopolymer.
Todo
What other API calls would be useful for supporting biopolymers as small molecules? Perhaps iterating over chains and residues?
Examples
Create a molecule from an sdf file
>>> from openff.toolkit.utils import get_data_file_path >>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf') >>> molecule = Molecule(sdf_filepath)
Convert to OpenEye OEMol object
>>> oemol = molecule.to_openeye()
Create a molecule from an OpenEye molecule
>>> molecule = Molecule.from_openeye(oemol)
Convert to RDKit Mol object
>>> rdmol = molecule.to_rdkit()
Create a molecule from an RDKit molecule
>>> molecule = Molecule.from_rdkit(rdmol)
Create a molecule from IUPAC name (requires the OpenEye toolkit)
>>> molecule = Molecule.from_iupac('imatinib')
Create a molecule from SMILES
>>> molecule = Molecule.from_smiles('Cc1ccccc1')
Warning
This API is experimental and subject to change.
- __init__(*args, **kwargs)[source]
See FrozenMolecule.__init__
Todo
If a filename or file-like object is specified but the file contains more than one molecule, what is the proper behavior? Read just the first molecule, or raise an exception if more than one molecule is found?
Should we also support SMILES strings or IUPAC names for
other
?
Methods
__init__
(*args, **kwargs)See FrozenMolecule.__init__
add_atom
(atomic_number, formal_charge, ...)Add an atom to the molecule.
add_bond
(atom1, atom2, bond_order, is_aromatic)Add a bond between two specified atom indices
add_conformer
(coordinates)Add a conformation of the molecule
Adds
chain
andresidue
hierarchy schemes.add_hierarchy_scheme
(uniqueness_criteria, ...)Use the molecule's metadata to facilitate iteration over its atoms.
apply_elf_conformer_selection
([percentage, ...])Select a set of diverse conformers from the molecule's conformers with ELF.
are_isomorphic
(mol1, mol2[, ...])Determine if
mol1
is isomorphic tomol2
.Update and store list of bond orders this molecule.
assign_partial_charges
(partial_charge_method)Calculate partial atomic charges and store them in the molecule.
atom
(index)Get the atom with the specified index.
atom_index
(atom)Returns the index of the given atom in this molecule
bond
(index)Get the bond with the specified index.
canonical_order_atoms
([toolkit_registry])Produce a copy of the molecule with the atoms reordered canonically.
chemical_environment_matches
(query[, ...])Find matches in the molecule for a SMARTS string
delete_hierarchy_scheme
(iter_name)Remove an existing
HierarchyScheme
specified by its iterator name.enumerate_protomers
([max_states])Enumerate the formal charges of a molecule to generate different protomoers.
enumerate_stereoisomers
([undefined_only, ...])Enumerate the stereocenters and bonds of the current molecule.
enumerate_tautomers
([max_states, ...])Enumerate the possible tautomers of the current molecule
find_rotatable_bonds
([...])Find all bonds classed as rotatable ignoring any matched to the
ignore_functional_groups
list.from_bson
(serialized)Instantiate an object from a BSON serialized representation.
from_dict
(molecule_dict)Create a new Molecule from a dictionary representation
from_file
(file_path[, file_format, ...])Create one or more molecules from a file
from_inchi
(inchi[, allow_undefined_stereo, ...])Construct a Molecule from a InChI representation
from_iupac
(iupac_name[, toolkit_registry, ...])Generate a molecule from IUPAC or common name
from_json
(serialized)Instantiate an object from a JSON serialized representation.
from_mapped_smiles
(mapped_smiles[, ...])Create a
Molecule
from a SMILES string, ordering atoms from mappingsfrom_messagepack
(serialized)Instantiate an object from a MessagePack serialized representation.
from_openeye
(oemol[, allow_undefined_stereo])Create a
Molecule
from an OpenEye molecule.from_pdb_and_smiles
(file_path, smiles[, ...])Create a Molecule from a pdb file and a SMILES string using RDKit.
from_pickle
(serialized)Instantiate an object from a pickle serialized representation.
from_polymer_pdb
(file_path[, ...])Loads a polymer from a PDB file.
from_qcschema
(qca_record[, client, ...])Create a Molecule from a QCArchive molecule record or dataset entry based on attached cmiles information.
from_rdkit
(rdmol[, allow_undefined_stereo, ...])Create a Molecule from an RDKit molecule.
from_smiles
(smiles[, ...])Construct a
Molecule
from a SMILES representationfrom_toml
(serialized)Instantiate an object from a TOML serialized representation.
from_topology
(topology)Return a Molecule representation of an OpenFF Topology containing a single Molecule object.
from_xml
(serialized)Instantiate an object from an XML serialized representation.
from_yaml
(serialized)Instantiate from a YAML serialized representation.
generate_conformers
([toolkit_registry, ...])Generate conformers for this molecule using an underlying toolkit.
Generate unique atom names from the element symbol and count.
get_bond_between
(i, j)Returns the bond between two atoms
is_isomorphic_with
(other, **kwargs)Check if the molecule is isomorphic with the other molecule which can be an openff.toolkit.topology.Molecule or nx.Graph().
nth_degree_neighbors
(n_degrees)Return canonicalized pairs of atoms whose shortest separation is exactly n bonds.
Compute an ordered hash of the atoms and bonds in the molecule
perceive_residues
([substructure_file_path, ...])Perceive a polymer's residues and permit iterating over them.
remap
(mapping_dict[, current_to_new, partial])Reorder the atoms in the molecule according to the given mapping dict.
strip_atom_stereochemistry
(smarts[, ...])Delete stereochemistry information for certain atoms, if it is present.
to_bson
()Return a BSON serialized representation.
to_dict
()Return a dictionary representation of the molecule.
to_file
(file_path, file_format[, ...])Write the current molecule to a file or file-like object
Generate the Hill formula of this molecule.
to_inchi
([fixed_hydrogens, toolkit_registry])Create an InChI string for the molecule using the requested toolkit backend.
to_inchikey
([fixed_hydrogens, toolkit_registry])Create an InChIKey for the molecule using the requested toolkit backend.
to_iupac
([toolkit_registry])Generate IUPAC name from Molecule
to_json
([indent])Return a JSON serialized representation.
Return a MessagePack representation.
Generate a NetworkX undirected graph from the molecule.
to_openeye
([toolkit_registry, aromaticity_model])Create an OpenEye molecule
Return a pickle serialized representation.
to_qcschema
([multiplicity, conformer, extras])Create a QCElemental Molecule.
to_rdkit
([aromaticity_model, toolkit_registry])Create an RDKit molecule
to_smiles
([isomeric, explicit_hydrogens, ...])Return a canonical isomeric SMILES representation of the current molecule.
to_toml
()Return a TOML serialized representation.
Return an OpenFF Topology representation containing one copy of this molecule
to_xml
([indent])Return an XML representation.
to_yaml
()Return a YAML serialized representation.
update_hierarchy_schemes
([iter_names])Infer a hierarchy from atom metadata according to the existing hierarchy schemes.
Render a visualization of the molecule in Jupyter
Attributes
Iterate over all impropers with trivalent centers, reporting the central atom first.
Get an iterator over all i-j-k angles.
Iterate over all Atom objects in the molecule.
Iterate over all Bond objects in the molecule.
Returns the list of conformers for this molecule.
True
if the molecule has unique atom names,False
otherwise.The hierarchy schemes available on the molecule.
Get the Hill formula of the molecule
Iterate over all improper torsions in the molecule.
Number of angles in the molecule.
The number of Atom objects.
The number of Bond objects in the molecule.
The number of conformers for this molecule.
Number of possible improper torsions in the molecule.
Number of proper torsions in the molecule.
The name (or title) of the molecule
Returns the partial charges (if present) on the molecule.
Iterate over all proper torsions in the molecule
The properties dictionary of the molecule
Iterate over all impropers with trivalent centers, reporting the central atom second.
Get an iterator over all i-j-k-l torsions.
Return the total charge on the molecule
- add_atom(atomic_number: int, formal_charge: int, is_aromatic: bool, stereochemistry: Optional[str] = None, name: Optional[str] = None, metadata: Optional[Dict[str, Union[int, str]]] = None) int [source]
Add an atom to the molecule.
- Parameters:
atomic_number (
int
) – Atomic number of the atomformal_charge (
int
) – Formal charge of the atomis_aromatic (
bool
) – IfTrue
, atom is aromatic; ifFalse
, not aromaticstereochemistry (
str
, optional, defaultNone
) – Either'R'
or'S'
for specified stereochemistry, orNone
if stereochemistry is irrelevantname (
str
, optional) – An optional name for the atommetadata (
dict[str
:(int
,str)]
, defaultNone
) – An optional dictionary where keys are strings and values are strings or ints. This is intended to record atom-level information used to inform hierarchy definition and iteration, such as grouping atom by residue and chain.
- Returns:
index (
int
) – The index of the atom in the molecule
Examples
Define a methane molecule
>>> molecule = Molecule() >>> molecule.name = 'methane' >>> C = molecule.add_atom(6, 0, False) >>> H1 = molecule.add_atom(1, 0, False) >>> H2 = molecule.add_atom(1, 0, False) >>> H3 = molecule.add_atom(1, 0, False) >>> H4 = molecule.add_atom(1, 0, False) >>> bond_idx = molecule.add_bond(C, H1, 1, False) >>> bond_idx = molecule.add_bond(C, H2, 1, False) >>> bond_idx = molecule.add_bond(C, H3, 1, False) >>> bond_idx = molecule.add_bond(C, H4, 1, False) >>> molecule.to_smiles(explicit_hydrogens=False) 'C'
- add_bond(atom1: Union[int, Atom], atom2: Union[int, Atom], bond_order: int, is_aromatic: bool, stereochemistry: Optional[str] = None, fractional_bond_order: Optional[float] = None)[source]
Add a bond between two specified atom indices
- Parameters:
atom1 (
int
oropenff.toolkit.topology.molecule.Atom
) – Index of first atomatom2 (
int
oropenff.toolkit.topology.molecule.Atom
) – Index of second atombond_order (
int
) – Integral bond order of Kekulized formis_aromatic (
bool
) – True if this bond is aromatic, False otherwisestereochemistry (
str
, optional, defaultNone
) – Either'E'
or'Z'
for specified stereochemistry, orNone
if stereochemistry is irrelevantfractional_bond_order (
float
, optional, defaultNone
) – The fractional (eg. Wiberg) bond order
- Returns:
index (
int
) – Index of the bond in this molecule
Examples
For an example of use, see
add_atom()
.
- add_conformer(coordinates)[source]
Add a conformation of the molecule
- Parameters:
coordinates (
unit-wrapped np.array with shape (n_atoms
,3)
anddimension
ofdistance
) – Coordinates of the new conformer, with the first dimension of the array corresponding to the atom index in the molecule’s indexing system.- Returns:
index (
int
) – The index of this conformer
- visualize(backend: Literal['rdkit']) IPython.display.SVG [source]
- visualize(backend: Literal['openeye']) IPython.display.Image
- visualize(backend: Literal['nglview']) nglview.NGLWidget
Render a visualization of the molecule in Jupyter
- Parameters:
backend (
str
, optional, default'rdkit'
) –The visualization engine to use. Choose from:
"rdkit"
"openeye"
"nglview"
(requires conformers)
width (
int
, default500
) – Width of the generated representation (only applicable tobackend="openeye"
orbackend="rdkit"
)height (
int
, default300
) – Width of the generated representation (only applicable tobackend="openeye"
orbackend="rdkit"
)show_all_hydrogens (
bool
, defaultTrue
) – Whether to explicitly depict all hydrogen atoms. (only applicable tobackend="openeye"
orbackend="rdkit"
)
- Returns:
object
– Depending on the backend chosen:rdkit → IPython.display.SVG
openeye → IPython.display.Image
nglview → nglview.NGLWidget
- perceive_residues(substructure_file_path=None, strict_chirality=True)[source]
Perceive a polymer’s residues and permit iterating over them.
Perceives residues by matching substructures in the current molecule with a substructure dictionary file, using SMARTS, and assigns residue names and numbers to atom metadata. It then constructs a residue hierarchy scheme to allow iterating over residues.
- Parameters:
- add_default_hierarchy_schemes(overwrite_existing=True)
Adds
chain
andresidue
hierarchy schemes.The Open Force Field Toolkit has no native understanding of hierarchical atom organisation schemes common to other biomolecular software, such as “residues” or “chains” (see userguide_hierarchy). Hierarchy schemes allow iteration over groups of atoms according to their metadata. For more information, see
HierarchyScheme
.If a
Molecule
with the default hierarchy schemes changes,Molecule.update_hierarchy_schemes()
must be called before the residues or chains are iterated over again or else the iteration may be incorrect.- Parameters:
overwrite_existing (
bool
, defaultTrue
) – Whether to overwrite existing instances of the residue and chain hierarchy schemes. If this isFalse
and either of the hierarchy schemes are already defined on this molecule, an exception will be raised.- Raises:
HierarchySchemeWithIteratorNameAlreadyRegisteredException – When
overwrite_existing=False
and either thechains
orresidues
hierarchy scheme is already configured.
See also
HierarchyScheme
,Molecule.add_hierarchy_scheme
,Molecule.update_hierarchy_schemes
,Molecule.perceive_residues
- add_hierarchy_scheme(uniqueness_criteria, iterator_name)
Use the molecule’s metadata to facilitate iteration over its atoms.
This method will add an attribute with the name given by the
iterator_name
argument that provides an iterator over groups of atoms. Atoms are grouped by the values in theiratom.metadata
dictionary; any atoms with the same values for the keys given in theuniqueness_criteria
argument will be in the same group. These groups have the typeHierarchyElement
.Hierarchy schemes are not updated dynamically; if a
Molecule
with hierarchy schemes changes,Molecule.update_hierarchy_schemes()
must be called before the scheme is iterated over again or else the grouping may be incorrect.Hierarchy schemes allow iteration over groups of atoms according to their metadata. For more information, see
HierarchyScheme
.- Parameters:
uniqueness_criteria (
tuple
ofstr
) – The names ofAtom
metadata entries that define this scheme. An atom belongs to aHierarchyElement
only if its metadata has the same values for these criteria as the other atoms in theHierarchyElement
.iterator_name (
str
) – Name of the iterator that will be exposed to access the hierarchy elements generated by this scheme. Must not match an existing attribute of theMolecule
, i.e.atoms
,angles
, etc.
- Returns:
new_hier_scheme (
openff.toolkit.topology.HierarchyScheme
) – The newly created HierarchyScheme
- property amber_impropers: Set[Tuple[Atom, Atom, Atom, Atom]]
Iterate over all impropers with trivalent centers, reporting the central atom first.
The central atom is reported first in each torsion. This method reports an improper for each trivalent atom in the molecule, whether or not any given force field would assign it improper torsion parameters.
Also note that this will return 6 possible atom orderings around each improper center. In current AMBER parameterization, one of these six orderings will be used for the actual assignment of the improper term and measurement of the angle. This method does not encode the logic to determine which of the six orderings AMBER would use.
- Returns:
impropers (
set
oftuple
) – An iterator of tuples, each containing the indices of atoms making up a possible improper torsion. The central atom is listed first in each tuple.
See also
- apply_elf_conformer_selection(percentage: float = 2.0, limit: int = 10, toolkit_registry: Optional[Union[ToolkitRegistry, ToolkitWrapper]] = GLOBAL_TOOLKIT_REGISTRY, **kwargs)
Select a set of diverse conformers from the molecule’s conformers with ELF.
Applies the Electrostatically Least-interacting Functional groups method to select a set of diverse conformers which have minimal electrostatically strongly interacting functional groups from the molecule’s conformers.
- Parameters:
toolkit_registry – The underlying toolkit to use to select the ELF conformers.
percentage – The percentage of conformers with the lowest electrostatic interaction energies to greedily select from.
limit – The maximum number of conformers to select.
Notes
The input molecule should have a large set of conformers already generated to select the ELF conformers from.
The selected conformers will be retained in the conformers list while unselected conformers will be discarded.
See also
openff.toolkit.utils.toolkits.OpenEyeToolkitWrapper.apply_elf_conformer_selection
,openff.toolkit.utils.toolkits.RDKitToolkitWrapper.apply_elf_conformer_selection
- static are_isomorphic(mol1: Union[FrozenMolecule, _SimpleMolecule, Graph], mol2: Union[FrozenMolecule, _SimpleMolecule, Graph], return_atom_map: bool = False, aromatic_matching: bool = True, formal_charge_matching: bool = True, bond_order_matching: bool = True, atom_stereochemistry_matching: bool = True, bond_stereochemistry_matching: bool = True, strip_pyrimidal_n_atom_stereo: bool = True, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY) Tuple[bool, Optional[Dict[int, int]]]
Determine if
mol1
is isomorphic tomol2
.are_isomorphic()
compares two molecule’s graph representations and the chosen node/edge attributes. Connections and atomic numbers are always checked.If nx.Graphs() are given they must at least have
atomic_number
attributes on nodes. Other attributes thatare_isomorphic()
can optionally check…… in nodes are:
is_aromatic
formal_charge
stereochemistry
… in edges are:
is_aromatic
bond_order
stereochemistry
By default, all attributes are checked, but stereochemistry around pyrimidal nitrogen is ignored.
Warning
This API is experimental and subject to change.
- Parameters:
mol1 (
an openff.toolkit.topology.molecule.FrozenMolecule
ornx.Graph()
) – The first molecule to test for isomorphism.mol2 (
an openff.toolkit.topology.molecule.FrozenMolecule
ornx.Graph()
) – The second molecule to test for isomorphism.return_atom_map (
bool
, defaultFalse
, optional) – Return adict
containing the atomic mapping, otherwiseNone
. Only processed if inputs are isomorphic, will always returnNone
if inputs are not isomorphic.aromatic_matching (
bool
, defaultTrue
, optional) – IfFalse
, aromaticity of graph nodes and edges are ignored for the purpose of determining isomorphism.formal_charge_matching (
bool
, defaultTrue
, optional) – IfFalse
, formal charges of graph nodes are ignored for the purpose of determining isomorphism.bond_order_matching (
bool
, defaultTrue
, optional) – IfFalse
, bond orders of graph edges are ignored for the purpose of determining isomorphism.atom_stereochemistry_matching (
bool
, defaultTrue
, optional) – IfFalse
, atoms’ stereochemistry is ignored for the purpose of determining isomorphism.bond_stereochemistry_matching (
bool
, defaultTrue
, optional) – IfFalse
, bonds’ stereochemistry is ignored for the purpose of determining isomorphism.strip_pyrimidal_n_atom_stereo (
bool
, defaultTrue
, optional) – IfTrue
, any stereochemistry defined around pyrimidal nitrogen stereocenters will be disregarded in the isomorphism check.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for removing stereochemistry from pyrimidal nitrogens.
- Returns:
- assign_fractional_bond_orders(bond_order_model=None, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, use_conformers=None)
Update and store list of bond orders this molecule.
Bond orders are stored on each bond, in the
bond.fractional_bond_order
attribute.Warning
This API is experimental and subject to change.
- Parameters:
toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for SMILES-to-molecule conversionbond_order_model (
string
,optional. Default=None
) – The bond order model to use for fractional bond order calculation. IfNone
,"am1-wiberg"
is used.use_conformers (
iterable
ofopenff.unit.Quantity(np.array) with shape (n_atoms
,3)
anddimension
ofdistance,
) – optional, default=None The conformers to use for fractional bond order calculation. IfNone
, an appropriate number of conformers will be generated by an availableToolkitWrapper
.
Examples
>>> from openff.toolkit import Molecule >>> molecule = Molecule.from_smiles('CCCCCC') >>> molecule.assign_fractional_bond_orders()
- Raises:
InvalidToolkitRegistryError – If an invalid object is passed as the toolkit_registry parameter
- assign_partial_charges(partial_charge_method: str, strict_n_conformers: bool = False, use_conformers: Optional[Iterable[Quantity]] = None, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY, normalize_partial_charges: bool = True)
Calculate partial atomic charges and store them in the molecule.
assign_partial_charges
computes charges using the specified toolkit and assigns the new values to thepartial_charges
attribute. Supported charge methods vary from toolkit to toolkit, but some supported methods are:"am1bcc"
"am1bccelf10"
(requires OpenEye Toolkits)"am1-mulliken"
"mmff94"
"gasteiger"
By default, the conformers on the input molecule are not used in the charge calculation. Instead, any conformers needed for the charge calculation are generated by this method. If this behavior is undesired, specific conformers can be provided via the
use_conformers
argument.ELF10 methods will neither fail nor warn when fewer than the expected number of conformers could be generated, as many small molecules are too rigid to provide a large number of conformers. Note that only the
"am1bccelf10"
partial charge method uses ELF conformer selection; the"am1bcc"
method only uses a single conformer. This may confuse users as the ToolkitAM1BCC SMIRNOFF tag in a force field file defines that AM1BCC-ELF10 should be used if the OpenEye Toolkits are available.For more supported charge methods and their details, see the corresponding methods in each toolkit wrapper:
OpenEyeToolkitWrapper.assign_partial_charges
RDKitToolkitWrapper.assign_partial_charges
AmberToolsToolkitWrapper.assign_partial_charges
BuiltInToolkitWrapper.assign_partial_charges
- Parameters:
partial_charge_method (
string
) – The partial charge calculation method to use for partial charge calculation.strict_n_conformers (
bool
, defaultFalse
) – Whether to raise an exception if an invalid number of conformers is provided for the given charge method. If this is False and an invalid number of conformers is found, a warning will be raised.use_conformers (
Arrays with shape (n_atoms
,3)
anddimensions
ofdistance
) – Coordinates to use for partial charge calculation. IfNone
, an appropriate number of conformers will be generated.toolkit_registry –
ToolkitRegistry
orToolkitWrapper
to use for the calculation.normalize_partial_charges (
bool
, defaultTrue
) – Whether to offset partial charges so that they sum to the total formal charge of the molecule. This is used to prevent accumulation of rounding errors when the partial charge assignment method returns values at limited precision.
Examples
Generate AM1 Mulliken partial charges. Conformers for the AM1 calculation are generated automatically:
>>> molecule = Molecule.from_smiles('CCCCCC') >>> molecule.assign_partial_charges('am1-mulliken')
To use pre-generated conformations, use the
use_conformers
argument:>>> molecule = Molecule.from_smiles('CCCCCC') >>> molecule.generate_conformers(n_conformers=1) >>> molecule.assign_partial_charges( ... 'am1-mulliken', ... use_conformers=molecule.conformers ... )
- Raises:
InvalidToolkitRegistryError – If an invalid object is passed as the toolkit_registry parameter
See also
openff.toolkit.utils.toolkits.OpenEyeToolkitWrapper.assign_partial_charges
,openff.toolkit.utils.toolkits.RDKitToolkitWrapper.assign_partial_charges
,openff.toolkit.utils.toolkits.AmberToolsToolkitWrapper.assign_partial_charges
,openff.toolkit.utils.toolkits.BuiltInToolkitWrapper.assign_partial_charges
- atom(index: int) Atom
Get the atom with the specified index.
- Parameters:
index (
int
) –- Returns:
atom (
openff.toolkit.topology.Atom
)
- atom_index(atom: Atom) int
Returns the index of the given atom in this molecule
- Parameters:
atom (
openff.toolkit.topology.Atom
) –- Returns:
index (
int
) – The index of the given atom in this molecule
- bond(index: int) Bond
Get the bond with the specified index.
- Parameters:
index (
int
) –- Returns:
bond (
openff.toolkit.topology.Bond
)
- property bonds: List[Bond]
Iterate over all Bond objects in the molecule.
- canonical_order_atoms(toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Produce a copy of the molecule with the atoms reordered canonically.
Each toolkit defines its own canonical ordering of atoms. The canonical order may change from toolkit version to toolkit version or between toolkits.
Warning
This API is experimental and subject to change.
- Parameters:
toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optionalToolkitRegistry
orToolkitWrapper
to use for SMILES-to-molecule conversion- Returns:
molecule (
openff.toolkit.topology.Molecule
) – An new OpenFF style molecule with atoms in the canonical order.
- chemical_environment_matches(query: str, unique: bool = False, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Find matches in the molecule for a SMARTS string
- Parameters:
query (
str
) – SMARTS string (with one or more tagged atoms).toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use for chemical environment matches
- Returns:
matches (
list
ofatom index tuples
) – A list of tuples, containing the indices of the matching atoms.
Examples
Retrieve all the carbon-carbon bond matches in a molecule
>>> molecule = Molecule.from_iupac('imatinib') >>> matches = molecule.chemical_environment_matches('[#6X3:1]~[#6X3:2]')
Todo
Do we want to generalize
query
to allow other kinds of queries, such as mdtraj DSL, pymol selections, atom index slices, etc? We could call ittopology.matches(query)
instead ofchemical_environment_matches
- property conformers
Returns the list of conformers for this molecule.
Conformers are presented as a list of
Quantity
-wrapped NumPy arrays, of shape (3 x n_atoms) and with dimensions of [Distance]. The return value is the actual list of conformers, and changes to the contents affect the originalFrozenMolecule
.
- delete_hierarchy_scheme(iter_name)
Remove an existing
HierarchyScheme
specified by its iterator name.Hierarchy schemes allow iteration over groups of atoms according to their metadata. For more information, see
HierarchyScheme
.- Parameters:
iter_name (
str
) –
See also
Molecule.add_hierarchy_scheme
,Molecule.update_hierarchy_schemes
,Molecule.hierarchy_schemes
,HierarchyScheme
- enumerate_protomers(max_states=10)
Enumerate the formal charges of a molecule to generate different protomoers.
- Parameters:
max_states (
int optional
, default10,
) – The maximum number of protomer states to be returned.- Returns:
molecules (
List[openff.toolkit.topology.Molecule],
) – A list of the protomers of the input molecules not including the input.
- enumerate_stereoisomers(undefined_only=False, max_isomers=20, rationalise=True, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Enumerate the stereocenters and bonds of the current molecule.
- Parameters:
undefined_only (
bool optional
, defaultFalse
) – If we should enumerate all stereocenters and bonds or only those with undefined stereochemistrymax_isomers (
int optional
, default20
) – The maximum amount of molecules that should be returnedrationalise (
bool optional
, defaultTrue
) – If we should try to build and rationalise the molecule to ensure it can existtoolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – lopenff.toolkit.utils.toolkits.ToolkitWrapper, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use to enumerate the stereoisomers.
- Returns:
molecules (
List[openff.toolkit.topology.Molecule]
) – A list ofMolecule
instances not including the input molecule.
- enumerate_tautomers(max_states=20, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Enumerate the possible tautomers of the current molecule
- Parameters:
max_states (
int optional
, default20
) – The maximum amount of molecules that should be returnedtoolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use to enumerate the tautomers.
- Returns:
molecules (
List[openff.toolkit.topology.Molecule]
) – A list of openff.toolkit.topology.Molecule instances not including the input molecule.
- find_rotatable_bonds(ignore_functional_groups=None, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Find all bonds classed as rotatable ignoring any matched to the
ignore_functional_groups
list.- Parameters:
ignore_functional_groups (optional,
List[str]
, defaultNone,
) – A list of bond SMARTS patterns to be ignored when finding rotatable bonds.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapperl, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for SMARTS matching
- Returns:
bonds (
List[openff.toolkit.topology.molecule.Bond]
) – The list of openff.toolkit.topology.molecule.Bond instances which are rotatable.
- classmethod from_bson(serialized)
Instantiate an object from a BSON serialized representation.
Specification: http://bsonspec.org/
- Parameters:
serialized (
bytes
) – A BSON serialized representation of the object- Returns:
instance (
cls
) – An instantiated object
- classmethod from_dict(molecule_dict: dict)
Create a new Molecule from a dictionary representation
- classmethod from_file(file_path: Union[str, Path, TextIO], file_format=None, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, allow_undefined_stereo=False)
Create one or more molecules from a file
Todo
Extend this to also include some form of .offmol Open Force Field Molecule format?
Generalize this to also include file-like objects?
- Parameters:
file_path (
str
,pathlib.Path
, orfile-like object
) – The path to the file or file-like object to stream one or more molecules from.file_format (
str
, optional, defaultNone
) – Format specifier, usually file suffix (eg. ‘MOL2’, ‘SMI’) Note that not all toolkits support all formats. Check ToolkitWrapper.toolkit_file_read_formats for your loaded toolkits for details.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use for file loading. If a Toolkit is passed, only the highest-precedence toolkit is usedallow_undefined_stereo (
bool
, defaultFalse
) – If false, raises an exception if oemol contains undefined stereochemistry.
- Returns:
molecules (
Molecule
orlist
ofMolecules
) – If there is a single molecule in the file, a Molecule is returned; otherwise, a list of Molecule objects is returned.
Examples
>>> from openff.toolkit import Molecule >>> from openff.toolkit.utils.utils import get_data_file_path >>> sdf_file_path = get_data_file_path("molecules/toluene.sdf") >>> molecule = Molecule.from_file(sdf_file_path)
- classmethod from_inchi(inchi: str, allow_undefined_stereo: bool = False, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY, name: str = '')
Construct a Molecule from a InChI representation
- Parameters:
inchi (
str
) – The InChI representation of the molecule.allow_undefined_stereo (
bool
, defaultFalse
) – Whether to accept InChI with undefined stereochemistry. If False, an exception will be raised if a InChI with undefined stereochemistry is passed into this function.toolkit_registry (
openff.toolkit.utils.toolkits.ToolRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for InChI-to-molecule conversionname (
str
, default""
) – An optional name for the output molecule
- Returns:
molecule (
openff.toolkit.topology.Molecule
)
Examples
Make cis-1,2-Dichloroethene:
>>> molecule = Molecule.from_inchi('InChI=1S/C2H2Cl2/c3-1-2-4/h1-2H/b2-1-')
- classmethod from_iupac(iupac_name, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, allow_undefined_stereo=False, **kwargs)
Generate a molecule from IUPAC or common name
Note
This method requires the OpenEye toolkit to be installed.
- Parameters:
iupac_name (
str
) – IUPAC name of molecule to be generatedtoolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use for chemical environment matchesallow_undefined_stereo (
bool
, defaultFalse
) – If false, raises an exception if molecule contains undefined stereochemistry.
- Returns:
molecule (
Molecule
) – The resulting molecule with position
Examples
Create a molecule from an IUPAC name
>>> molecule = Molecule.from_iupac('4-[(4-methylpiperazin-1-yl)methyl]-N-(4-methyl-3-{[4-(pyridin-3-yl)pyrimidin-2-yl]amino}phenyl)benzamide') # noqa
Create a molecule from a common name
>>> molecule = Molecule.from_iupac('imatinib')
- classmethod from_json(serialized: str)
Instantiate an object from a JSON serialized representation.
Specification: https://www.json.org/
- Parameters:
serialized (
str
) – A JSON serialized representation of the object- Returns:
instance (
cls
) – An instantiated object
- classmethod from_mapped_smiles(mapped_smiles: str, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY, allow_undefined_stereo: bool = False)
Create a
Molecule
from a SMILES string, ordering atoms from mappingsSMILES strings support mapping integer indices to each atom by ending a bracketed atom declaration with a colon followed by a 1-indexed integer:
This method creates a
Molecule
from such a SMILES string whose atoms are ordered according to the mapping. Each atom must be mapped exactly once; any duplicate, missing, or out-of-range mappings will cause the method to fail.Warning
This API is experimental and subject to change.
- Parameters:
mapped_smiles (
str
) – A mapped SMILES string with explicit hydrogens.toolkit_registry – Cheminformatics toolkit to use for SMILES-to-molecule conversion
allow_undefined_stereo – If false, raise an exception if the SMILES contains undefined stereochemistry.
- Returns:
offmol
– An OpenFF molecule instance.- Raises:
SmilesParsingError – If the given SMILES had no indexing picked up by the toolkits, or if the indexing is missing indices.
RemapIndexError – If the mapping has duplicate or out-of-range indices.
Examples
Create a mapped chlorofluoroiodomethane molecule and check the atoms are placed accordingly:
>>> molecule = Molecule.from_mapped_smiles( ... "[Cl:2][C@:1]([F:3])([I:4])[H:5]" ... ) >>> assert molecule.atom(0).symbol == "C" >>> assert molecule.atom(1).symbol == "Cl" >>> assert molecule.atom(2).symbol == "F" >>> assert molecule.atom(3).symbol == "I" >>> assert molecule.atom(4).symbol == "H"
See also
- classmethod from_messagepack(serialized)
Instantiate an object from a MessagePack serialized representation.
Specification: https://msgpack.org/index.html
- Parameters:
serialized (
bytes
) – A MessagePack-encoded bytes serialized representation- Returns:
instance (
cls
) – Instantiated object.
- classmethod from_openeye(oemol, allow_undefined_stereo=False)
Create a
Molecule
from an OpenEye molecule.Requires the OpenEye toolkit to be installed.
- Parameters:
- Returns:
molecule (
openff.toolkit.topology.Molecule
) – An OpenFF molecule
Examples
Create a
Molecule
from an OpenEye OEMol>>> from openff.toolkit import Molecule >>> from openeye import oechem >>> oemol = oechem.OEMol() >>> oechem.OESmilesToMol(oemol, '[H]C([H])([H])C([H])([H])O[H]') True >>> molecule = Molecule.from_openeye(oemol)
- classmethod from_pdb_and_smiles(file_path, smiles, allow_undefined_stereo=False, name='')
Create a Molecule from a pdb file and a SMILES string using RDKit.
Requires RDKit to be installed.
Warning
This API is experimental and subject to change.
The molecule is created and sanitised based on the SMILES string, we then find a mapping between this molecule and one from the PDB based only on atomic number and connections. The SMILES molecule is then reindexed to match the PDB, the conformer is attached, and the molecule returned.
Note that any stereochemistry in the molecule is set by the SMILES, and not the coordinates of the PDB.
- Parameters:
file_path (
str
) – PDB file pathsmiles (
str
) – a valid smiles string for the pdb, used for stereochemistry, formal charges, and bond orderallow_undefined_stereo (
bool
, defaultFalse
) – If false, raises an exception if SMILES contains undefined stereochemistry.name (
str
, default""
) – An optional name for the output molecule
- Returns:
molecule (
openff.toolkit.Molecule
) – An OFFMol instance with ordering the same as used in the PDB file.- Raises:
InvalidConformerError – If the SMILES and PDB molecules are not isomorphic.
- classmethod from_pickle(serialized)
Instantiate an object from a pickle serialized representation.
Warning
This is not recommended for safe, stable storage since the pickle specification may change between Python versions.
- Parameters:
serialized (
str
) – A pickled representation of the object- Returns:
instance (
cls
) – An instantiated object
- classmethod from_polymer_pdb(file_path: Union[str, Path, TextIO], toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, name: str = '')
Loads a polymer from a PDB file.
Also see
Topology.from_multicomponent_pdb()
, which can do everything this method can and more.Currently only supports proteins with canonical amino acids that are either uncapped or capped by ACE/NME groups, but may later be extended to handle other common polymers, or accept user-defined polymer templates. Only one polymer chain may be present in the PDB file, and it must be the only molecule present.
Connectivity and bond orders are assigned by matching SMARTS codes for the supported residues against atom names. The PDB file must include all atoms with the correct standard atom names described in the PDB Chemical Component Dictionary. Residue names are used to assist trouble-shooting failed assignments, but are not used in the actual assignment process.
Metadata such as residues, chains, and atom names are recorded in the
Atom.metadata
attribute, which is a dictionary mapping from strings like “residue_name” to the appropriate value.from_polymer_pdb
returns a molecule that can be iterated over with the.residues
and.chains
attributes, as well as the usual.atoms
.- Parameters:
- Returns:
molecule (
openff.toolkit.topology.Molecule
)- Raises:
UnassignedChemistryInPDBError – If an atom or bond could not be assigned; the exception will provide a detailed diagnostic of what went wrong.
MultipleMoleculesInPDBError – If all atoms and bonds could be assigned, but the PDB includes multiple chains or molecules.
- classmethod from_qcschema(qca_record, client=None, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, allow_undefined_stereo=False)
Create a Molecule from a QCArchive molecule record or dataset entry based on attached cmiles information.
For a molecule record, a conformer will be set from its geometry.
For a dataset entry, if a corresponding client instance is provided, the starting geometry for that entry will be used as a conformer.
A QCElemental Molecule produced from
Molecule.to_qcschema
can be round-tripped through this method to produce a new, valid Molecule.- Parameters:
qca_record (
dict
) – A QCArchive molecule record or dataset entry.client (optional, default
None,
) – A qcportal.FractalClient instance to use for fetching an initial geometry. Only used ifqca_record
is a dataset entry.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optionalToolkitRegistry
orToolkitWrapper
to use for SMILES-to-molecule conversionallow_undefined_stereo (
bool
, defaultFalse
) – If false, raises an exception if qca_record contains undefined stereochemistry.
- Returns:
molecule (
openff.toolkit.topology.Molecule
) – An OpenFF molecule instance.
Examples
Get Molecule from a QCArchive molecule record:
>>> from qcportal import FractalClient >>> client = FractalClient() >>> offmol = Molecule.from_qcschema( ... client.query_molecules(molecular_formula="C7H12N2O4")[0] ... )
Get Molecule from a QCArchive optimization entry:
>>> from qcportal import FractalClient >>> client = FractalClient() >>> optds = client.get_collection( ... "OptimizationDataset", ... "SMIRNOFF Coverage Set 1" ... ) >>> offmol = Molecule.from_qcschema(optds.get_entry('coc(o)oc-0'))
Same as above, but with conformer(s) from initial molecule(s) by providing client to database:
>>> offmol = Molecule.from_qcschema( ... optds.get_entry('coc(o)oc-0'), ... client=client ... )
- Raises:
AttributeError – If the record dict can not be made from
qca_record
, or if the providedclient
could not retrieve the initial molecule.KeyError – If the record does not contain the
canonical_isomeric_explicit_hydrogen_mapped_smiles
.InvalidConformerError – Silent error, if the conformer could not be attached.
- classmethod from_rdkit(rdmol, allow_undefined_stereo=False, hydrogens_are_explicit=False)
Create a Molecule from an RDKit molecule.
Requires the RDKit to be installed.
- Parameters:
- Returns:
molecule (
openff.toolkit.topology.Molecule
) – An OpenFF molecule
Examples
Create a molecule from an RDKit molecule
>>> from openff.toolkit import Molecule >>> from rdkit import Chem >>> rdmol = Chem.MolFromSmiles("CCO") >>> molecule = Molecule.from_rdkit(rdmol)
- classmethod from_smiles(smiles: str, hydrogens_are_explicit: bool = False, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY, allow_undefined_stereo: bool = False, name: str = '') Molecule
Construct a
Molecule
from a SMILES representationThe order of atoms in the
Molecule
is unspecified and may change from version to version or with different toolkits. SMILES atom indices (also known as atom maps) are not used to order atoms; instead, they are stored in the produced molecule’s properties attribute, accessible viamolecule.properties["atom_map"]
. The atom map is stored as a dictionary mapping molecule atom indices to SMILES atom maps. To order atoms according to SMILES atom indices, seeMolecule.from_mapped_smiles()
, which helpfully raises an exception if any atom map is missing, duplicated, or out-of-range, or elseMolecule.remap()
for arbitrary remaps.- Parameters:
smiles – The SMILES representation of the molecule.
hydrogens_are_explicit – If
True
, forbid the cheminformatics toolkit from inferring hydrogen atoms not explicitly specified in the SMILES.toolkit_registry – The cheminformatics toolkit to use to interpret the SMILES.
allow_undefined_stereo – Whether to accept SMILES with undefined stereochemistry. If
False
, an exception will be raised if a SMILES with undefined stereochemistry is passed into this function.name (
str
, default""
) – An optional name for the output molecule
- Raises:
RadicalsNotSupportedError – If any atoms in the input molecule contain radical electrons.
Examples
Create a
Molecule
representing toluene from SMILES:>>> molecule = Molecule.from_smiles('Cc1ccccc1')
Create a
Molecule
representing phenol from SMILES with the oxygen at atom index 0 (SMILES indices begin at 1):>>> molecule = Molecule.from_smiles('c1ccccc1[OH:1]') >>> molecule = molecule.remap( ... {k: v - 1 for k, v in molecule.properties["atom_map"].items()}, ... partial=True, ... ) >>> assert molecule.atom(0).symbol == "O"
See also
- classmethod from_toml(serialized)
Instantiate an object from a TOML serialized representation.
Specification: https://github.com/toml-lang/toml
- Parameters:
serlialized (
str
) – A TOML serialized representation of the object- Returns:
instance (
cls
) – An instantiated object
- classmethod from_topology(topology)
Return a Molecule representation of an OpenFF Topology containing a single Molecule object.
- Parameters:
topology (
openff.toolkit.topology.Topology
) – TheTopology
object containing a singleMolecule
object. Note that OpenMM and MDTrajTopology
objects are not supported.- Returns:
molecule (
openff.toolkit.topology.Molecule
) – The Molecule object in the topology- Raises:
ValueError – If the topology does not contain exactly one molecule.
Examples
Create a molecule from a Topology object that contains exactly one molecule
>>> from openff.toolkit import Molecule, Topology >>> topology = Topology.from_molecules(Molecule.from_smiles('[CH4]')) >>> molecule = Molecule.from_topology(topology)
- classmethod from_xml(serialized)
Instantiate an object from an XML serialized representation.
Specification: https://www.w3.org/XML/
- Parameters:
serialized (
bytes
) – An XML serialized representation- Returns:
instance (
cls
) – Instantiated object.
- classmethod from_yaml(serialized)
Instantiate from a YAML serialized representation.
Specification: http://yaml.org/
- Parameters:
serialized (
str
) – A YAML serialized representation of the object- Returns:
instance (
cls
) – Instantiated object
- generate_conformers(toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY, n_conformers: int = 10, rms_cutoff: Optional[Quantity] = None, clear_existing: bool = True, make_carboxylic_acids_cis: bool = True)
Generate conformers for this molecule using an underlying toolkit.
If
n_conformers=0
, no toolkit wrapper will be called. Ifn_conformers=0
andclear_existing=True
,molecule.conformers
will be set toNone
.- Parameters:
toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for SMILES-to-molecule conversionn_conformers (
int
, default1
) – The maximum number of conformers to producerms_cutoff (
openff.unit.Quantity-wrapped float
,in units
ofdistance
, optional, defaultNone
) – The minimum RMS value at which two conformers are considered redundant and one is deleted. Precise implementation of this cutoff may be toolkit-dependent. IfNone
, the cutoff is set to be the default value for eachToolkitWrapper
(generally 1 Angstrom).clear_existing (
bool
, defaultTrue
) – Whether to overwrite existing conformers for the moleculemake_carboxylic_acids_cis (
bool
, defaultTrue
) – Guarantee all conformers have exclusively cis carboxylic acid groups (COOH) by rotating the proton in any trans carboxylic acids 180 degrees around the C-O bond. Works around a bug in conformer generation by the OpenEye toolkit where trans COOH is much more common than it should be.
Examples
>>> molecule = Molecule.from_smiles('CCCCCC') >>> molecule.generate_conformers()
- Raises:
InvalidToolkitRegistryError – If an invalid object is passed as the toolkit_registry parameter
- generate_unique_atom_names()
Generate unique atom names from the element symbol and count.
Names are generated from the elemental symbol and the number of times that element is found in the molecule. The character ‘x’ is appended to these generated names to reduce the odds that they clash with an atom name or type imported from another source. For example, generated atom names might begin ‘C1x’, ‘H1x’, ‘O1x’, ‘C2x’, etc.
- property has_unique_atom_names: bool
True
if the molecule has unique atom names,False
otherwise.
- property hierarchy_schemes: Dict[str, HierarchyScheme]
The hierarchy schemes available on the molecule.
Hierarchy schemes allow iteration over groups of atoms according to their metadata. For more information, see
HierarchyScheme
.- Returns:
A dict of the form {str (
HierarchyScheme``
}``) – The HierarchySchemes associated with the molecule.
See also
Molecule.add_hierarchy_scheme
,Molecule.delete_hierarchy_scheme
,Molecule.update_hierarchy_schemes
,Topology.hierarchy_iterator
,HierarchyScheme
- property hill_formula: str
Get the Hill formula of the molecule
- property impropers: Set[Tuple[Atom, Atom, Atom, Atom]]
Iterate over all improper torsions in the molecule.
Todo
Do we need to return a
Torsion
object that collects information about fractional bond orders?
- Returns:
impropers (
set
oftuple
) – An iterator of tuples, each containing the atoms making up a possible improper torsion.
See also
- is_isomorphic_with(other: Union[FrozenMolecule, _SimpleMolecule, Graph], **kwargs) bool
Check if the molecule is isomorphic with the other molecule which can be an openff.toolkit.topology.Molecule or nx.Graph(). Full matching is done using the options described bellow.
Warning
This API is experimental and subject to change.
- Parameters:
other (
openff.toolkit.topology.Molecule
ornx.Graph()
) –atoms. (compare the formal charges attributes of the) –
atoms. –
bond_order_matching (
bool
,deafult=True
, optional) –bonds. (compare the bond order on attributes of the) –
atom_stereochemistry_matching (
bool
, defaultTrue
, optional) – IfFalse
, atoms’ stereochemistry is ignored for the purpose of determining equality.bond_stereochemistry_matching (
bool
, defaultTrue
, optional) – IfFalse
, bonds’ stereochemistry is ignored for the purpose of determining equality.strip_pyrimidal_n_atom_stereo (
bool
, defaultTrue
, optional) – IfTrue
, any stereochemistry defined around pyrimidal nitrogen stereocenters will be disregarded in the isomorphism check.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for removing stereochemistry from pyrimidal nitrogens.
- Returns:
isomorphic (
bool
)
- property n_angles: int
Number of angles in the molecule.
- property n_atoms: int
The number of Atom objects.
- property n_bonds: int
The number of Bond objects in the molecule.
- property n_conformers: int
The number of conformers for this molecule.
- property n_impropers: int
Number of possible improper torsions in the molecule.
- property n_propers: int
Number of proper torsions in the molecule.
- property name: str
The name (or title) of the molecule
- nth_degree_neighbors(n_degrees)
Return canonicalized pairs of atoms whose shortest separation is exactly n bonds. Only pairs with increasing atom indices are returned.
- Parameters:
n (
int
) – The number of bonds separating atoms in each pair- Returns:
neighbors (
iterator
oftuple
ofAtom
) – Tuples (len 2) of atom that are separated byn
bonds.
Notes
The criteria used here relies on minimum distances; when there are multiple valid paths between atoms, such as atoms in rings, the shortest path is considered. For example, two atoms in “meta” positions with respect to each other in a benzene are separated by two paths, one length 2 bonds and the other length 4 bonds. This function would consider them to be 2 apart and would not include them if
n=4
was passed.
- property partial_charges
Returns the partial charges (if present) on the molecule.
- Returns:
partial_charges (
a openff.unit.Quantity - wrapped numpy array [1 x n_atoms]
orNone
) – The partial charges on the molecule’s atoms. Returns None if no charges have been specified.
- property propers: Set[Tuple[Atom, Atom, Atom, Atom]]
Iterate over all proper torsions in the molecule
Todo
Do we need to return a
Torsion
object that collects information about fractional bond orders?
- remap(mapping_dict: Dict[int, int], current_to_new: bool = True, partial: bool = False)
Reorder the atoms in the molecule according to the given mapping dict.
The mapping dict must be a dictionary mapping atom indices to atom indices. Each atom index must be an integer in the half-open interval
[0, n_atoms)
; ie, it must be a valid index into theself.atoms
list. All atom indices in the molecule must be mapped from and to exactly once unlesspartial=True
is given, in which case they must be mapped no more than once. Missing (unlesspartial=True
), out-of-range (including non-integer), or duplicate indices are not allowed in themapping_dict
and will lead to an exception.By default, the mapping dict’s keys are the source indices and its values are destination indices, but this can be changed with the
current_to_new
argument.The keys of the
self.properties["atom_map"]
property are updated for the new ordering. Other values of the properties dictionary are transferred unchanged.Warning
This API is experimental and subject to change.
- Parameters:
mapping_dict – A dictionary of the mapping between indices. The mapping should be indexed starting from 0 for both the source and destination; note that SMILES atom mapping is typically 1-based.
current_to_new – If this is
True
, thenmapping_dict
is of the form{current_index: new_index}
; otherwise, it is of the form{new_index: current_index}
.partial – If
False
(the default), an exception will be raised if any atom is lacking a destination in the atom map. Note that if this isTrue
, atoms without entries in the mapping dict may be moved in addition to those in the dictionary. Note that partial maps must still be in-range and not include duplicates.
- Returns:
new_molecule (
openff.toolkit.topology.molecule.Molecule
) – A copy of the molecule in the new order.- Raises:
RemapIndexError – When an out-of-range, duplicate, or missing index is found in the
mapping_dict
.
See also
- property smirnoff_impropers: Set[Tuple[Atom, Atom, Atom, Atom]]
Iterate over all impropers with trivalent centers, reporting the central atom second.
The central atom is reported second in each torsion. This method reports an improper for each trivalent atom in the molecule, whether or not any given force field would assign it improper torsion parameters.
Also note that this will return 6 possible atom orderings around each improper center. In current SMIRNOFF parameterization, three of these six orderings will be used for the actual assignment of the improper term and measurement of the angles. These three orderings capture the three unique angles that could be calculated around the improper center, therefore the sum of these three terms will always return a consistent energy.
The exact three orderings that will be applied during parameterization can not be determined in this method, since it requires sorting the atom indices, and those indices may change when this molecule is added to a Topology.
For more details on the use of three-fold (‘trefoil’) impropers, see https://openforcefield.github.io/standards/standards/smirnoff/#impropertorsions
- Returns:
impropers (
set
oftuple
) – An iterator of tuples, each containing the indices of atoms making up a possible improper torsion. The central atom is listed second in each tuple.
See also
- strip_atom_stereochemistry(smarts: str, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY)
Delete stereochemistry information for certain atoms, if it is present. This method can be used to “normalize” molecules imported from different cheminformatics toolkits, which differ in which atom centers are considered stereogenic.
- Parameters:
smarts (
str
) – Tagged SMARTS with a single atom with index 1. Any matches for this atom will have any assigned stereocheistry information removed.toolkit_registry (
a :class:`ToolkitRegistry`
orToolkitWrapper
object,optional,
) – default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use for I/O operations
- to_bson()
Return a BSON serialized representation.
Specification: http://bsonspec.org/
- Returns:
serialized (
bytes
) – A BSON serialized representation of the objecft
- to_dict() dict
Return a dictionary representation of the molecule.
Todo
Document the representation standard.
How do we do version control with this standard?
- Returns:
molecule_dict (
dict
) – A dictionary representation of the molecule.
- to_file(file_path, file_format, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Write the current molecule to a file or file-like object
- Parameters:
file_path (
str
orfile-like object
) – A file-like object or the path to the file to be written.file_format (
str
) – Format specifier, one of [‘MOL2’, ‘MOL2H’, ‘SDF’, ‘PDB’, ‘SMI’, ‘CAN’, ‘TDT’] Note that not all toolkits support all formatstoolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=GLOBAL_TOOLKIT_REGISTRYToolkitRegistry
orToolkitWrapper
to use for file writing. If a Toolkit is passed, only the highest-precedence toolkit is used
- Raises:
ValueError – If the requested file_format is not supported by one of the installed cheminformatics toolkits
Examples
>>> molecule = Molecule.from_iupac('imatinib') >>> molecule.to_file('imatinib.mol2', file_format='mol2') >>> molecule.to_file('imatinib.sdf', file_format='sdf') >>> molecule.to_file('imatinib.pdb', file_format='pdb')
- to_hill_formula() str
Generate the Hill formula of this molecule.
- Returns:
formula (
the Hill formula
ofthe molecule
)
:raises NotImplementedError :
if the molecule is not
ofone
ofthe specified types.
:
- to_inchi(fixed_hydrogens: bool = False, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY) str
Create an InChI string for the molecule using the requested toolkit backend. InChI is a standardised representation that does not capture tautomers unless specified using the fixed hydrogen layer.
For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
- Parameters:
fixed_hydrogens (
bool
, defaultFalse
) – If a fixed hydrogen layer should be added to the InChI, if True this will produce a non standard specific InChI string of the molecule.toolkit_registry (
openff.toolkit.utils.toolkits.ToolRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for molecule-to-InChI conversion
- Returns:
inchi (
str
) – The InChI string of the molecule.- Raises:
InvalidToolkitRegistryError – If an invalid object is passed as the toolkit_registry parameter
- to_inchikey(fixed_hydrogens: bool = False, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY)
Create an InChIKey for the molecule using the requested toolkit backend. InChIKey is a standardised representation that does not capture tautomers unless specified using the fixed hydrogen layer.
For information on InChi see here https://iupac.org/who-we-are/divisions/division-details/inchi/
- Parameters:
fixed_hydrogens (
bool
, defaultFalse
) – If a fixed hydrogen layer should be added to the InChI, if True this will produce a non standard specific InChI string of the molecule.toolkit_registry (
openff.toolkit.utils.toolkits.ToolRegistry
) – or openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for molecule-to-InChIKey conversion
- Returns:
inchi_key (
str
) – The InChIKey representation of the molecule.- Raises:
InvalidToolkitRegistryError – If an invalid object is passed as the toolkit_registry parameter
- to_iupac(toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Generate IUPAC name from Molecule
- Returns:
iupac_name (
str
) – IUPAC name of the moleculenote :
:This method requires the OpenEye toolkit
tobe installed.
Examples
>>> from openff.toolkit.utils import get_data_file_path >>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf') >>> molecule = Molecule(sdf_filepath) >>> iupac_name = molecule.to_iupac()
- to_json(indent=None) str
Return a JSON serialized representation.
Specification: https://www.json.org/
- to_messagepack()
Return a MessagePack representation.
Specification: https://msgpack.org/index.html
- Returns:
serialized (
bytes
) – A MessagePack-encoded bytes serialized representation of the object
- to_networkx()
Generate a NetworkX undirected graph from the molecule.
Nodes are Atoms labeled with atom indices and atomic elements (via the
element
node atrribute). Edges denote chemical bonds between Atoms.Todo
Do we need a
from_networkx()
method? If so, what would the Graph be required to provide?Should edges be labeled with discrete bond types in some aromaticity model?
Should edges be labeled with fractional bond order if a method is specified?
Should we add other per-atom and per-bond properties (e.g. partial charges) if present?
Can this encode bond/atom chirality?
- Returns:
graph (
networkx.Graph
) – The resulting graph, with nodes (atoms) labeled with atom indices, elements, stereochemistry and aromaticity flags and bonds with two atom indices, bond order, stereochemistry, and aromaticity flags
Examples
Retrieve the bond graph for imatinib (OpenEye toolkit required)
>>> molecule = Molecule.from_iupac('imatinib') >>> nxgraph = molecule.to_networkx()
- to_openeye(toolkit_registry=GLOBAL_TOOLKIT_REGISTRY, aromaticity_model=DEFAULT_AROMATICITY_MODEL)
Create an OpenEye molecule
Requires the OpenEye toolkit to be installed.
Todo
Use stored conformer positions instead of an argument.
Should the aromaticity model be specified in some other way?
- Parameters:
aromaticity_model (
str
, optional, default"OEAroModel_MDL"
) – The aromaticity model to use. Only OEAroModel_MDL is supported.- Returns:
oemol (
openeye.oechem.OEMol
) – An OpenEye molecule
Examples
Create an OpenEye molecule from a Molecule
>>> molecule = Molecule.from_smiles('CC') >>> oemol = molecule.to_openeye()
- to_pickle()
Return a pickle serialized representation.
Warning
This is not recommended for safe, stable storage since the pickle specification may change between Python versions.
- Returns:
serialized (
str
) – A pickled representation of the object
- to_qcschema(multiplicity=1, conformer=0, extras=None)
Create a QCElemental Molecule.
Warning
This API is experimental and subject to change.
- Parameters:
multiplicity (
int
, default1,
) – The multiplicity of the molecule; setsmolecular_multiplicity
field for QCElemental Molecule.conformer (
int
, default0,
) – The index of the conformer to use for the QCElemental Molecule geometry.extras (
dict
, defaultNone
) – A dictionary that should be included in theextras
field on the QCElemental Molecule. This can be used to include extra information, such as a smiles representation.
- Returns:
qcelemental.models.Molecule
– A validated QCElemental Molecule.
Examples
Create a QCElemental Molecule:
>>> import qcelemental as qcel >>> mol = Molecule.from_smiles('CC') >>> mol.generate_conformers(n_conformers=1) >>> qcemol = mol.to_qcschema()
- Raises:
MissingOptionalDependencyError – If qcelemental is not installed, the qcschema can not be validated.
InvalidConformerError – No conformer found at the given index.
- to_rdkit(aromaticity_model=DEFAULT_AROMATICITY_MODEL, toolkit_registry=GLOBAL_TOOLKIT_REGISTRY)
Create an RDKit molecule
Requires the RDKit to be installed.
- Parameters:
aromaticity_model (
str
, optional, default"OEAroModel_MDL"
) – The aromaticity model to use. Only OEAroModel_MDL is supported.- Returns:
rdmol (
rdkit.RDMol
) – An RDKit molecule
Examples
Convert a molecule to RDKit
>>> from openff.toolkit.utils import get_data_file_path >>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf') >>> molecule = Molecule(sdf_filepath) >>> rdmol = molecule.to_rdkit()
- to_smiles(isomeric: bool = True, explicit_hydrogens: bool = True, mapped: bool = False, toolkit_registry: Union[ToolkitRegistry, ToolkitWrapper] = GLOBAL_TOOLKIT_REGISTRY)
Return a canonical isomeric SMILES representation of the current molecule. A partially mapped smiles can also be generated for atoms of interest by supplying an atom_map to the properties dictionary.
Note
RDKit and OpenEye versions will not necessarily return the same representation.
- Parameters:
isomeric (
bool optional
, default True) – return an isomeric smilesexplicit_hydrogens (
bool optional
, defaultTrue
) – return a smiles string containing all hydrogens explicitlymapped (
bool optional
, defaultFalse
) – return a explicit hydrogen mapped smiles, the atoms to be mapped can be controlled by supplying an atom map into the properties dictionary. If no mapping is passed all atoms will be mapped in order, else an atom map dictionary from the current atom index to the map id should be supplied with no duplicates. The map ids (values) should start from 0 or 1.toolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry or
) – openff.toolkit.utils.toolkits.ToolkitWrapper, optional, default=NoneToolkitRegistry
orToolkitWrapper
to use for SMILES conversion
- Returns:
smiles (
str
) – Canonical isomeric explicit-hydrogen SMILES
Examples
>>> from openff.toolkit.utils import get_data_file_path >>> sdf_filepath = get_data_file_path('molecules/ethanol.sdf') >>> molecule = Molecule(sdf_filepath) >>> smiles = molecule.to_smiles()
- to_toml()
Return a TOML serialized representation.
Specification: https://github.com/toml-lang/toml
- Returns:
serialized (
str
) – A TOML serialized representation of the object
- to_topology()
Return an OpenFF Topology representation containing one copy of this molecule
- Returns:
topology (
openff.toolkit.topology.Topology
) – A Topology representation of this molecule
Examples
>>> from openff.toolkit import Molecule >>> molecule = Molecule.from_iupac('imatinib') >>> topology = molecule.to_topology()
- to_xml(indent=2)
Return an XML representation.
Specification: https://www.w3.org/XML/
- to_yaml()
Return a YAML serialized representation.
Specification: http://yaml.org/
- Returns:
serialized (
str
) – A YAML serialized representation of the object
- property torsions: Set[Tuple[Atom, Atom, Atom, Atom]]
Get an iterator over all i-j-k-l torsions. Note that i-j-k-i torsions (cycles) are excluded.
- Returns:
torsions (
iterable
of4-Atom tuples
)
- update_hierarchy_schemes(iter_names=None)
Infer a hierarchy from atom metadata according to the existing hierarchy schemes.
Hierarchy schemes allow iteration over groups of atoms according to their metadata. For more information, see
HierarchyScheme
.- Parameters:
iter_names (
Iterable
ofstr
,Optional
) – Only perceive hierarchy for HierarchySchemes that expose these iterator names. If not provided, all known hierarchies will be perceived, overwriting previous results if applicable.
See also
Molecule.add_hierarchy_scheme
,Molecule.delete_hierarchy_schemes
,Molecule.hierarchy_schemes
,HierarchyScheme