ForceField
- class openff.toolkit.typing.engines.smirnoff.ForceField(*sources, aromaticity_model: str = DEFAULT_AROMATICITY_MODEL, parameter_handler_classes=None, parameter_io_handler_classes=None, disable_version_check: bool = False, allow_cosmetic_attributes: bool = False, load_plugins: bool = False)[source]
A factory that assigns SMIRNOFF parameters to a molecular system
ForceField
is a factory that constructs an OpenMMSystem
object from aTopology
object defining a (bio)molecular system containing one or more molecules.When a
ForceField
object is created from one or more specified SMIRNOFF serialized representations, allParameterHandler
subclasses currently imported are identified and registered to handle different sections of the SMIRNOFF force field definition file(s).All
ParameterIOHandler
subclasses currently imported are identified and registered to handle different serialization formats (such as XML).The force field definition is processed by these handlers to populate the
ForceField
object model data structures that can easily be manipulated via the API:Processing a
Topology
object defining a chemical system will then call allParameterHandler
objects in an order guaranteed to satisfy the declared processing order constraints of eachParameterHandler
.Examples
Create a new ForceField object from the distributed OpenFF 2.0 (“Sage”) file:
>>> from openff.toolkit import ForceField >>> force_field = ForceField('openff-2.0.0.offxml')
Create an OpenMM system from a
openff.toolkit.topology.Topology
object:>>> from openff.toolkit import Molecule, Topology >>> ethanol = Molecule.from_smiles('CCO') >>> topology = Topology.from_molecules(molecules=[ethanol]) >>> system = force_field.create_openmm_system(topology)
Modify the long-range electrostatics method:
>>> force_field.get_parameter_handler('Electrostatics').periodic_potential = 'PME'
Inspect the first few vdW parameters:
>>> low_precedence_parameters = force_field.get_parameter_handler('vdW').parameters[0:3]
Retrieve the vdW parameters by SMIRKS string and manipulate it:
>>> from openff.units import unit >>> parameter = force_field.get_parameter_handler('vdW').parameters['[#1:1]-[#7]'] >>> parameter.rmin_half += 0.1 * unit.angstroms >>> parameter.epsilon *= 1.02
Make a child vdW type more specific (checking modified SMIRKS for validity):
>>> force_field.get_parameter_handler('vdW').parameters[-1].smirks += '~[#53]'
Warning
While we check whether the modified SMIRKS is still valid and has the appropriate valence type, we currently don’t check whether the typing remains hierarchical, which could result in some types no longer being assignable because more general types now come below them and preferentially match.
Delete a parameter:
>>> del force_field.get_parameter_handler('vdW').parameters['[#1:1]-[#6X4]']
Insert a parameter at a specific point in the parameter tree:
>>> from openff.toolkit.typing.engines.smirnoff import vdWHandler >>> new_parameter = vdWHandler.vdWType( ... smirks='[*:1]', ... epsilon=0.0157*unit.kilocalories_per_mole, ... rmin_half=0.6000*unit.angstroms, ... ) >>> force_field.get_parameter_handler('vdW').parameters.insert(0, new_parameter)
Warning
We currently don’t check whether removing a parameter could accidentally remove the root type, so it’s possible to no longer type all molecules this way.
- __init__(*sources, aromaticity_model: str = DEFAULT_AROMATICITY_MODEL, parameter_handler_classes=None, parameter_io_handler_classes=None, disable_version_check: bool = False, allow_cosmetic_attributes: bool = False, load_plugins: bool = False)[source]
Create a new
ForceField
object from one or more SMIRNOFF parameter definition files.- Parameters:
sources (string or file-like object or open file handle or URL (or iterable of these)) – A list of files defining the SMIRNOFF force field to be loaded. Currently, only the SMIRNOFF XML format is supported. Each entry may be an absolute file path, a path relative to the current working directory, a path relative to this module’s data subdirectory (for built in force fields), or an open file-like object with a
read()
method from which the force field XML data can be loaded. If multiple files are specified, any top-level tags that are repeated will be merged if they are compatible, with files appearing later in the sequence resulting in parameters that have higher precedence. Support for multiple files is primarily intended to allow solvent parameters to be specified by listing them last in the sequence.aromaticity_model (str, optional, default="OEAroModel_MDL") – The aromaticity model to use. Only OEAroModel_MDL is supported.
parameter_handler_classes (iterable of ParameterHandler classes, optional, default=None) – If not None, the specified set of ParameterHandler classes will be instantiated to create the parameter object model. By default, all imported subclasses of ParameterHandler not loaded as plugins are automatically registered.
parameter_io_handler_classes (iterable of ParameterIOHandler classes) – If not None, the specified set of ParameterIOHandler classes will be used to parse/generate serialized parameter sets. By default, all imported subclasses of ParameterIOHandler are automatically registered.
disable_version_check (bool, optional, default=False) – If True, will disable checks against the current highest supported force field version. This option is primarily intended for force field development.
allow_cosmetic_attributes (bool, optional. Default = False) – Whether to retain non-spec kwargs from data sources.
load_plugins (bool, optional. Default = False) – Whether to load
ParameterHandler
classes which have been registered by installed plugins.
Examples
Load one SMIRNOFF parameter set in XML format (searching the package data directory by default, which includes some standard parameter sets):
>>> forcefield = ForceField('openff-2.0.0.offxml')
Load multiple SMIRNOFF parameter sets:
>>> from openff.toolkit._tests.utils import get_data_file_path >>> forcefield = ForceField('openff-2.0.0.offxml', get_data_file_path('test_forcefields/tip3p.offxml'))
Load a parameter set from a string:
>>> offxml = '<SMIRNOFF version="0.2" aromaticity_model="OEAroModel_MDL"/>' >>> forcefield = ForceField(offxml)
Methods
__init__
(*sources[, aromaticity_model, ...])Create a new
ForceField
object from one or more SMIRNOFF parameter definition files.create_interchange
(topology[, ...])Create an Interchange object from a ForceField, Topology, and (optionally) box vectors.
create_openmm_system
(topology, *[, ...])Create an OpenMM System from this ForceField and a Topology.
deregister_parameter_handler
(handler)Deregister a parameter handler specified by tag name, class, or instance.
get_parameter_handler
(tagname[, ...])Retrieve the parameter handlers associated with the provided tagname.
get_parameter_io_handler
(io_format)Retrieve the parameter handlers associated with the provided tagname.
get_partial_charges
(molecule, **kwargs)Generate the partial charges for the given molecule in this force field.
label_molecules
(topology)Return labels for a list of molecules corresponding to parameters from this force field.
parse_smirnoff_from_source
(source)Reads a SMIRNOFF data structure from a source, which can be one of many types.
parse_sources
(sources[, ...])Parse a SMIRNOFF force field definition.
register_parameter_handler
(parameter_handler)Register a new ParameterHandler for a specific tag, making it available for lookup in the ForceField.
Register a new ParameterIOHandler, making it available for lookup in the ForceField.
to_file
(filename[, io_format, ...])Write this Forcefield and all its associated parameters to a string in a given format which complies with the SMIRNOFF spec.
to_string
([io_format, ...])Write this Forcefield and all its associated parameters to a string in a given format which complies with the SMIRNOFF spec.
Attributes
Returns the aromaticity model for this ForceField object.
Returns the author data for this ForceField object.
Returns the date data for this ForceField object.
Return the list of registered parameter handlers by name
- property aromaticity_model
Returns the aromaticity model for this ForceField object.
- Returns:
aromaticity_model – The aromaticity model for this force field.
- property author
Returns the author data for this ForceField object. If not defined in any loaded files, this will be None.
- Returns:
author (str) – The author data for this force field.
- property date
Returns the date data for this ForceField object. If not defined in any loaded files, this will be None.
- Returns:
date (str) – The date data for this force field.
- register_parameter_handler(parameter_handler)[source]
Register a new ParameterHandler for a specific tag, making it available for lookup in the ForceField.
Warning
This API is experimental and subject to change.
- Parameters:
parameter_handler (A ParameterHandler object) – The ParameterHandler to register. The TAGNAME attribute of this object will be used as the key for registration.
- register_parameter_io_handler(parameter_io_handler)[source]
Register a new ParameterIOHandler, making it available for lookup in the ForceField.
Warning
This API is experimental and subject to change.
- Parameters:
parameter_io_handler (A ParameterIOHandler object) – The ParameterIOHandler to register. The FORMAT attribute of this object will be used to associate it to a file format/suffix.
- property registered_parameter_handlers: List[str]
Return the list of registered parameter handlers by name
Warning
This API is experimental and subject to change.
- Returns:
registered_parameter_handlers (iterable of names of ParameterHandler objects in this ForceField)
- get_parameter_handler(tagname, handler_kwargs=None, allow_cosmetic_attributes=False)[source]
Retrieve the parameter handlers associated with the provided tagname.
If the parameter handler has not yet been instantiated, it will be created and returned. If a parameter handler object already exists, it will be checked for compatibility and an Exception raised if it is incompatible with the provided kwargs. If compatible, the existing ParameterHandler will be returned.
- Parameters:
tagname (str) – The name of the parameter to be handled.
handler_kwargs (dict, optional. Default = None) – Dict to be passed to the handler for construction or checking compatibility. If this is None and no existing ParameterHandler exists for the desired tag, a handler will be initialized with all default values. If this is None and a handler for the desired tag exists, the existing ParameterHandler will be returned.
allow_cosmetic_attributes (bool, optional. Default = False) – Whether to permit non-spec kwargs in smirnoff_data.
- Returns:
handler (An openff.toolkit.engines.typing.smirnoff.ParameterHandler)
- Raises:
KeyError – If there is no ParameterHandler for the given tagname
- get_parameter_io_handler(io_format)[source]
Retrieve the parameter handlers associated with the provided tagname. If the parameter IO handler has not yet been instantiated, it will be created.
- deregister_parameter_handler(handler)[source]
Deregister a parameter handler specified by tag name, class, or instance.
- parse_sources(sources, allow_cosmetic_attributes=True)[source]
Parse a SMIRNOFF force field definition.
- Parameters:
sources (string or file-like object or open file handle or URL (or iterable of these)) –
A list of files defining the SMIRNOFF force field to be loaded. Currently, only the SMIRNOFF XML format is supported. Each entry may be an absolute file path, a path relative to the current working directory, a path relative to this module’s data subdirectory (for built in force fields), or an open file-like object with a
read()
method from which the force field XML data can be loaded. If multiple files are specified, any top-level tags that are repeated will be merged if they are compatible, with files appearing later in the sequence resulting in parameters that have higher precedence. Support for multiple files is primarily intended to allow solvent parameters to be specified by listing them last in the sequence.allow_cosmetic_attributes (bool, optional. Default = False) – Whether to permit non-spec kwargs present in the source.
Notes
New SMIRNOFF sections are handled independently, as if they were specified in the same file.
- If a SMIRNOFF section that has already been read appears again, its definitions are appended to the end
of the previously-read definitions if the sections are configured with compatible attributes; otherwise, an
IncompatibleTagException
is raised.
- parse_smirnoff_from_source(source) dict [source]
Reads a SMIRNOFF data structure from a source, which can be one of many types.
- Parameters:
source (str or bytes or file-like object) –
File defining the SMIRNOFF force field to be loaded Currently, only the SMIRNOFF XML format is supported. The file may be an absolute file path, a path relative to the current working directory, a path relative to this module’s data subdirectory (for built in force fields), or an open file-like object with a
read()
method from which the force field XML data can be loaded.- Returns:
smirnoff_data (dict) – A representation of a SMIRNOFF-format data structure. Begins at top-level ‘SMIRNOFF’ key.
- to_string(io_format='XML', discard_cosmetic_attributes=False)[source]
Write this Forcefield and all its associated parameters to a string in a given format which complies with the SMIRNOFF spec.
- Parameters:
io_format (str or ParameterIOHandler, optional. Default='XML') – The serialization format to write to
discard_cosmetic_attributes (bool, default=False) – Whether to discard any non-spec attributes stored in the ForceField.
- Returns:
forcefield_string (str) – The string representation of the serialized force field
- to_file(filename, io_format=None, discard_cosmetic_attributes=False)[source]
Write this Forcefield and all its associated parameters to a string in a given format which complies with the SMIRNOFF spec.
- Parameters:
filename (str) – The filename to write to
io_format (str or ParameterIOHandler, optional. Default=None) – The serialization format to write out. If None, will attempt to be inferred from the filename.
discard_cosmetic_attributes (bool, default=False) – Whether to discard any non-spec attributes stored in the ForceField.
- Returns:
forcefield_string (str) – The string representation of the serialized force field
- create_openmm_system(topology: Topology, *, toolkit_registry: Optional[Union[ToolkitRegistry, ToolkitWrapper]] = None, charge_from_molecules: Optional[List[Molecule]] = None, partial_bond_orders_from_molecules: Optional[List[Molecule]] = None, allow_nonintegral_charges: bool = False) openmm.System [source]
Create an OpenMM System from this ForceField and a Topology.
Note that most force fields specify their own partial charges, and any partial charges defined on the
Molecule
objects in the topology are ignored. To use custom partial charges, see thecharge_from_molecules
argument.- Parameters:
topology – The
Topology
which is to be parameterized with thisForceField
.toolkit_registry – The toolkit registry to use for parametrization (eg, for calculating partial charges and partial bond orders)
charge_from_molecules – Take partial charges from the input topology rather than calculating them. This may be useful for avoiding recalculating charges, but take care to ensure that your charges are appropriate for the force field.
partial_bond_orders_from_molecules – Take partial bond orders from the input topology rather than calculating them. This may be useful for avoiding recalculating PBOs, but take to ensure that they are appropriate for the force field.
allow_nonintegral_charges – Allow charges that do not sum to an integer.
- create_interchange(topology: Topology, toolkit_registry: Optional[Union[ToolkitRegistry, ToolkitWrapper]] = None, charge_from_molecules: Optional[List[Molecule]] = None, partial_bond_orders_from_molecules: Optional[List[Molecule]] = None, allow_nonintegral_charges: bool = False)[source]
Create an Interchange object from a ForceField, Topology, and (optionally) box vectors.
WARNING: This API and functionality are experimental and not suitable for production.
- Parameters:
topology (Topology) – The topology to create this Interchange object from.
toolkit_registry – The toolkit registry to use for parametrization (eg, for calculating partial charges and partial bond orders)
charge_from_molecules – Take charges from the input topology rather than calculating them. This may be useful for avoiding recalculating charges, but take care to ensure that your charges are appropriate for the force field.
partial_bond_orders_from_molecules – Take partial bond orders from the input topology rather than calculating them. This may be useful for avoiding recalculating PBOs, but take to ensure that they are appropriate for the force field.
allow_nonintegral_charges – Allow charges that do not sum to an integer.
- Returns:
interchange (openff.interchange.Interchange) – An Interchange object resulting from applying this ForceField to a Topology.
- label_molecules(topology)[source]
Return labels for a list of molecules corresponding to parameters from this force field.
For each molecule, a dictionary of force types is returned, and for each force type, each force term is provided with the atoms involved, the parameter id assigned, and the corresponding SMIRKS.
- Parameters:
topology (Topology) – A Topology object containing one or more unique molecules to be labeled
- Returns:
molecule_labels (list) – List of labels for unique molecules. Each entry in the list corresponds to one unique molecule in the Topology and is a dictionary keyed by force type, i.e.,
molecule_labels[0] ['HarmonicBondForce']
gives details for the harmonic bond parameters for the first molecule. Each element is a list of the form:[ ( [ atom1, ..., atomN], parameter_id, SMIRKS), ... ]
.
- get_partial_charges(molecule: Molecule, **kwargs) Quantity [source]
Generate the partial charges for the given molecule in this force field.
- Parameters:
molecule (
openff.toolkit.topology.Molecule
) – TheMolecule
corresponding to the system to be parameterizedtoolkit_registry (
openff.toolkit.utils.toolkits.ToolkitRegistry
, default=GLOBAL_TOOLKIT_REGISTRY) – The toolkit registry to use for operations like conformer generation and partial charge assignment.
- Returns:
charges (
openff.units.Quantity
with shape(n_atoms,)
and dimensions of charge) – The partial charges of the provided molecule in this force field.- Raises:
PartialChargeVirtualSitesError – If the
ForceField
applies virtual sites to theMolecule
.get_partial_charges
cannot identify which virtual site charges may belong to which atoms in this case.Other exceptions – As any
ParameterHandler
may in principle modify charges, the entire force field must be applied to the molecule to produce the charges. Calls to this method from incorrectly or incompletely specifiedForceField
objects thus may raise an exception.
Examples
>>> from openff.toolkit import ForceField, Molecule >>> ethanol = Molecule.from_smiles('CCO') >>> force_field = ForceField('openff-2.0.0.offxml')
Assign partial charges to the molecule according to the force field:
>>> ethanol.partial_charges = force_field.get_partial_charges(ethanol)
Use the assigned partial charges when creating an OpenMM
System
:>>> topology = ethanol.to_topology() >>> system = force_field.create_openmm_system( ... topology, ... charge_from_molecules=[ethanol] ... )
This is especially useful when you want to create multiple systems with the same molecule or molecules, as it allows the expensive charge calculation to be cached.