-
Notifications
You must be signed in to change notification settings - Fork 92
/
parameters.py
5260 lines (4324 loc) · 209 KB
/
parameters.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Parameter handlers for the SMIRNOFF force field engine
This file contains standard parameter handlers for the SMIRNOFF force field engine.
These classes implement the object model for self-contained parameter assignment.
New pluggable handlers can be created by creating subclasses of :class:`ParameterHandler`.
"""
__all__ = [
"DuplicateParameterError",
"DuplicateVirtualSiteTypeException",
"FractionalBondOrderInterpolationMethodUnsupportedError",
"IncompatibleParameterError",
"NonintegralMoleculeChargeException",
"NotEnoughPointsForInterpolationError",
"ParameterLookupError",
"SMIRNOFFSpecError",
"SMIRNOFFSpecUnimplementedError",
"UnassignedAngleParameterException",
"UnassignedBondParameterException",
"UnassignedMoleculeChargeException",
"UnassignedProperTorsionParameterException",
"UnassignedValenceParameterException",
"NonbondedMethod",
"ParameterList",
"ParameterType",
"ParameterHandler",
"ParameterAttribute",
"MappedParameterAttribute",
"IndexedParameterAttribute",
"IndexedMappedParameterAttribute",
"ConstraintHandler",
"BondHandler",
"AngleHandler",
"ProperTorsionHandler",
"ImproperTorsionHandler",
"ElectrostaticsHandler",
"LibraryChargeHandler",
"vdWHandler",
"GBSAHandler",
"ToolkitAM1BCCHandler",
"VirtualSiteHandler",
]
import copy
import functools
import inspect
import logging
import re
from collections import OrderedDict, defaultdict
from enum import Enum
from typing import Any, List, Optional, Tuple, Union, cast
try:
import openmm
from openmm import unit
except ImportError:
from simtk import openmm, unit
from typing import Dict, Tuple
import numpy as np
from typing_extensions import Literal, get_args
from openff.toolkit.topology import (
ImproperDict,
TagSortedDict,
Topology,
TopologyAtom,
ValenceDict,
)
from openff.toolkit.topology.molecule import (
BondChargeVirtualSite,
DivalentLonePairVirtualSite,
Molecule,
MonovalentLonePairVirtualSite,
TrivalentLonePairVirtualSite,
)
from openff.toolkit.topology.topology import NotBondedError
from openff.toolkit.typing.chemistry import ChemicalEnvironment
from openff.toolkit.utils.collections import ValidatedDict, ValidatedList
from openff.toolkit.utils.exceptions import (
DuplicateParameterError,
DuplicateVirtualSiteTypeException,
FractionalBondOrderInterpolationMethodUnsupportedError,
IncompatibleParameterError,
MissingIndexedAttributeError,
NonintegralMoleculeChargeException,
NotEnoughPointsForInterpolationError,
ParameterLookupError,
SMIRNOFFSpecError,
SMIRNOFFSpecUnimplementedError,
UnassignedAngleParameterException,
UnassignedBondParameterException,
UnassignedMoleculeChargeException,
UnassignedProperTorsionParameterException,
UnassignedValenceParameterException,
)
from openff.toolkit.utils.toolkits import GLOBAL_TOOLKIT_REGISTRY
from openff.toolkit.utils.utils import (
IncompatibleUnitError,
attach_units,
extract_serialized_units_from_dict,
object_to_quantity,
)
# =============================================================================================
# CONFIGURE LOGGER
# =============================================================================================
logger = logging.getLogger(__name__)
# ======================================================================
# ENUM TYPES
# ======================================================================
class NonbondedMethod(Enum):
"""
An enumeration of the nonbonded methods
"""
NoCutoff = 0
CutoffPeriodic = 1
CutoffNonPeriodic = 2
Ewald = 3
PME = 4
# ======================================================================
# UTILITY FUNCTIONS
# ======================================================================
def _linear_inter_or_extrapolate(points_dict, x_query):
"""
Linearly interpolate or extrapolate based on a piecewise linear function defined by a set of points.
This function is designed to work with key:value pairs where the value may be a openmm.unit.Quantity.
Parameters
----------
points_dict : dict{float: float or float-valued openmm.unit.Quantity}
A dictionary with each item representing a point, where the key is the X value and the value is the Y value.
x_query : float
The X value of the point to interpolate or extrapolate.
Returns
-------
y_value : float or float-valued openmm.unit.Quantity
The result of interpolation/extrapolation.
"""
# pre-empt case where no interpolation is necessary
if x_query in points_dict:
return points_dict[x_query]
if len(points_dict) < 2:
raise NotEnoughPointsForInterpolationError(
f"Unable to perform interpolation with less than two points. "
f"points_dict: {points_dict} x_query: {x_query}"
)
# TODO: error out for nonsensical fractional bond orders
# find the nearest point beneath our queried x value
try:
below = max(bo for bo in points_dict if bo < x_query)
except ValueError:
below = None
# find the nearest point above our queried x value
try:
above = min(bo for bo in points_dict if bo > x_query)
except ValueError:
above = None
# handle case where we can clearly interpolate
if (above is not None) and (below is not None):
return points_dict[below] + (points_dict[above] - points_dict[below]) * (
(x_query - below) / (above - below)
)
# error if we can't hope to interpolate at all
elif (above is None) and (below is None):
raise NotImplementedError(
f"Failed to find interpolation references for "
f"`x_query` '{x_query}', "
f"with `points_dict` '{points_dict}'"
)
# extrapolate for fractional bond orders below our lowest defined bond order
elif below is None:
bond_orders = sorted(points_dict)
k = points_dict[bond_orders[0]] - (
(points_dict[bond_orders[1]] - points_dict[bond_orders[0]])
/ (bond_orders[1] - bond_orders[0])
) * (bond_orders[0] - x_query)
return k
# extrapolate for fractional bond orders above our highest defined bond order
elif above is None:
bond_orders = sorted(points_dict)
k = points_dict[bond_orders[-1]] + (
(points_dict[bond_orders[-1]] - points_dict[bond_orders[-2]])
/ (bond_orders[-1] - bond_orders[-2])
) * (x_query - bond_orders[-1])
return k
# TODO: This is technically a validator, not a converter, but ParameterAttribute doesn't support them yet (it'll be easy if we switch to use the attrs library).
def _allow_only(allowed_values):
"""A converter that checks the new value is only in a set."""
allowed_values = frozenset(allowed_values)
def _value_checker(instance, attr, new_value):
# This statement means that, in the "SMIRNOFF Data Dict" format, the string "None"
# and the Python None are the same thing
if new_value == "None":
new_value = None
# Ensure that the new value is in the list of allowed values
if new_value not in allowed_values:
err_msg = (
f"Attempted to set {instance.__class__.__name__}.{attr.name} "
f"to {new_value}. Currently, only the following values "
f"are supported: {sorted(allowed_values)}."
)
raise SMIRNOFFSpecError(err_msg)
return new_value
return _value_checker
def _compute_lj_sigma(
sigma: Optional[unit.Quantity], rmin_half: Optional[unit.Quantity]
) -> unit.Quantity:
return sigma if sigma is not None else (2.0 * rmin_half / (2.0 ** (1.0 / 6.0))) # type: ignore
def _validate_units(attr, value: Union[str, unit.Quantity], units: unit.Unit):
value = object_to_quantity(value)
try:
if not units.is_compatible(value.unit):
raise IncompatibleUnitError(
f"{attr.name}={value} should have units of {units}"
)
except AttributeError:
raise IncompatibleUnitError(f"{attr.name}={value} should have units of {units}")
return value
# ======================================================================
# PARAMETER ATTRIBUTES
# ======================================================================
# TODO: Think about adding attrs to the dependencies and inherit from attr.ib
class ParameterAttribute:
"""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).
Parameters
----------
default : object, optional
When specified, the descriptor makes this attribute optional by
attaching a default value to it.
unit : openmm.unit.Quantity, optional
When specified, only quantities with compatible units are allowed
to be set, and string expressions are automatically parsed into a
``Quantity``.
converter : callable, optional
An optional function that can be used to convert values before
setting the attribute.
See Also
--------
IndexedParameterAttribute
A parameter attribute with multiple terms.
Examples
--------
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 openmm 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):
...
openff.toolkit.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
"""
class UNDEFINED:
"""Custom type used by ``ParameterAttribute`` to differentiate between ``None`` and undeclared default."""
pass
def __init__(self, default=UNDEFINED, unit=None, converter=None, docstring=""):
self.default = default
self._unit = unit
self._converter = converter
self.__doc__ = docstring
def __set_name__(self, owner, name):
self._name = "_" + name
@property
def name(self):
# Get rid of the initial underscore.
return self._name[1:]
def __get__(self, instance, owner):
if instance is None:
# This is called from the class. Return the descriptor object.
return self
try:
return getattr(instance, self._name)
except AttributeError:
# The attribute has not initialized. Check if there's a default.
if self.default is ParameterAttribute.UNDEFINED:
raise
return self.default
def __set__(self, instance, value):
# Convert and validate the value.
value = self._convert_and_validate(instance, value)
setattr(instance, self._name, value)
def converter(self, converter):
"""Create a new ParameterAttribute with an associated converter.
This is meant to be used as a decorator (see main examples).
"""
return self.__class__(default=self.default, converter=converter)
def _convert_and_validate(self, instance, value):
"""Convert to Quantity, validate units, and call custom converter."""
# The default value is always allowed.
if self._is_valid_default(value):
return value
# Convert and validate units.
value = self._validate_units(value)
# Call the custom converter before setting the value.
value = self._call_converter(value, instance)
return value
def _is_valid_default(self, value):
"""Return True if this is a defined default value."""
return (
self.default is not ParameterAttribute.UNDEFINED and value == self.default
)
def _validate_units(self, value):
"""Convert strings expressions to Quantity and validate the units if requested."""
if self._unit is not None:
# Convert eventual strings to Quantity objects.
value = object_to_quantity(value)
# Check if units are compatible.
try:
if not self._unit.is_compatible(value.unit):
raise IncompatibleUnitError(
f"{self.name}={value} should have units of {self._unit}"
)
except AttributeError:
# This is not a Quantity object.
raise IncompatibleUnitError(
f"{self.name}={value} should have units of {self._unit}"
)
return value
def _call_converter(self, value, instance):
"""Correctly calls static and instance converters."""
if self._converter is not None:
try:
# Static function.
return self._converter(value)
except TypeError:
# Instance method.
return self._converter(instance, self, value)
return value
class IndexedParameterAttribute(ParameterAttribute):
"""The attribute of a parameter with an unspecified number of terms.
Some parameters can be associated to multiple terms, For example,
torsions have parameters such as k1, k2, ..., and ``IndexedParameterAttribute``
can be used to encapsulate the sequence of terms.
The only substantial difference with ``ParameterAttribute`` is that
only sequences are supported as values and converters and units are
checked on each element of the sequence.
Currently, the descriptor makes the sequence immutable. This is to
avoid that an element of the sequence could be set without being
properly validated. In the future, the data could be wrapped in a
safe list that would safely allow mutability.
Parameters
----------
default : object, optional
When specified, the descriptor makes this attribute optional by
attaching a default value to it.
unit : openmm.unit.Quantity, optional
When specified, only sequences of quantities with compatible units
are allowed to be set.
converter : callable, optional
An optional function that can be used to validate and cast each
element of the sequence before setting the attribute.
See Also
--------
ParameterAttribute
A simple parameter attribute.
MappedParameterAttribute
A parameter attribute representing a mapping.
IndexedMappedParameterAttribute
A parameter attribute representing a sequence, each term of which is a mapping.
Examples
--------
Create an optional indexed attribute with unit of angstrom.
>>> from openmm import unit
>>> class MyParameter:
... length = IndexedParameterAttribute(default=None, unit=unit.angstrom)
...
>>> my_par = MyParameter()
>>> my_par.length is None
True
Strings are parsed into Quantity objects.
>>> my_par.length = ['1 * angstrom', 0.5 * unit.nanometer]
>>> my_par.length[0]
Quantity(value=1, unit=angstrom)
Similarly, custom converters work as with ``ParameterAttribute``, but
they are used to validate each value in the sequence.
>>> class MyParameter:
... attr_indexed = IndexedParameterAttribute(converter=float)
...
>>> my_par = MyParameter()
>>> my_par.attr_indexed = [1, '1.0', '1e-2', 4.0]
>>> my_par.attr_indexed
[1.0, 1.0, 0.01, 4.0]
"""
def _convert_and_validate(self, instance, value):
"""Overwrite ParameterAttribute._convert_and_validate to make the value a ValidatedList."""
# The default value is always allowed.
if self._is_valid_default(value):
return value
# We push the converters into a ValidatedList so that we can make
# sure that elements are validated correctly when they are modified
# after their initialization.
# ValidatedList expects converters that take the value as a single
# argument so we create a partial function with the instance assigned.
static_converter = functools.partial(self._call_converter, instance=instance)
value = ValidatedList(value, converter=[self._validate_units, static_converter])
return value
class MappedParameterAttribute(ParameterAttribute):
"""The attribute of a parameter in which each term is a mapping.
The substantial difference with ``IndexedParameterAttribute`` is that, unlike
indexing, the mapping can be based on artbitrary references, like indices but
can starting at non-zero values and include non-adjacent keys.
Parameters
----------
default : object, optional
When specified, the descriptor makes this attribute optional by
attaching a default value to it.
unit : openmm.unit.Quantity, optional
When specified, only sequences of mappings where values are quantities with
compatible units are allowed to be set.
converter : callable, optional
An optional function that can be used to validate and cast each
component of each element of the sequence before setting the attribute.
See Also
--------
IndexedParameterAttribute
A parameter attribute representing a sequence.
IndexedMappedParameterAttribute
A parameter attribute representing a sequence, each term of which is a mapping.
Examples
--------
Create an optional indexed attribute with unit of angstrom.
>>> from openmm import unit
>>> class MyParameter:
... length = MappedParameterAttribute(default=None, unit=unit.angstrom)
...
>>> my_par = MyParameter()
>>> my_par.length is None
True
Like other ParameterAttribute objects, strings are parsed into Quantity objects.
>>> my_par.length = {1:'1.5 * angstrom', 2: '1.4 * angstrom'}
>>> my_par.length[1]
Quantity(value=1.5, unit=angstrom)
Unlike other ParameterAttribute objects, the reference points can do not need ot be
zero-indexed, non-adjancent, such as interpolating defining a bond parameter for
interpolation by defining references values and bond orders 2 and 3:
>>> my_par.length = {2:'1.42 * angstrom', 3: '1.35 * angstrom'}
>>> my_par.length[2]
Quantity(value=1.42, unit=angstrom)
"""
def _convert_and_validate(self, instance, value):
if self._is_valid_default(value):
return value
static_converter = functools.partial(self._call_converter, instance=instance)
value = ValidatedDict(value, converter=[self._validate_units, static_converter])
return value
class IndexedMappedParameterAttribute(ParameterAttribute):
"""The attribute of a parameter with an unspecified number of terms, where
each term is a mapping.
Some parameters can be associated to multiple terms,
where those terms have multiple components.
For example, torsions with fractional bond orders have parameters such as
k1_bondorder1, k1_bondorder2, k2_bondorder1, k2_bondorder2, ..., and
``IndexedMappedParameterAttribute`` can be used to encapsulate the sequence of
terms as mappings (typically, ``dict``\ s) of their components.
The only substantial difference with ``IndexedParameterAttribute`` is that
only sequences of mappings are supported as values and converters and units are
checked on each component of each element in the sequence.
Currently, the descriptor makes the sequence immutable. This is to
avoid that an element of the sequence could be set without being
properly validated. In the future, the data could be wrapped in a
safe list that would safely allow mutability.
Parameters
----------
default : object, optional
When specified, the descriptor makes this attribute optional by
attaching a default value to it.
unit : openmm.unit.Quantity, optional
When specified, only sequences of mappings where values are quantities with
compatible units are allowed to be set.
converter : callable, optional
An optional function that can be used to validate and cast each
component of each element of the sequence before setting the attribute.
See Also
--------
IndexedParameterAttribute
A parameter attribute representing a sequence.
MappedParameterAttribute
A parameter attribute representing a mapping.
Examples
--------
Create an optional indexed attribute with unit of angstrom.
>>> from openmm import unit
>>> class MyParameter:
... length = IndexedMappedParameterAttribute(default=None, unit=unit.angstrom)
...
>>> my_par = MyParameter()
>>> my_par.length is None
True
Strings are parsed into Quantity objects.
>>> my_par.length = [{1:'1 * angstrom'}, {1: 0.5 * unit.nanometer}]
>>> my_par.length[0]
{1: Quantity(value=1, unit=angstrom)}
Similarly, custom converters work as with ``ParameterAttribute``, but
they are used to validate each value in the sequence.
>>> class MyParameter:
... attr_indexed = IndexedMappedParameterAttribute(converter=float)
...
>>> my_par = MyParameter()
>>> my_par.attr_indexed = [{1: 1}, {2: '1.0', 3: '1e-2'}, {4: 4.0}]
>>> my_par.attr_indexed
[{1: 1.0}, {2: 1.0, 3: 0.01}, {4: 4.0}]
"""
def _convert_and_validate(self, instance, value):
"""Overwrite ParameterAttribute._convert_and_validate to make the value a ValidatedList."""
# The default value is always allowed.
if self._is_valid_default(value):
return value
# We push the converters into a ValidatedListMapping so that we can make
# sure that elements are validated correctly when they are modified
# after their initialization.
# ValidatedListMapping expects converters that take the value as a single
# argument so we create a partial function with the instance assigned.
static_converter = functools.partial(self._call_converter, instance=instance)
value = ValidatedList(
[
ValidatedDict(
element, converter=[self._validate_units, static_converter]
)
for element in value
],
converter=self._index_converter,
)
return value
@staticmethod
def _index_converter(x):
return ValidatedDict(x)
class _ParameterAttributeHandler:
"""A base class for ``ParameterType`` and ``ParameterHandler`` objects.
Encapsulate shared code of ``ParameterType`` and ``ParameterHandler``.
In particular, this base class provides an ``__init__`` method that
automatically initialize the attributes defined through the ``ParameterAttribute``
and ``IndexedParameterAttribute`` descriptors, as well as handling
cosmetic attributes.
See Also
--------
ParameterAttribute
A simple parameter attribute.
IndexedParameterAttribute
A parameter attribute with multiple terms.
Examples
--------
This base class was design to encapsulate shared code between ``ParameterType``
and ``ParameterHandler``, which both need to deal with parameter and cosmetic
attributes.
To create a new type/handler, you can use the ``ParameterAttribute`` descriptors.
>>> class ParameterTypeOrHandler(_ParameterAttributeHandler):
... length = ParameterAttribute(unit=unit.angstrom)
... k = ParameterAttribute(unit=unit.kilocalorie_per_mole / unit.angstrom**2)
...
``_ParameterAttributeHandler`` and the descriptors take care of performing
sanity checks on initialization and assignment of the single attributes. Because
we attached units to the parameters, we need to pass them with compatible units.
>>> my_par = ParameterTypeOrHandler(
... length='1.01 * angstrom',
... k=5 * unit.kilocalorie_per_mole / unit.angstrom**2
... )
Note that ``_ParameterAttributeHandler`` took care of implementing
a constructor, and that unit parameters support string assignments.
These are automatically converted to ``Quantity`` objects.
>>> my_par.length
Quantity(value=1.01, unit=angstrom)
While assigning incompatible units is forbidden.
>>> my_par.k = 3.0 * unit.gram
Traceback (most recent call last):
...
openff.toolkit.utils.utils.IncompatibleUnitError: k=3.0 g should have units of kilocalorie/(angstrom**2*mole)
On top of type checking, the constructor implemented in ``_ParameterAttributeHandler``
checks if some required parameters are not given.
>>> ParameterTypeOrHandler(length=3.0*unit.nanometer)
Traceback (most recent call last):
...
openff.toolkit.typing.engines.smirnoff.parameters.SMIRNOFFSpecError: <class 'openff.toolkit.typing.engines.smirnoff.parameters.ParameterTypeOrHandler'> require the following missing parameters: ['k']. Defined kwargs are ['length']
Each attribute can be made optional by specifying a default value,
and you can attach a converter function by passing a callable as an
argument or through the decorator syntax.
>>> class ParameterTypeOrHandler(_ParameterAttributeHandler):
... attr_optional = ParameterAttribute(default=2)
... 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 floats
... # 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 = ParameterTypeOrHandler(attr_all_to_float='3.0', attr_int_to_float=1)
>>> my_par.attr_optional
2
>>> my_par.attr_all_to_float
3.0
>>> my_par.attr_int_to_float
1.0
The float() function can convert strings to integers, but our custom
converter forbids it
>>> my_par.attr_all_to_float = '2.0'
>>> my_par.attr_int_to_float = '4.0'
Traceback (most recent call last):
...
TypeError: Cannot convert '4.0' to float
Parameter attributes that can be indexed can be handled with the
``IndexedParameterAttribute``. These support unit validation and
converters exactly as ``ParameterAttribute``s, but the validation/conversion
is performed for each indexed attribute.
>>> class MyTorsionType(_ParameterAttributeHandler):
... periodicity = IndexedParameterAttribute(converter=int)
... k = IndexedParameterAttribute(unit=unit.kilocalorie_per_mole)
...
>>> my_par = MyTorsionType(
... periodicity1=2,
... k1=5 * unit.kilocalorie_per_mole,
... periodicity2='3',
... k2=6 * unit.kilocalorie_per_mole,
... )
>>> my_par.periodicity
[2, 3]
Indexed attributes, can be accessed both as a list or as their indexed
parameter name.
>>> my_par.periodicity2 = 6
>>> my_par.periodicity[0] = 1
>>> my_par.periodicity
[1, 6]
"""
def __init__(self, allow_cosmetic_attributes=False, **kwargs):
"""
Initialize parameter and cosmetic attributes.
Parameters
----------
allow_cosmetic_attributes : bool optional. Default = False
Whether to permit non-spec kwargs ("cosmetic attributes").
If True, non-spec kwargs will be stored as an attribute of
this parameter which can be accessed and written out. Otherwise,
an exception will be raised.
"""
# A list that may be populated to record the cosmetic attributes
# read from a SMIRNOFF data source.
self._cosmetic_attribs = []
# Do not modify the original data.
smirnoff_data = copy.deepcopy(kwargs)
(
smirnoff_data,
indexed_mapped_attr_lengths,
) = self._process_indexed_mapped_attributes(smirnoff_data)
smirnoff_data = self._process_indexed_attributes(
smirnoff_data, indexed_mapped_attr_lengths
)
smirnoff_data = self._process_mapped_attributes(smirnoff_data)
# Check for missing required arguments.
given_attributes = set(smirnoff_data.keys())
required_attributes = set(self._get_required_parameter_attributes().keys())
missing_attributes = required_attributes.difference(given_attributes)
if len(missing_attributes) != 0:
msg = (
f"{self.__class__} require the following missing parameters: {sorted(missing_attributes)}."
f" Defined kwargs are {sorted(smirnoff_data.keys())}"
)
raise SMIRNOFFSpecError(msg)
# Finally, set attributes of this ParameterType and handle cosmetic attributes.
allowed_attributes = set(self._get_parameter_attributes().keys())
for key, val in smirnoff_data.items():
if key in allowed_attributes:
setattr(self, key, val)
# Handle all unknown kwargs as cosmetic so we can write them back out
elif allow_cosmetic_attributes:
self.add_cosmetic_attribute(key, val)
else:
msg = (
f"Unexpected kwarg ({key}: {val}) passed to {self.__class__} constructor. "
"If this is a desired cosmetic attribute, consider setting "
"'allow_cosmetic_attributes=True'"
)
raise SMIRNOFFSpecError(msg)
def _process_mapped_attributes(self, smirnoff_data):
kwargs = list(smirnoff_data.keys())
for kwarg in kwargs:
attr_name, key = self._split_attribute_mapping(kwarg)
# Check if this is a mapped attribute
if key is not None and attr_name in self._get_mapped_parameter_attributes():
if attr_name not in smirnoff_data:
smirnoff_data[attr_name] = dict()
smirnoff_data[attr_name][key] = smirnoff_data[kwarg]
del smirnoff_data[kwarg]
return smirnoff_data
def _process_indexed_mapped_attributes(self, smirnoff_data):
# TODO: construct data structure for holding indexed_mapped attrs, which
# will get fed into setattr
indexed_mapped_attr_lengths = {}
reindex = set()
reverse = defaultdict(dict)
kwargs = list(smirnoff_data.keys())
for kwarg in kwargs:
attr_name, index, key = self._split_attribute_index_mapping(kwarg)
# Check if this is an indexed_mapped attribute.
if (
(key is not None)
and (index is not None)
and attr_name in self._get_indexed_mapped_parameter_attributes()
):
# we start with a dict because have no guarantee of order
# in which we will see each kwarg
# we'll switch this to a list later
if attr_name not in smirnoff_data:
smirnoff_data[attr_name] = dict()
reindex.add(attr_name)
if index not in smirnoff_data[attr_name]:
smirnoff_data[attr_name][index] = dict()
smirnoff_data[attr_name][index][key] = smirnoff_data[kwarg]
del smirnoff_data[kwarg]
# build reverse mapping; needed for contiguity check below
if index not in reverse[attr_name]:
reverse[attr_name][index] = dict()
reverse[attr_name][index][key] = kwarg
# turn all our top-level dicts into lists
# catch cases where we skip an index,
# e.g. k1_bondorder*, k3_bondorder* defined, but not k2_bondorder*
for attr_name in reindex:
indexed_mapping = []
j = 0
for i in sorted(smirnoff_data[attr_name].keys()):
if int(i) == j:
indexed_mapping.append(smirnoff_data[attr_name][i])
j += 1
else:
# any key will do; we are sensitive only to top-level index
key = sorted(reverse[attr_name][i].keys())[0]
kwarg = reverse[attr_name][i][key]
val = smirnoff_data[attr_name][i][key]
msg = (
f"Unexpected kwarg ({kwarg}: {val}) passed to {self.__class__} constructor. "
"If this is a desired cosmetic attribute, consider setting "
"'allow_cosmetic_attributes=True'"
)
raise SMIRNOFFSpecError(msg)
smirnoff_data[attr_name] = indexed_mapping
# keep track of lengths; used downstream for checking against other
# indexed attributes
indexed_mapped_attr_lengths[attr_name] = len(smirnoff_data[attr_name])
return smirnoff_data, indexed_mapped_attr_lengths
def _process_indexed_attributes(self, smirnoff_data, indexed_attr_lengths=None):
# Check for indexed attributes and stack them into a list.
# Keep track of how many indexed attribute we find to make sure they all have the same length.
# TODO: REFACTOR ME; try looping over contents of `smirnoff_data`, using
# `split_attribute_index` to extract values
if indexed_attr_lengths is None:
indexed_attr_lengths = {}
for attrib_basename in self._get_indexed_parameter_attributes().keys():
index = 1
while True:
attrib_w_index = "{}{}".format(attrib_basename, index)
# Exit the while loop if the indexed attribute is not given.
# this is the stop condition
try: