openforcefield.typing.engines.smirnoff.parameters.ParameterHandler

class openforcefield.typing.engines.smirnoff.parameters.ParameterHandler(allow_cosmetic_attributes=False, skip_version_check=False, **kwargs)[source]

Base class for parameter handlers.

Parameter handlers are configured with some global parameters for a given section. They may also contain a ParameterList populated with ParameterType objects if they are responsible for assigning SMIRKS-based parameters.

Warning

This API is experimental and subject to change.

Attributes
TAGNAME

The name of this ParameterHandler corresponding to the SMIRNOFF tag name

known_kwargs

List of kwargs that can be parsed by the function.

parameters

The ParameterList that holds this ParameterHandler’s parameter objects

version

A descriptor for ParameterType attributes.

The descriptors allows associating to the parameter a default value, which makes the attribute optional, a unit, and a custom converter.

Because we may want to have None as a default value, required attributes have the default set to the special type UNDEFINED.

Converters can be both static or instance functions/methods with respective signatures

converter(value): -> converted_value converter(instance, parameter_attribute, value): -> converted_value

A decorator syntax is available (see example below).

defaultobject, optional

When specified, the descriptor makes this attribute optional by attaching a default value to it.

unitsimtk.unit.Quantity, optional

When specified, only quantities with compatible units are allowed to be set, and string expressions are automatically parsed into a Quantity.

convertercallable, optional

An optional function that can be used to convert values before setting the attribute.

IndexedParameterAttribute

A parameter attribute with multiple terms.

Create a parameter type with an optional and a required attribute.

>>> class MyParameter:
...     attr_required = ParameterAttribute()
...     attr_optional = ParameterAttribute(default=2)
...
>>> my_par = MyParameter()

Even without explicit assignment, the default value is returned.

>>> my_par.attr_optional
2

If you try to access an attribute without setting it first, an exception is raised.

>>> my_par.attr_required
Traceback (most recent call last):
...
AttributeError: 'MyParameter' object has no attribute '_attr_required'

The attribute allow automatic conversion and validation of units.

>>> from simtk import unit
>>> class MyParameter:
...     attr_quantity = ParameterAttribute(unit=unit.angstrom)
...
>>> my_par = MyParameter()
>>> my_par.attr_quantity = '1.0 * nanometer'
>>> my_par.attr_quantity
Quantity(value=1.0, unit=nanometer)
>>> my_par.attr_quantity = 3.0
Traceback (most recent call last):
...
openforcefield.utils.utils.IncompatibleUnitError: attr_quantity=3.0 dimensionless should have units of angstrom

You can attach a custom converter to an attribute.

>>> class MyParameter:
...     # Both strings and integers convert nicely to floats with float().
...     attr_all_to_float = ParameterAttribute(converter=float)
...     attr_int_to_float = ParameterAttribute()
...     @attr_int_to_float.converter
...     def attr_int_to_float(self, attr, value):
...         # This converter converts only integers to float
...         # and raise an exception for the other types.
...         if isinstance(value, int):
...             return float(value)
...         elif not isinstance(value, float):
...             raise TypeError(f"Cannot convert '{value}' to float")
...         return value
...
>>> my_par = MyParameter()

attr_all_to_float accepts and convert to float both strings and integers

>>> my_par.attr_all_to_float = 1
>>> my_par.attr_all_to_float
1.0
>>> my_par.attr_all_to_float = '2.0'
>>> my_par.attr_all_to_float
2.0

The custom converter associated to attr_int_to_float converts only integers instead. >>> my_par.attr_int_to_float = 3 >>> my_par.attr_int_to_float 3.0 >>> my_par.attr_int_to_float = ‘4.0’ Traceback (most recent call last): … TypeError: Cannot convert ‘4.0’ to float

Methods

add_cosmetic_attribute(attr_name, attr_value)

Add a cosmetic attribute to this object.

add_parameter([parameter_kwargs, parameter, …])

Add a parameter to the forcefield, ensuring all parameters are valid.

assign_parameters(topology, system)

Assign parameters for the given Topology to the specified System object.

attribute_is_cosmetic(attr_name)

Determine whether an attribute of this object is cosmetic.

check_handler_compatibility(handler_kwargs)

Checks if a set of kwargs used to create a ParameterHandler are compatible with this ParameterHandler.

delete_cosmetic_attribute(attr_name)

Delete a cosmetic attribute from this object.

find_matches(entity)

Find the elements of the topology/molecule matched by a parameter type.

get_parameter(parameter_attrs)

Return the parameters in this ParameterHandler that match the parameter_attrs argument.

