-
Notifications
You must be signed in to change notification settings - Fork 92
/
test_parameters.py
2837 lines (2416 loc) · 104 KB
/
test_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
"""
Test classes and function in module openff.toolkit.typing.engines.smirnoff.parameters.
"""
from collections import defaultdict
from inspect import isabstract, isclass
import numpy
import pytest
from numpy.testing import assert_almost_equal
from packaging.version import Version
from openff.toolkit import ForceField, Molecule, Quantity, Topology, unit
from openff.toolkit._tests.mocking import VirtualSiteMocking
from openff.toolkit._tests.utils import does_not_raise
from openff.toolkit.typing.engines.smirnoff.parameters import (
AngleHandler,
BondHandler,
ChargeIncrementModelHandler,
ConstraintHandler,
ElectrostaticsHandler,
GBSAHandler,
ImproperTorsionHandler,
IndexedParameterAttribute,
LibraryChargeHandler,
ParameterAttribute,
ParameterHandler,
ParameterList,
ParameterType,
ProperTorsionHandler,
VirtualSiteHandler,
_cal_mol_a2,
_linear_inter_or_extrapolate,
_ParameterAttributeHandler,
vdWHandler,
)
from openff.toolkit.utils.collections import ValidatedList
from openff.toolkit.utils.exceptions import (
DuplicateParameterError,
IncompatibleParameterError,
IncompatibleUnitError,
MissingIndexedAttributeError,
NotEnoughPointsForInterpolationError,
ParameterLookupError,
SMIRNOFFSpecError,
SMIRNOFFSpecUnimplementedError,
SMIRNOFFVersionError,
)
class TestParameterAttribute:
"""Test cases for the descriptor ParameterAttribute."""
def test_default_value(self):
"""Default values are assigned correctly on initialization."""
class MyParameter:
attr_optional = ParameterAttribute(default=2)
my_par = MyParameter()
assert my_par.attr_optional == 2
def test_none_default_value(self):
"""None is a valid default value for ParameterAttribute."""
class MyParameter:
attr_optional = ParameterAttribute(default=None)
my_par = MyParameter()
assert my_par.attr_optional is None
def test_required_value(self):
"""AttributeError is raised if a required attribute is accessed before being initialized."""
class MyParameter:
attr_required = ParameterAttribute()
my_par = MyParameter()
with pytest.raises(AttributeError):
my_par.attr_required
def test_unit_validation(self):
"""ParameterAttributes attached to a unit are validated correctly."""
class MyParameter:
attr_unit = ParameterAttribute(
unit=unit.kilocalorie / unit.mole / unit.angstrom**2
)
my_par = MyParameter()
# TypeError is raised when setting a unit-less value.
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_unit = 3.0
# TypeError is raised when setting a value with incorrect units.
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_unit = 3.0 * unit.kilocalorie / unit.mole
# Otherwise the attribute is assigned correctly.
value = 3.0 * unit.kilocalorie / unit.mole / unit.angstrom**2
my_par.attr_unit = value
assert my_par.attr_unit == value
assert my_par.attr_unit.units == value.units
def test_quantity_string_parsing(self):
"""ParameterAttributes attached to units convert strings into Quantity objects."""
class MyParameter:
attr_unit = ParameterAttribute(unit=unit.meter / unit.second**2)
my_par = MyParameter()
my_par.attr_unit = "3.0*meter/second**2"
assert my_par.attr_unit == 3.0 * unit.meter / unit.second**2
assert my_par.attr_unit.units == unit.meter / unit.second**2
# Assigning incorrect units still raises an error.
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_unit = "3.0"
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_unit = "3.0*meter/second"
def test_custom_converter(self):
"""Custom converters of ParameterAttributes are executed correctly."""
class MyParameter:
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):
"""Convert only integers to float"""
if isinstance(value, int):
return float(value)
elif not isinstance(value, float):
raise TypeError()
return value
my_par = MyParameter()
# Both strings and integers are converted to floats when casted with float().
my_par.attr_all_to_float = "1.0"
assert (
isinstance(my_par.attr_all_to_float, float)
and my_par.attr_all_to_float == 1.0
)
my_par.attr_all_to_float = 2
assert (
isinstance(my_par.attr_all_to_float, float)
and my_par.attr_all_to_float == 2.0
)
# Only integers are converted with the custom converter function.
with pytest.raises(TypeError):
my_par.attr_int_to_float = "1.0"
my_par.attr_int_to_float = 2
assert (
isinstance(my_par.attr_int_to_float, float)
and my_par.attr_int_to_float == 2.0
)
def test_default_pass_validation(self):
"""The default value of ParameterAttribute is always allowed regardless of the validator/converter."""
class MyParameter:
attr = ParameterAttribute(
default=None, unit=unit.angstrom, converter=unit.Quantity
)
my_par = MyParameter()
my_par.attr = 3.0 * unit.nanometer
my_par.attr = None
assert my_par.attr is None
def test_get_descriptor_object(self):
"""When the descriptor is called from the class, the ParameterAttribute descriptor is returned."""
class MyParameter:
attr = ParameterAttribute()
assert isinstance(MyParameter.attr, ParameterAttribute)
class TestIndexedParameterAttribute:
"""Tests for the IndexedParameterAttribute descriptor."""
def test_tuple_conversion(self):
"""IndexedParameterAttribute converts internally sequences to ValidatedList."""
class MyParameter:
attr_indexed = IndexedParameterAttribute()
my_par = MyParameter()
my_par.attr_indexed = [1, 2, 3]
assert isinstance(my_par.attr_indexed, ValidatedList)
def test_indexed_default(self):
"""IndexedParameterAttribute handles default values correctly."""
class MyParameter:
attr_indexed_optional = IndexedParameterAttribute(default=None)
my_par = MyParameter()
assert my_par.attr_indexed_optional is None
# Assigning the default is allowed.
my_par.attr_indexed_optional = None
assert my_par.attr_indexed_optional is None
def test_units_on_all_elements(self):
"""IndexedParameterAttribute validates every single element of the sequence."""
class MyParameter:
attr_indexed_unit = IndexedParameterAttribute(unit=unit.gram)
my_par = MyParameter()
# Strings are correctly converted.
my_par.attr_indexed_unit = ["1.0*gram", 2 * unit.gram]
assert my_par.attr_indexed_unit == [1.0 * unit.gram, 2 * unit.gram]
# Incompatible units on a single elements are correctly caught.
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_indexed_unit = [3.0, 2 * unit.gram]
with pytest.raises(IncompatibleUnitError, match="should have units of"):
my_par.attr_indexed_unit = [2 * unit.gram, 4.0 * unit.meter]
def test_converter_on_all_elements(self):
"""IndexedParameterAttribute calls custom converters on every single element of the sequence."""
class MyParameter:
attr_indexed_converter = IndexedParameterAttribute(converter=float)
my_par = MyParameter()
my_par.attr_indexed_converter = [1, "2.0", "1e-3", 4.0]
assert my_par.attr_indexed_converter == [1.0, 2.0, 1e-3, 4.0]
def test_validate_new_elements(self):
"""New elements set in the list are correctly validated."""
class MyParameter:
attr_indexed = IndexedParameterAttribute(converter=int)
my_par = MyParameter()
my_par.attr_indexed = (1, 2, 3)
# Modifying one or more elements of the list should validate them.
my_par.attr_indexed[2] = "4"
assert my_par.attr_indexed[2] == 4
my_par.attr_indexed[0:3] = ["2", "3", 4]
assert my_par.attr_indexed == [2, 3, 4]
# Same for append().
my_par.attr_indexed.append("5")
assert my_par.attr_indexed[3] == 5
# And extend.
my_par.attr_indexed.extend([6, "7"])
assert my_par.attr_indexed[5] == 7
my_par.attr_indexed += ["8", 9]
assert my_par.attr_indexed[6] == 8
# And insert.
my_par.attr_indexed.insert(5, "10")
assert my_par.attr_indexed[5] == 10
class TestInterpolation:
"""Test method(s) that are used for functionality like fractional bond order-dependent parameter interpolation"""
@pytest.mark.parametrize(
("fractional_bond_order", "k_interpolated"),
[(1.6, 1.48), (0.7, 0.76), (2.3, 2.04)],
)
def test_linear_inter_or_extrapolate(self, fractional_bond_order, k_interpolated):
"""Test that linear interpolation works as expected"""
k_bondorder = {
1: 1 * unit.kilocalorie / unit.mole,
2: 1.8 * unit.kilocalorie / unit.mole,
}
k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
assert_almost_equal(k.m, k_interpolated)
def test_linear_inter_or_extrapolate_one_point(self):
"""Test that linear interpolation raises an error if attempted with just one point"""
k_bondorder = {
2: 1.8 * unit.kilocalorie / unit.mole,
}
with pytest.raises(NotEnoughPointsForInterpolationError):
_linear_inter_or_extrapolate(k_bondorder, 1)
@pytest.mark.parametrize(
("fractional_bond_order", "k_interpolated"),
[(1.6, 1.48), (0.7, 0.76), (2.3, 2.01), (3.1, 2.57)],
)
def test_linear_inter_or_extrapolate_3_terms(
self, fractional_bond_order, k_interpolated
):
"""Test that linear interpolation works as expected for three terms"""
k_bondorder = {
1: 1 * unit.kilocalorie / unit.mole,
2: 1.8 * unit.kilocalorie / unit.mole,
3: 2.5 * unit.kilocalorie / unit.mole,
}
k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
assert_almost_equal(k.m, k_interpolated)
def test_linear_inter_or_extrapolate_below_zero(self):
"""Test that linear interpolation does not error if resulting k less than 0"""
k_bondorder = {
1: 1 * unit.kilocalorie / unit.mole,
2: 2.3 * unit.kilocalorie / unit.mole,
}
fractional_bond_order = 0.2
k = _linear_inter_or_extrapolate(k_bondorder, fractional_bond_order)
assert k.m < 0
class TestParameterAttributeHandler:
"""Test suite for the base class _ParameterAttributeHandler."""
def test_access_get_set_single_indexed_attribute_legacy(self):
"""Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
class MyParameterType(_ParameterAttributeHandler):
k = IndexedParameterAttribute()
my_parameter = MyParameterType(k=[1, 2, 3])
# Getting the attribute works.
assert my_parameter.k1 == 1
assert my_parameter.k2 == 2
assert my_parameter.k3 == 3
# So does setting it.
my_parameter.k2 = 5
assert my_parameter.k2 == 5
assert my_parameter.k == [1, 5, 3]
# Accessing k4 raises an index error.
with pytest.raises(
IndexError, match="'k4' is out of bounds for indexed attribute 'k'"
):
my_parameter.k4
with pytest.raises(
IndexError, match="'k4' is out of bounds for indexed attribute 'k'"
):
my_parameter.k4 = 2
# For other attributes, the behavior is normal.
with pytest.raises(AttributeError, match="has no attribute 'x'"):
my_parameter.x
# Monkey-patching.
my_parameter.x = 3
def test_access_get_set_single_indexed_attribute(self):
"""Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
class MyParameterType(_ParameterAttributeHandler):
k = IndexedParameterAttribute()
my_parameter = MyParameterType(k=[1, 2, 3])
# Getting the attribute works.
assert my_parameter.k1 == 1
assert my_parameter.k2 == 2
assert my_parameter.k3 == 3
# So does setting it.
my_parameter.k2 = 5
assert my_parameter.k2 == 5
assert my_parameter.k == [1, 5, 3]
# Accessing k4 raises an index error.
with pytest.raises(
MissingIndexedAttributeError,
match="'k4' is out of bounds for indexed attribute 'k'",
):
my_parameter.k4
with pytest.raises(
MissingIndexedAttributeError,
match="'k4' is out of bounds for indexed attribute 'k'",
):
my_parameter.k4 = 2
# For other attributes, the behavior is normal.
with pytest.raises(AttributeError, match="has no attribute 'x'"):
my_parameter.x
# Monkey-patching.
my_parameter.x = 3
def test_hasattr(self):
"""Single indexed attributes such as k1 can be accessed through normal attribute syntax."""
class MyParameterType(_ParameterAttributeHandler):
k = IndexedParameterAttribute()
my_parameter = MyParameterType(k=[1, 2, 3])
assert hasattr(my_parameter, "k3")
assert not hasattr(my_parameter, "k4")
def test_mro_access_get_set_single_indexed_attribute(self):
"""Attribute access is forwarded correctly to the next MRO classes."""
class MixIn:
"""Utility class to keep track of whether __get/setattr__ are called."""
data = {}
def __getattr__(self, item):
self.getattr_flag = True
try:
return self.data[item]
except KeyError:
raise AttributeError()
def __setattr__(self, key, value):
self.data[key] = value
super().__setattr__("setattr_flag", True)
def assert_getattr(self):
assert self.getattr_flag is True
self.getattr_flag = False
def assert_setattr(self):
assert self.setattr_flag is True
super().__setattr__("setattr_flag", False)
class MyParameterType(_ParameterAttributeHandler, MixIn):
k = IndexedParameterAttribute()
my_parameter = MyParameterType(k=[1, 2, 3])
# Non-existing parameters.
my_parameter.a = 2
my_parameter.assert_setattr()
my_parameter.a1 = 4
my_parameter.assert_setattr()
my_parameter.a
my_parameter.assert_getattr()
my_parameter.a1
my_parameter.assert_getattr()
class TestParameterHandler:
length = 1 * unit.angstrom
k = 10 * unit.kilocalorie / unit.mole / unit.angstrom**2
def test_tagname(self):
"""Test the TAGNAME getter and default behavior"""
ph = ParameterHandler(skip_version_check=True)
assert ph.TAGNAME is None
bh = BondHandler(skip_version_check=True)
assert bh.TAGNAME == "Bonds"
def test_add_parameter(self):
"""Test the behavior of add_parameter"""
bh = BondHandler(skip_version_check=True)
param1 = {
"smirks": "[*:1]-[*:2]",
"length": self.length,
"k": self.k,
"id": "b1",
}
param2 = {
"smirks": "[*:1]=[*:2]",
"length": self.length,
"k": self.k,
"id": "b2",
}
param3 = {
"smirks": "[*:1]#[*:2]",
"length": self.length,
"k": self.k,
"id": "b3",
}
bh.add_parameter(param1)
bh.add_parameter(param2)
bh.add_parameter(param3)
assert [p.id for p in bh._parameters] == ["b1", "b2", "b3"]
param_duplicate_smirks = {
"smirks": param2["smirks"],
"length": 2 * self.length,
"k": 2 * self.k,
"id": "b4",
}
# Ensure a duplicate parameter cannot be added under default conditions
with pytest.raises(DuplicateParameterError):
bh.add_parameter(param_duplicate_smirks)
# Ensure a duplicate parameter CAN be added if `allow_duplicate_smirks=True`
bh.add_parameter(param_duplicate_smirks, allow_duplicate_smirks=True)
dict_to_add_by_smirks = {
"smirks": "[#1:1]-[#6:2]",
"length": self.length,
"k": self.k,
"id": "d1",
}
dict_to_add_by_index = {
"smirks": "[#1:1]-[#8:2]",
"length": self.length,
"k": self.k,
"id": "d2",
}
param_to_add_by_smirks = BondHandler.BondType(
**{
"smirks": "[#6:1]-[#6:2]",
"length": self.length,
"k": self.k,
"id": "p1",
}
)
param_to_add_by_index = BondHandler.BondType(
**{
"smirks": "[#6:1]=[#8:2]",
"length": self.length,
"k": self.k,
"id": "p2",
}
)
param_several_apart = {
"smirks": "[#1:1]-[#7:2]",
"length": self.length,
"k": self.k,
"id": "s0",
}
# The `before` parameter should come after the `after` parameter
# in the parameter list; i.e. in this list of ['-', '=', '#'], it is
# impossible to add a new parameter after '=' *and* before '-'
with pytest.raises(ValueError):
# Test invalid parameter order by SMIRKS
bh.add_parameter(
dict_to_add_by_smirks, after="[*:1]=[*:2]", before="[*:1]-[*:2]"
)
with pytest.raises(ValueError):
# Test invalid parameter order by index
bh.add_parameter(dict_to_add_by_index, after=1, before=0)
# Add d1 before param b2
bh.add_parameter(dict_to_add_by_smirks, before="[*:1]=[*:2]")
assert [p.id for p in bh._parameters] == ["b1", "d1", "b2", "b3", "b4"]
# Add d2 after index 2 (which is also param b2)
bh.add_parameter(dict_to_add_by_index, after=2)
assert [p.id for p in bh._parameters] == ["b1", "d1", "b2", "d2", "b3", "b4"]
# Add p1 before param b3
bh.add_parameter(parameter=param_to_add_by_smirks, before="[*:1]=[*:2]")
assert [p.id for p in bh._parameters] == [
"b1",
"d1",
"p1",
"b2",
"d2",
"b3",
"b4",
]
# Add p2 after index 2 (which is param p1)
bh.add_parameter(parameter=param_to_add_by_index, after=2)
assert [p.id for p in bh._parameters] == [
"b1",
"d1",
"p1",
"p2",
"b2",
"d2",
"b3",
"b4",
]
# Add s0 between params that are several positions apart
bh.add_parameter(param_several_apart, after=1, before=6)
assert [p.id for p in bh._parameters] == [
"b1",
"d1",
"s0",
"p1",
"p2",
"b2",
"d2",
"b3",
"b4",
]
def test_different_units_to_dict(self):
"""Test ParameterHandler.to_dict() function when some parameters are in
different units (proper behavior is to convert all quantities to the last-
read unit)
"""
bh = BondHandler(skip_version_check=True)
bh.add_parameter(
{
"smirks": "[*:1]-[*:2]",
"length": 1 * unit.angstrom,
"k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
}
)
bh.add_parameter(
{
"smirks": "[*:1]=[*:2]",
"length": 0.2 * unit.nanometer,
"k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
}
)
bh_dict = bh.to_dict()
assert bh_dict["Bond"][0]["length"] == unit.Quantity(
value=1, units=unit.angstrom
)
assert bh_dict["Bond"][1]["length"] == unit.Quantity(
value=2, units=unit.angstrom
)
def test_to_dict_maintain_units(self):
"""Test ParameterHandler.to_dict() function when parameters were provided in different units"""
bh = BondHandler(skip_version_check=True)
bh.add_parameter(
{
"smirks": "[*:1]-[*:2]",
"length": 1 * unit.angstrom,
"k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
}
)
bh.add_parameter(
{
"smirks": "[*:1]=[*:2]",
"length": 0.2 * unit.nanometer,
"k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
}
)
bh_dict = bh.to_dict()
assert bh_dict["Bond"][0]["length"] == unit.Quantity(1.0, unit.angstrom)
assert bh_dict["Bond"][0]["length"].units == unit.angstrom
assert bh_dict["Bond"][1]["length"] == unit.Quantity(0.2, unit.nanometer)
assert bh_dict["Bond"][1]["length"].units == unit.nanometer
def test_missing_section_version(self):
"""Test that exceptions are raised if invalid or improper section versions are provided during intialization"""
# Generate a SMIRNOFFSpecError by not providing a section version
with pytest.raises(
SMIRNOFFSpecError, match="Missing version while trying to construct"
):
ParameterHandler()
# Successfully create ParameterHandler by skipping version check
ParameterHandler(skip_version_check=True)
# Successfully create ParameterHandler by providing max supported version
ParameterHandler(version=ParameterHandler._MAX_SUPPORTED_SECTION_VERSION)
# Successfully create ParameterHandler by providing min supported version
ParameterHandler(version=ParameterHandler._MIN_SUPPORTED_SECTION_VERSION)
# Generate a SMIRNOFFSpecError by providing a value higher than the max supported
with pytest.raises(
SMIRNOFFVersionError,
match="SMIRNOFF offxml file was written with version 1000.0, "
"but this version of ForceField only supports version",
):
ParameterHandler(version="1000.0")
# Generate a SMIRNOFFSpecError by providing a value lower than the min supported
with pytest.raises(
SMIRNOFFVersionError,
match="SMIRNOFF offxml file was written with version 0.1, "
"but this version of ForceField only supports version",
):
ParameterHandler(version="0.1")
def test_supported_version_range(self):
"""
Ensure that version values in various formats can be correctly parsed and validated
"""
class MyPHSubclass(ParameterHandler):
_MIN_SUPPORTED_SECTION_VERSION = Version("0.3")
_MAX_SUPPORTED_SECTION_VERSION = Version("2")
with pytest.raises(SMIRNOFFVersionError):
MyPHSubclass(version=0.1)
with pytest.raises(Exception, match="Could not convert .*list"):
MyPHSubclass(version=[0])
MyPHSubclass(version=0.3)
MyPHSubclass(version=1)
MyPHSubclass(version="1.9")
MyPHSubclass(version=2.0)
with pytest.raises(SMIRNOFFVersionError):
MyPHSubclass(version=2.1)
def test_write_same_version_as_was_set(self):
"""Ensure that a ParameterHandler remembers the version that was set when it was initialized."""
class MyPHSubclass(ParameterHandler):
_MIN_SUPPORTED_SECTION_VERSION = Version("0.3")
_MAX_SUPPORTED_SECTION_VERSION = Version("2")
my_ph = MyPHSubclass(version=1.234)
assert my_ph.to_dict()["version"] == str(Version("1.234"))
def test_add_delete_cosmetic_attributes(self):
"""Test ParameterHandler.to_dict() function when some parameters are in
different units (proper behavior is to convert all quantities to the last-
read unit)
"""
bh = BondHandler(skip_version_check=True)
bh.add_parameter(
{
"smirks": "[*:1]-[*:2]",
"length": 1 * unit.angstrom,
"k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
}
)
bh.add_parameter(
{
"smirks": "[*:1]=[*:2]",
"length": 0.2 * unit.nanometer,
"k": 0.4 * unit.kilojoule / unit.mole / unit.nanometer**2,
}
)
assert not (bh.attribute_is_cosmetic("pilot"))
# Ensure the cosmetic attribute is present by default during output
bh.add_cosmetic_attribute("pilot", "alice")
param_dict = bh.to_dict()
assert ("pilot", "alice") in param_dict.items()
assert bh.attribute_is_cosmetic("pilot")
# Ensure the cosmetic attribute isn't present if we request that it be discarded
param_dict = bh.to_dict(discard_cosmetic_attributes=True)
assert "pilot" not in param_dict
# Manually delete the cosmetic attribute and ensure it doesn't get written out
bh.delete_cosmetic_attribute("pilot")
param_dict = bh.to_dict()
assert "pilot" not in param_dict
assert not (bh.attribute_is_cosmetic("pilot"))
def test_get_parameter(self):
"""Test that ParameterHandler.get_parameter can lookup function"""
bh = BondHandler(skip_version_check=True, allow_cosmetic_attributes=True)
bh.add_parameter(
{
"smirks": "[*:1]-[*:2]",
"length": 1 * unit.angstrom,
"k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
"id": "b0",
}
)
bh.parameters[0].add_cosmetic_attribute("foo", "bar")
# Check base behavior
params = bh.get_parameter({"smirks": "[*:1]-[*:2]"})
assert params[0].length == unit.Quantity(1.0, unit.angstrom)
assert params[0].k == unit.Quantity(
10.0, unit.kilocalorie / unit.mole / unit.angstrom**2
)
# Ensure a query with no matches returns an empty list
assert not bh.get_parameter({"smirks": "xyz"})
# Ensure searching for a nonexistent attr does not raise an exception
assert not bh.get_parameter({"bAdAttR": "0"})
# Check for optional and cosmetic attrs
optional_params = bh.get_parameter({"id": "b0"})
cosmetic_params = bh.get_parameter({"foo": "bar"})
assert optional_params[0].id == "b0"
assert cosmetic_params[0]._foo == "bar"
# Ensure selection behaves a "OR" not "AND"
bh.add_parameter(
{
"smirks": "[#1:1]-[#6:2]",
"length": 1 * unit.angstrom,
"k": 10 * unit.kilocalorie / unit.mole / unit.angstrom**2,
"id": "b1",
}
)
params = bh.get_parameter({"id": "b0", "smirks": "[#1:1]-[#6:2]"})
assert "b0" in [param.id for param in params]
assert "[*:1]-[*:2]" in [param.smirks for param in params]
# Ensure selection does not return duplicates if multiple matches
params = bh.get_parameter({"id": "b1", "smirks": "[#1:1]-[#6:2]"})
assert len(params) == 1
def test_create_force(self):
class MyParameterHandler(ParameterHandler):
pass
handler = MyParameterHandler(version=0.3)
with pytest.raises(
NotImplementedError, match="no longer create OpenMM forces."
):
handler.create_force()
class TestParameterList:
"""Test capabilities of ParameterList for accessing and manipulating SMIRNOFF parameter definitions."""
def test_create(self):
"""Test creation of a parameter list."""
p1 = ParameterType(smirks="[*:1]")
p2 = ParameterType(smirks="[#1:1]")
ParameterList([p1, p2])
def test_index(self):
"""
Tests the ParameterList.index() function by attempting lookups by SMIRKS and by ParameterType equivalence.
"""
p1 = ParameterType(smirks="[*:1]")
p2 = ParameterType(smirks="[#1:1]")
p3 = ParameterType(smirks="[#7:1]")
parameters = ParameterList([p1, p2, p3])
assert parameters.index(p1) == 0
assert parameters.index(p2) == 1
assert parameters.index(p3) == 2
assert parameters.index("[*:1]") == 0
assert parameters.index("[#1:1]") == 1
assert parameters.index("[#7:1]") == 2
with pytest.raises(
ParameterLookupError, match=r"SMIRKS \[#2:1\] not found in ParameterList"
):
parameters.index("[#2:1]")
p4 = ParameterType(smirks="[#2:1]")
with pytest.raises(ValueError, match="is not in list"):
parameters.index(p4)
def test_index_duplicates(self):
"""Test ParameterList.index when multiple parameters have identical SMIRKS"""
p1 = ParameterType(smirks="[*:1]")
p2 = ParameterType(smirks="[*:1]")
parameters = ParameterList([p1, p2])
assert parameters.index("[*:1]") == 1
def test_contains(self):
"""Test ParameterList __contains__ overloading."""
p1 = ParameterType(smirks="[*:1]")
p2 = ParameterType(smirks="[#1:1]")
p3 = ParameterType(smirks="[#7:1]")
parameters = ParameterList([p1, p2])
assert p1 in parameters
assert p2 in parameters
assert p3 not in parameters
assert p1.smirks in parameters
assert p2.smirks in parameters
assert p3.smirks not in parameters
def test_del(self):
"""
Test ParameterList __del__ overloading.
"""
p1 = ParameterType(smirks="[*:1]")
p2 = ParameterType(smirks="[#1:1]")
p3 = ParameterType(smirks="[#7:1]")
parameters = ParameterList([p1, p2, p3])
with pytest.raises(IndexError, match="list assignment index out of range"):
del parameters[4]
with pytest.raises(
ParameterLookupError,
match=r"SMIRKS \[#6:1\] not found in ParameterList",
):
del parameters["[#6:1]"]
# Test that original list deletion behavior is preserved.
del parameters[2]
assert len(parameters) == 2
assert p1 in parameters
assert p2 in parameters
assert p3 not in parameters
# Test that we can delete elements by their smirks.
del parameters["[#1:1]"]
assert len(parameters) == 1
assert p1 in parameters
assert p2 not in parameters
def test_append(self):
"""
Test ParameterList.append, ensuring that the new parameter was added to the bottom of the list
and that it is properly recorded as the most recently-added.
"""
p1 = ParameterType(smirks="[*:1]-[*:2]")
p2 = ParameterType(smirks="[*:1]=[*:2]")
param_list = ParameterList()
param_list.append(p1)
assert len(param_list) == 1
assert "[*:1]-[*:2]" in param_list
param_list.append(p2)
assert len(param_list) == 2
assert "[*:1]=[*:2]" in param_list
assert param_list[-1] == p2
def test_insert(self):
"""
Test ParameterList.insert, ensuring that the new parameter was added to the proper spot in
the list and that it is propertly recorded as the most recently added.
"""
p1 = ParameterType(smirks="[*:1]-[*:2]")
p2 = ParameterType(smirks="[*:1]=[*:2]")
p3 = ParameterType(smirks="[*:1]#[*:2]")
param_list = ParameterList([p1, p2])
param_list.insert(1, p3)
assert param_list[1] == p3
def test_extend(self):
"""
Test ParameterList.extend, ensuring that the new parameter was added to the proper spot in
the list and that it is propertly recorded as the most recently added.
"""
p1 = ParameterType(smirks="[*:1]-[*:2]")
p2 = ParameterType(smirks="[*:1]=[*:2]")
param_list1 = ParameterList()
param_list2 = ParameterList([p1, p2])
param_list1.extend(param_list2)
assert len(param_list1) == 2
assert "[*:1]-[*:2]" in param_list1
assert "[*:1]=[*:2]" in param_list1
assert param_list1[-1] == p2
def test_to_list(self):
"""Test basic ParameterList.to_list() function, ensuring units are preserved"""
p1 = BondHandler.BondType(
smirks="[*:1]-[*:2]",
length=1.01 * unit.angstrom,
k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
p2 = BondHandler.BondType(
smirks="[*:1]=[*:2]",
length=1.02 * unit.angstrom,
k=6 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
p3 = BondHandler.BondType(
smirks="[*:1]#[*:3]",
length=1.03 * unit.angstrom,
k=7 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
parameter_list = ParameterList([p1, p2, p3])
ser_param_list = parameter_list.to_list()
assert len(ser_param_list) == 3
assert ser_param_list[0]["length"] == 1.01 * unit.angstrom
def test_round_trip(self):
"""Test basic ParameterList.to_list() function and constructor"""
p1 = BondHandler.BondType(
smirks="[*:1]-[*:2]",
length=1.01 * unit.angstrom,
k=5 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
p2 = BondHandler.BondType(
smirks="[*:1]=[*:2]",
length=1.02 * unit.angstrom,
k=6 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
p3 = BondHandler.BondType(
smirks="[*:1]#[*:3]",
length=1.03 * unit.angstrom,
k=7 * unit.kilocalorie / unit.mole / unit.angstrom**2,
)
parameter_list = ParameterList([p1, p2, p3])
param_dict_list = parameter_list.to_list()
parameter_list_2 = ParameterList()
for param_dict in param_dict_list:
new_parameter = BondHandler.BondType(**param_dict)
parameter_list_2.append(new_parameter)
assert parameter_list.to_list() == parameter_list_2.to_list()