postprocess_system(topology, system, **kwargs)

Allow the force to perform a a final post-processing pass on the System following parameter assignment, if needed.

to_dict([discard_cosmetic_attributes])

Convert this ParameterHandler to an OrderedDict, compliant with the SMIRNOFF data spec.

assign_partial_bond_orders_from_molecules

check_partial_bond_orders_from_molecules_duplicates

__init__(allow_cosmetic_attributes=False, skip_version_check=False, **kwargs)[source]

Initialize a ParameterHandler, optionally with a list of parameters and other kwargs.

Parameters
allow_cosmetic_attributesbool, optional. Default = False

Whether to permit non-spec kwargs. If True, non-spec kwargs will be stored as attributes of this object and can be accessed and modified. Otherwise an exception will be raised if a non-spec kwarg is encountered.

skip_version_check: bool, optional. Default = False

If False, the SMIRNOFF section version will not be checked, and the ParameterHandler will be initialized with version set to _MAX_SUPPORTED_SECTION_VERSION.

**kwargsdict

The dict representation of the SMIRNOFF data source

Methods

__init__([allow_cosmetic_attributes, …])

Initialize a ParameterHandler, optionally with a list of parameters and other kwargs.

add_cosmetic_attribute(attr_name, attr_value)

Add a cosmetic attribute to this object.

add_parameter([parameter_kwargs, parameter, …])

Add a parameter to the forcefield, ensuring all parameters are valid.

assign_parameters(topology, system)

Assign parameters for the given Topology to the specified System object.

assign_partial_bond_orders_from_molecules(…)

attribute_is_cosmetic(attr_name)

Determine whether an attribute of this object is cosmetic.

check_handler_compatibility(handler_kwargs)

Checks if a set of kwargs used to create a ParameterHandler are compatible with this ParameterHandler.

check_partial_bond_orders_from_molecules_duplicates(pb_mols)

delete_cosmetic_attribute(attr_name)

Delete a cosmetic attribute from this object.

find_matches(entity)

Find the elements of the topology/molecule matched by a parameter type.

get_parameter(parameter_attrs)

Return the parameters in this ParameterHandler that match the parameter_attrs argument.

postprocess_system(topology, system, **kwargs)

Allow the force to perform a a final post-processing pass on the System following parameter assignment, if needed.

to_dict([discard_cosmetic_attributes])

Convert this ParameterHandler to an OrderedDict, compliant with the SMIRNOFF data spec.

Attributes

TAGNAME

The name of this ParameterHandler corresponding to the SMIRNOFF tag name

known_kwargs

List of kwargs that can be parsed by the function.

parameters

The ParameterList that holds this ParameterHandler’s parameter objects

version

A descriptor for ParameterType attributes.

property parameters

The ParameterList that holds this ParameterHandler’s parameter objects

property TAGNAME

The name of this ParameterHandler corresponding to the SMIRNOFF tag name

Returns
handler_namestr

The name of this parameter handler

property known_kwargs

List of kwargs that can be parsed by the function.

check_handler_compatibility(handler_kwargs)[source]

Checks if a set of kwargs used to create a ParameterHandler are compatible with this ParameterHandler. This is called if a second handler is attempted to be initialized for the same tag.

Parameters
handler_kwargsdict

The kwargs that would be used to construct

Raises
IncompatibleParameterError if handler_kwargs are incompatible with existing parameters.
add_parameter(parameter_kwargs=None, parameter=None, after=None, before=None)[source]

Add a parameter to the forcefield, ensuring all parameters are valid.

Parameters
parameter_kwargs: dict, optional

The kwargs to pass to the ParameterHandler.INFOTYPE (a ParameterType) constructor

parameter: ParameterType, optional

A ParameterType to add to the ParameterHandler

afterstr or int, optional

The SMIRKS pattern (if str) or index (if int) of the parameter directly before where the new parameter will be added

beforestr, optional

The SMIRKS pattern (if str) or index (if int) of the parameter directly after where the new parameter will be added

Note that one of (parameter_kwargs, parameter) must be specified
Note that when `before` and `after` are both None, the new parameter will be appended

to the END of the parameter list.

Note that when `before` and `after` are both specified, the new parameter

will be added immediately after the parameter matching the after pattern or index.

Examples

Add a ParameterType to an existing ParameterList at a specified position.

Given an existing parameter handler and a new parameter to add to it:

>>> from simtk import unit
>>> bh = BondHandler(skip_version_check=True)
>>> length = 1.5 * unit.angstrom
>>> k = 100 * unit.kilocalorie_per_mole / unit.angstrom ** 2
>>> bh.add_parameter({'smirks': '[*:1]-[*:2]', 'length': length, 'k': k, 'id': 'b1'})
>>> bh.add_parameter({'smirks': '[*:1]=[*:2]', 'length': length, 'k': k, 'id': 'b2'})
>>> bh.add_parameter({'smirks': '[*:1]#[*:2]', 'length': length, 'k': k, 'id': 'b3'})
>>> [p.id for p in bh.parameters]
['b1', 'b2', 'b3']
>>> param = {'smirks': '[#1:1]-[#6:2]', 'length': length, 'k': k, 'id': 'b4'}

Add a new parameter immediately after the parameter with the smirks ‘[:1]=[:2]’

>>> bh.add_parameter(param, after='[*:1]=[*:2]')
>>> [p.id for p in bh.parameters]
['b1', 'b2', 'b4', 'b3']
get_parameter(parameter_attrs)[source]

Return the parameters in this ParameterHandler that match the parameter_attrs argument. When multiple attrs are passed, parameters that have any (not all) matching attributes are returned.

Parameters
parameter_attrsdict of {attr: value}

The attrs mapped to desired values (for example {“smirks”: “[:1]~[#16:2]=,:[#6:3]~[:4]”, “id”: “t105”} )

Returns
paramslist of ParameterType objects

A list of matching ParameterType objects

Examples

Create a parameter handler and populate it with some data.

>>> from simtk import unit
>>> handler = BondHandler(skip_version_check=True)
>>> handler.add_parameter(
...     {
...         'smirks': '[*:1]-[*:2]',
...         'length': 1*unit.angstrom,
...         'k': 10*unit.kilocalorie_per_mole/unit.angstrom**2,
...     }
... )

Look up, from this handler, all parameters matching some SMIRKS pattern

>>> handler.get_parameter({'smirks': '[*:1]-[*:2]'})
[<BondType with smirks: [*:1]-[*:2]  length: 1 A  k: 10 kcal/(A**2 mol)  >]
find_matches(entity)[source]

Find the elements of the topology/molecule matched by a parameter type.

Parameters
entityopenforcefield.topology.Topology

Topology to search.

Returns
matchesValenceDict[Tuple[int], ParameterHandler._Match]

matches[particle_indices] is the ParameterType object matching the tuple of particle indices in entity.

assign_parameters(topology, system)[source]

Assign parameters for the given Topology to the specified System object.

Parameters
topologyopenforcefield.topology.Topology

The Topology for which parameters are to be assigned. Either a new Force will be created or parameters will be appended to an existing Force.

systemsimtk.openmm.System

The OpenMM System object to add the Force (or append new parameters) to.

postprocess_system(topology, system, **kwargs)[source]

Allow the force to perform a a final post-processing pass on the System following parameter assignment, if needed.

Parameters
topologyopenforcefield.topology.Topology

The Topology for which parameters are to be assigned. Either a new Force will be created or parameters will be appended to an existing Force.

systemsimtk.openmm.System

The OpenMM System object to add the Force (or append new parameters) to.

to_dict(discard_cosmetic_attributes=False)[source]

Convert this ParameterHandler to an OrderedDict, compliant with the SMIRNOFF data spec.

Parameters
discard_cosmetic_attributesbool, optional. Default = False.

Whether to discard non-spec parameter and header attributes in this ParameterHandler.

Returns
smirnoff_dataOrderedDict

SMIRNOFF-spec compliant representation of this ParameterHandler and its internal ParameterList.

add_cosmetic_attribute(attr_name, attr_value)

Add a cosmetic attribute to this object.

This attribute will not have a functional effect on the object in the Open Force Field toolkit, but can be written out during output.

Warning

The API for modifying cosmetic attributes is experimental and may change in the future (see issue #338).

Parameters
attr_namestr

Name of the attribute to define for this object.

attr_valuestr

The value of the attribute to define for this object.

attribute_is_cosmetic(attr_name)

Determine whether an attribute of this object is cosmetic.

Warning

The API for modifying cosmetic attributes is experimental and may change in the future (see issue #338).

Parameters
attr_namestr

The attribute name to check

Returns
is_cosmeticbool

Returns True if the attribute is defined and is cosmetic. Returns False otherwise.

delete_cosmetic_attribute(attr_name)

Delete a cosmetic attribute from this object.

Warning

The API for modifying cosmetic attributes is experimental and may change in the future (see issue #338).

Parameters
attr_namestr

Name of the cosmetic attribute to delete.