-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathtest_topology.py
More file actions
2443 lines (2024 loc) · 96.9 KB
/
Copy pathtest_topology.py
File metadata and controls
2443 lines (2024 loc) · 96.9 KB
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
"""
Tests for Topology
"""
import itertools
import re
import tempfile
from collections import defaultdict
from copy import deepcopy
from io import StringIO
from pathlib import Path
import numpy as np
import openmm.app
import openmm.unit
import pytest
from openff.units.openmm import from_openmm
from openff.toolkit import Molecule, Quantity, Topology, unit
from openff.toolkit._tests.create_molecules import (
create_ammonia,
create_cyclohexane,
create_ethanol,
create_reversed_ethanol,
create_water,
cyx_hierarchy_added,
dipeptide,
dipeptide_hierarchy_added,
dipeptide_residues_perceived,
ethane_from_smiles,
ethene_from_smiles,
propane_from_smiles,
toluene_from_sdf,
topology_with_metadata,
)
from openff.toolkit._tests.utils import (
get_data_file_path,
requires_openeye,
requires_pkg,
requires_rdkit,
)
from openff.toolkit._utilities import skip_if_missing
from openff.toolkit.topology import (
Atom,
ImproperDict,
TagSortedDict,
ValenceDict,
)
from openff.toolkit.topology._mm_molecule import _SimpleMolecule
from openff.toolkit.utils import (
BASIC_CHEMINFORMATICS_TOOLKITS,
OPENEYE_AVAILABLE,
RDKIT_AVAILABLE,
OpenEyeToolkitWrapper,
RDKitToolkitWrapper,
)
from openff.toolkit.utils.exceptions import (
AmbiguousAtomChemicalAssignment,
AmbiguousBondChemicalAssignment,
AtomNotInTopologyError,
BondNotInTopologyError,
DuplicateUniqueMoleculeError,
HierarchyIteratorNameConflictError,
IncompatibleUnitError,
InvalidBoxVectorsError,
InvalidPeriodicityError,
MissingConformersError,
MissingUniqueMoleculesError,
MoleculeNotInTopologyError,
NonUniqueSubstructureName,
PDBMoleculeHasNoncontiguousAtomIndicesError,
SubstructureAtomSmartsInvalid,
SubstructureBondSmartsInvalid,
UnassignedChemistryInPDBError,
VirtualSitesUnsupportedError,
WrongShapeError,
)
def assert_tuple_of_atoms_equal(atom_tuples1, atom_tuples2, transformed_dict_cls=ValenceDict):
"""Check that two lists of atoms are the same.
The function compares that the parent molecules are isomorphic and
that the molecule index is the same.
"""
assert len(atom_tuples1) == len(atom_tuples2)
# They are atoms of isomorphic molecules. We assume here that all
# atoms in the same list of tuples belong to the same molecule so
# that we can perform the check only once.
molecule1 = atom_tuples1[0][0]._molecule
molecule2 = atom_tuples2[0][0]._molecule
assert molecule1 == molecule2
for atom_tuple in atom_tuples1:
for a in atom_tuple:
assert a._molecule is molecule1
for atom_tuple in atom_tuples2:
for a in atom_tuple:
assert a._molecule is molecule2
# All atoms are equal. Use ValenceDict for this
atom_indices = []
for atom_tuples in [atom_tuples1, atom_tuples2]:
valence_dict = transformed_dict_cls()
for atom_tuple in atom_tuples:
key = tuple(a.molecule_atom_index for a in atom_tuple)
valence_dict[key] = atom_tuple
atom_indices.append(valence_dict)
assert set(atom_indices[0]) == set(atom_indices[1])
# IF we've done our jobs right, it shouldn't matter which toolkit the tests for Topology run using (both's behaviors
# should be indistinguishable)
def test_cheminformatics_toolkit_is_installed():
"""Ensure that at least one supported cheminformatics toolkit is installed."""
if not (RDKIT_AVAILABLE) and not (OPENEYE_AVAILABLE):
msg = "No supported cheminformatics toolkits are installed. Please install a supported toolkit:\n"
msg += str(BASIC_CHEMINFORMATICS_TOOLKITS)
raise Exception(msg)
@pytest.fixture()
def mixed_topology():
return Topology.from_molecules(
[
create_ethanol(),
create_ethanol(),
_SimpleMolecule.from_molecule(create_ethanol()),
_SimpleMolecule.from_molecule(create_ethanol()),
]
)
# TODO: Refactor this to pytest
class TestTopology:
def test_empty(self):
"""Test creation of empty topology"""
topology = Topology()
assert topology.n_molecules == 0
assert topology.n_unique_molecules == 0
assert topology.n_atoms == 0
assert topology.n_bonds == 0
assert topology.box_vectors is None
assert not topology.is_periodic
assert len(topology.constrained_atom_pairs.items()) == 0
def test_add_molecule_index(self):
"""Ensure the index of added molecules is 0-indexed."""
topology = Topology()
index = topology.add_molecule(create_ammonia())
assert index == 0 == topology.n_molecules - 1
# Ensure that same index can immediately be used as a lookup
topology.molecule(index)
next_index = topology.add_molecule(create_ethanol())
assert next_index == 1 == topology.n_molecules - 1
def test_from_molecule_bad_argument(self):
with pytest.raises(
ValueError,
match=r"Invalid type.*Topology",
):
topology = Topology()
topology.add_molecule(create_water().to_topology())
@pytest.mark.timeout(10)
def test_add_molecules(self):
water = create_water()
topology = Topology()
indices = topology.add_molecules(10_000 * [water])
assert topology.n_molecules == 10_000
assert indices == [*range(10_000)]
def test_from_molecule_nonlist(self):
topology = Topology()
with pytest.raises(
ValueError,
match=r"Invalid type.*set.*molecules",
):
topology.add_molecules({create_water(), create_ammonia()})
with pytest.raises(
ValueError,
match=r"Invalid type.*str.*molecules",
):
topology.add_molecules("CC.CCO")
def test_add_simple_molecule_atom_names(self):
"""Reproduce issue #1927"""
simple = _SimpleMolecule.from_molecule(Molecule.from_smiles("C"))
for index, letter in enumerate("BLAHB"):
simple.atom(index).name = letter
topology = Topology()
topology.add_molecule(simple)
assert topology.atom(0).name == "B"
assert topology.atom(1).name == "L"
assert topology.atom(2).name == "A"
assert topology.atom(3).name == "H"
assert topology.atom(4).name == "B"
def test_reinitialization_box_vectors(self):
topology = Topology()
assert Topology(topology).box_vectors is None
topology.box_vectors = [1, 2, 3] * unit.nanometer
topology_copy = Topology(topology)
assert (topology.box_vectors == topology_copy.box_vectors).all()
def test_box_vectors(self):
"""Test the getter and setter for box_vectors"""
topology = Topology()
good_box_vectors = unit.Quantity(np.eye(3) * 20, unit.angstrom)
one_dim_vectors = unit.Quantity(np.ones(3) * 20, unit.angstrom)
list_vectors = unit.Quantity([20, 20, 20], unit.angstrom)
list_list_vectors = unit.Quantity([[20, 0, 0], [0, 20, 0], [0, 0, 20]], unit.angstrom)
bad_shape_vectors = unit.Quantity(np.ones(2) * 20, unit.angstrom)
bad_units_vectors = unit.Quantity(np.ones(3) * 20, unit.year)
bad_type_vectors = unit.Quantity(1.0, unit.nanometer)
unitless_vectors = np.array([10, 20, 30])
assert topology.box_vectors is None
for bad_vectors in [
bad_shape_vectors,
bad_units_vectors,
bad_type_vectors,
unitless_vectors,
]:
with pytest.raises(InvalidBoxVectorsError):
topology.box_vectors = bad_vectors
assert topology.box_vectors is None
for good_vectors in [
good_box_vectors,
one_dim_vectors,
list_vectors,
list_list_vectors,
]:
topology.box_vectors = good_vectors
assert (topology.box_vectors == good_vectors * np.eye(3)).all()
def test_issue_1527(self):
"""Test the error handling of setting box vectors with an OpenMM quantity."""
topology = Topology()
topology.box_vectors = np.ones(3) * openmm.unit.nanometer
assert isinstance(topology.box_vectors, unit.Quantity)
def test_is_periodic(self):
"""Test the getter and setter for is_periodic"""
vacuum_top = Topology()
assert vacuum_top.is_periodic is False
with pytest.raises(InvalidPeriodicityError):
vacuum_top.is_periodic = True
solvent_box = Topology()
solvent_box.box_vectors = np.eye(3) * 4 * unit.nanometer
assert solvent_box.is_periodic is True
with pytest.raises(InvalidPeriodicityError):
solvent_box.is_periodic = False
solvent_box.box_vectors = None
assert solvent_box.is_periodic is False
def test_from_smiles(self):
"""Test creation of a OpenFF Topology object from a SMILES string"""
topology = Topology.from_molecules(ethane_from_smiles())
assert topology.n_molecules == 1
assert topology.n_unique_molecules == 1
assert topology.n_atoms == 8
assert topology.n_bonds == 7
assert topology.box_vectors is None
assert len(topology.constrained_atom_pairs.items()) == 0
topology.add_molecule(ethane_from_smiles())
assert topology.n_molecules == 2
assert topology.n_unique_molecules == 1
assert topology.n_atoms == 16
assert topology.n_bonds == 14
assert topology.box_vectors is None
assert len(topology.constrained_atom_pairs.items()) == 0
def test_from_smiles_unique_mols(self):
"""Test the addition of two different molecules to a topology"""
topology = Topology.from_molecules([ethane_from_smiles(), propane_from_smiles()])
assert topology.n_molecules == 2
assert topology.n_unique_molecules == 2
def test_n_atoms(self):
"""Test n_atoms function"""
topology = Topology()
assert topology.n_atoms == 0
assert topology.n_bonds == 0
topology.add_molecule(ethane_from_smiles())
assert topology.n_atoms == 8
assert topology.n_bonds == 7
def test_get_atom(self):
"""Test Topology.atom function (atom lookup from index)"""
topology = Topology()
topology.add_molecule(ethane_from_smiles())
# Make sure we get 2 carbons and 8 hydrogens
n_carbons = 0
n_hydrogens = 0
for index in range(8):
if topology.atom(index).atomic_number == 6:
n_carbons += 1
if topology.atom(index).atomic_number == 1:
n_hydrogens += 1
assert n_carbons == 2
assert n_hydrogens == 6
with pytest.raises(ValueError, match=r"must be an int.*'str'"):
topology.atom("one")
with pytest.raises(AtomNotInTopologyError):
topology.atom(-1)
with pytest.raises(AtomNotInTopologyError):
topology.atom(8)
def test_atom_index(self):
topology = create_ethanol().to_topology()
for index in range(topology.n_atoms):
atom = topology.atom(index)
assert topology.atom_index(atom) == index
ghost_atom = Atom(atomic_number=1, formal_charge=0, is_aromatic=False)
with pytest.raises(AtomNotInTopologyError):
topology.atom_index(ghost_atom)
def test_molecule_index(self):
molecules = [Molecule.from_smiles("CCO"), Molecule.from_smiles("O")]
topology = Topology.from_molecules(molecules)
for index in range(topology.n_molecules):
molecule = topology.molecule(index)
assert topology.molecule_index(molecule) == index
ghost_molecule = Molecule.from_smiles("N")
with pytest.raises(MoleculeNotInTopologyError):
topology.molecule_index(ghost_molecule)
def test_atom_element_properties(self):
"""
Test element-like getters of `Atom`. In 0.11.0, Atom.element
was removed and replaced with Atom.atomic_number and Atom.symbol.
"""
topology = Topology()
topology.add_molecule(toluene_from_sdf())
first_atom = topology.atom(0)
eighth_atom = topology.atom(7)
# These atoms are expected to be hydrogen and carbon, respectively
assert first_atom.symbol == "C"
assert first_atom.atomic_number == 6
assert eighth_atom.symbol == "H"
assert eighth_atom.atomic_number == 1
def test_get_bond(self):
"""Test Topology.bond function (bond lookup from index)"""
topology = Topology()
topology.add_molecule(ethane_from_smiles())
topology.add_molecule(ethene_from_smiles())
n_single_bonds = 0
n_double_bonds = 0
n_ch_bonds = 0
n_cc_bonds = 0
for index in range(12): # 7 from ethane, 5 from ethene
bond = topology.bond(index)
if bond.bond_order == 1:
n_single_bonds += 1
if bond.bond_order == 2:
n_double_bonds += 1
n_bond_carbons = 0
n_bond_hydrogens = 0
for atom in bond.atoms:
if atom.atomic_number == 6:
n_bond_carbons += 1
if atom.atomic_number == 1:
n_bond_hydrogens += 1
if n_bond_carbons == 2:
n_cc_bonds += 1
if n_bond_carbons == 1 and n_bond_hydrogens == 1:
n_ch_bonds += 1
assert n_single_bonds == 11
assert n_double_bonds == 1
assert n_cc_bonds == 2
assert n_ch_bonds == 10
with pytest.raises(ValueError, match=r"must be an int.*'str'"):
topology.bond("one")
with pytest.raises(BondNotInTopologyError, match="No bond with index -1"):
topology.bond(-1)
with pytest.raises(BondNotInTopologyError, match="No bond with index 12"):
topology.bond(12)
def test_angles(self):
"""Topology.angles should return image angles of all topology molecules."""
molecule1 = ethane_from_smiles()
molecule2 = propane_from_smiles()
# Create topology.
topology = Topology()
topology.add_molecule(molecule1)
topology.add_molecule(molecule1)
topology.add_molecule(molecule2)
# The topology should have the correct number of angles.
topology_angles = list(topology.angles)
assert len(topology_angles) == topology.n_angles
assert topology.n_angles == 2 * molecule1.n_angles + molecule2.n_angles
# Check that the topology angles are the correct ones.
mol_angle_atoms1 = list(molecule1.angles)
mol_angle_atoms2 = list(molecule2.angles)
top_angle_atoms1 = [tuple(a for a in atoms) for atoms in topology_angles[: molecule1.n_angles]]
top_angle_atoms2 = [
tuple(a for a in atoms) for atoms in topology_angles[molecule1.n_angles : 2 * molecule1.n_angles]
]
top_angle_atoms3 = [tuple(a for a in atoms) for atoms in topology_angles[2 * molecule1.n_angles :]]
assert_tuple_of_atoms_equal(top_angle_atoms1, mol_angle_atoms1)
assert_tuple_of_atoms_equal(top_angle_atoms2, mol_angle_atoms1)
assert_tuple_of_atoms_equal(top_angle_atoms3, mol_angle_atoms2)
def test_propers(self):
"""Topology.propers should return image propers torsions of all topology molecules."""
molecule1 = ethane_from_smiles()
molecule2 = propane_from_smiles()
# Create topology.
topology = Topology()
topology.add_molecule(molecule1)
topology.add_molecule(molecule1)
topology.add_molecule(molecule2)
# The topology should have the correct number of propers.
topology_propers = list(topology.propers)
assert len(topology_propers) == topology.n_propers
assert topology.n_propers == 2 * molecule1.n_propers + molecule2.n_propers
# Check that the topology propers are the correct ones.
mol_proper_atoms1 = list(molecule1.propers)
mol_proper_atoms2 = list(molecule2.propers)
top_proper_atoms1 = [tuple(a for a in atoms) for atoms in topology_propers[: molecule1.n_propers]]
top_proper_atoms2 = [
tuple(a for a in atoms) for atoms in topology_propers[molecule1.n_propers : 2 * molecule1.n_propers]
]
top_proper_atoms3 = [tuple(a for a in atoms) for atoms in topology_propers[2 * molecule1.n_propers :]]
assert_tuple_of_atoms_equal(top_proper_atoms1, mol_proper_atoms1)
assert_tuple_of_atoms_equal(top_proper_atoms2, mol_proper_atoms1)
assert_tuple_of_atoms_equal(top_proper_atoms3, mol_proper_atoms2)
def test_impropers(self):
"""Topology.impropers should return image impropers torsions of all topology molecules."""
molecule1 = ethane_from_smiles()
molecule2 = propane_from_smiles()
# Create topology.
topology = Topology()
topology.add_molecule(molecule1)
topology.add_molecule(molecule1)
topology.add_molecule(molecule2)
# The topology should have the correct number of impropers.
topology_impropers = list(topology.impropers)
assert len(topology_impropers) == topology.n_impropers
assert topology.n_impropers == 2 * molecule1.n_impropers + molecule2.n_impropers
# Check that the topology impropers are the correct ones.
mol_improper_atoms1 = list(molecule1.impropers)
mol_improper_atoms2 = list(molecule2.impropers)
top_improper_atoms1 = [tuple(a for a in atoms) for atoms in topology_impropers[: molecule1.n_impropers]]
top_improper_atoms2 = [
tuple(a for a in atoms) for atoms in topology_impropers[molecule1.n_impropers : 2 * molecule1.n_impropers]
]
top_improper_atoms3 = [tuple(a for a in atoms) for atoms in topology_impropers[2 * molecule1.n_impropers :]]
assert_tuple_of_atoms_equal(top_improper_atoms1, mol_improper_atoms1, transformed_dict_cls=ImproperDict)
assert_tuple_of_atoms_equal(top_improper_atoms2, mol_improper_atoms1, transformed_dict_cls=ImproperDict)
assert_tuple_of_atoms_equal(top_improper_atoms3, mol_improper_atoms2, transformed_dict_cls=ImproperDict)
def test_pruned_impropers(self):
"""Test {smirnoff|amber}_impropers from the Topology API"""
top = Topology.from_molecules([Molecule.from_smiles(smi) for smi in ["N", "C=C"]])
assert len([*top.smirnoff_impropers]) == 18
assert len([*top.amber_impropers]) == 18
# Order not guaranteed, so cannot zip and compare directly
for smirnoff_imp in top.smirnoff_impropers:
# Convert SMIRNOFF-style improper into AMBER-style
mod_imp = (
smirnoff_imp[1],
smirnoff_imp[0],
smirnoff_imp[2],
smirnoff_imp[3],
)
assert mod_imp in top.amber_impropers
# test_two_of_same_molecule
# test_two_different_molecules
# test_get_molecule
# test_is_bonded
# TODO: Test serialization
def test_from_openmm(self):
"""Test creation of an OpenFF Topology object from an OpenMM Topology and component molecules"""
pdbfile = openmm.app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
with pytest.raises(MissingUniqueMoleculesError, match="requires a list of Molecule objects"):
Topology.from_openmm(pdbfile.topology)
molecules = [create_ethanol(), create_cyclohexane()]
topology = Topology.from_openmm(
pdbfile.topology,
unique_molecules=molecules,
positions=pdbfile.positions,
)
assert topology.n_molecules == 239
assert topology.n_unique_molecules == 2
assert np.all(topology.get_positions() == from_openmm(pdbfile.positions))
# Ensure that hierarchy iterators are initialized
assert all(all([molecule.residues, molecule.chains]) for molecule in topology.molecules)
for omm_atom, off_atom in zip(pdbfile.topology.atoms(), topology.atoms):
assert omm_atom.name == off_atom.name
def test_from_openmm_virtual_sites(self, opc):
water = Molecule.from_mapped_smiles("[O:1]([H:2])[H:3]")
openmm_topology = opc.create_interchange([water]).to_openmm_topology()
with pytest.raises(
VirtualSitesUnsupportedError,
match=r"Atom <Atom 3 .*EP.*a virtual site",
):
Topology.from_openmm(
openmm_topology,
unique_molecules=[water],
)
def test_from_openmm_missing_reference(self):
"""Test creation of an OpenFF Topology object from an OpenMM Topology when missing a unique molecule"""
pdbfile = openmm.app.PDBFile(get_data_file_path("systems/packmol_boxes/cyclohexane_ethanol_0.4_0.6.pdb"))
molecules = [create_ethanol()]
with pytest.raises(ValueError, match="No match found for molecule C6H12"):
Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
def test_from_openmm_missing_conect(self):
"""
Test creation of an OpenFF Topology object from an OpenMM Topology
when the origin PDB lacks CONECT records
"""
pdbfile = openmm.app.PDBFile(get_data_file_path("systems/test_systems/1_ethanol_no_conect.pdb"))
molecules = []
molecules.append(Molecule.from_smiles("CCO"))
with pytest.raises(
ValueError,
match=r"No match found for molecule C. This would be a "
r"very unusual molecule to try and parameterize, "
r"and it is likely that the data source it was "
r"read from does not contain connectivity "
r"information. If this molecule is coming from "
r"PDB, please ensure that the file contains CONECT "
r"records.",
):
Topology.from_openmm(pdbfile.topology, unique_molecules=molecules)
def test_to_from_openmm(self):
"""Test a round-trip OpenFF -> OpenMM -> OpenFF Topology."""
# Create OpenFF topology with 1 ethanol and 2 benzenes.
ethanol = Molecule.from_smiles("CCO")
benzene = Molecule.from_smiles("c1ccccc1")
off_topology = Topology.from_molecules(molecules=[ethanol, benzene, benzene])
# Convert to OpenMM Topology.
omm_topology = off_topology.to_openmm()
# Check that bond orders are preserved.
n_double_bonds = sum([b.order == 2 for b in omm_topology.bonds()])
n_aromatic_bonds = sum([b.type is openmm.app.Aromatic for b in omm_topology.bonds()])
assert n_double_bonds == 6
assert n_aromatic_bonds == 12
# Check that there is one residue and chain for each molecule.
assert omm_topology.getNumResidues() == 3
assert omm_topology.getNumChains() == 3
# Convert back to OpenFF Topology.
off_topology_copy = Topology.from_openmm(omm_topology, unique_molecules=[ethanol, benzene])
# The round-trip OpenFF Topology is identical to the original.
# The reference molecules are the same.
assert off_topology.n_molecules == off_topology_copy.n_molecules
assert off_topology.n_unique_molecules == off_topology_copy.n_unique_molecules
molecules_copy = list(off_topology_copy.molecules)
for mol_idx, mol in enumerate(off_topology.molecules):
assert mol == molecules_copy[mol_idx]
# The number of topology molecules is the same.
assert off_topology.n_molecules == off_topology_copy.n_molecules
# Check atoms.
assert off_topology.n_atoms == off_topology_copy.n_atoms
for atom_idx, atom in enumerate(off_topology.atoms):
atom_copy = off_topology_copy.atom(atom_idx)
assert atom.atomic_number == atom_copy.atomic_number
# Check bonds.
for bond in off_topology.bonds:
bond_copy = off_topology_copy.get_bond_between(
off_topology.atom_index(bond.atoms[0]),
off_topology.atom_index(bond.atoms[1]),
)
bond_atoms = [a.atomic_number for a in bond.atoms]
bond_atoms_copy = [a.atomic_number for a in bond_copy.atoms]
assert bond_atoms == bond_atoms_copy
assert bond.bond_order == bond_copy.bond_order
assert bond.is_aromatic == bond_copy.is_aromatic
def test_to_from_openmm_hierarchy_metadata(self):
"""
Test roundtripping to/from ``OpenEyeToolkitWrapper`` for molecules with PDB hierarchy metadata
"""
top = topology_with_metadata()
omm_top = top.to_openmm()
# Make a list of the unique molecules in the topology for the return from roundtripping to OpenMM
unique_mols = []
for mol in top.molecules:
if mol.to_smiles() not in [m.to_smiles() for m in unique_mols]:
unique_mols.append(mol)
roundtrip_top = Topology.from_openmm(omm_top, unique_molecules=unique_mols)
# Check OMM Atom
for orig_atom, omm_atom in zip(top.atoms, omm_top.atoms()):
if "residue_name" in orig_atom.metadata:
assert orig_atom.metadata["residue_name"] == omm_atom.residue.name
else:
assert omm_atom.residue.name == "UNK"
if "residue_number" in orig_atom.metadata:
assert orig_atom.metadata["residue_number"] == int(omm_atom.residue.id)
else:
assert omm_atom.residue.id == "0"
if "insertion_code" in orig_atom.metadata:
assert orig_atom.metadata["insertion_code"] == omm_atom.residue.insertionCode
else:
assert omm_atom.residue.insertionCode == " "
if "chain_id" in orig_atom.metadata:
assert orig_atom.metadata["chain_id"] == omm_atom.residue.chain.id
else:
assert omm_atom.residue.chain.id == "X"
# Check roundtripped OFFMol
for orig_atom, roundtrip_atom in zip(top.atoms, roundtrip_top.atoms):
if "residue_name" in orig_atom.metadata:
original = orig_atom.metadata["residue_name"]
roundtrip = roundtrip_atom.metadata["residue_name"]
assert original == roundtrip
else:
assert roundtrip_atom.metadata["residue_name"] == "UNK"
if "residue_number" in orig_atom.metadata:
original = orig_atom.metadata["residue_number"]
roundtrip = roundtrip_atom.metadata["residue_number"]
assert original == roundtrip
else:
assert roundtrip_atom.metadata["residue_number"] == "0"
if "insertion_code" in orig_atom.metadata:
original = orig_atom.metadata["insertion_code"]
roundtrip = roundtrip_atom.metadata["insertion_code"]
assert original == roundtrip
else:
assert roundtrip_atom.metadata["insertion_code"] == " "
if "chain_id" in orig_atom.metadata:
original = orig_atom.metadata["chain_id"]
roundtrip = roundtrip_atom.metadata["chain_id"]
assert original == roundtrip
else:
assert roundtrip_atom.metadata["chain_id"] == "X"
@requires_rdkit
def test_from_to_openmm_hierarchy_metadata(self):
"""Reproduce issue #1953"""
import openmm.app
openmm_topology = openmm.app.PDBFile(get_data_file_path("proteins/MainChain_ALA_ALA.pdb")).topology
openff_molecule = Topology.from_pdb(get_data_file_path("proteins/MainChain_ALA_ALA.pdb")).molecule(0)
roundtripped = Topology.from_openmm(
openmm_topology,
unique_molecules=[openff_molecule],
).to_openmm()
assert {type(residue.id) for residue in roundtripped.residues()} == {str}, (
"type mistmatch in residue id in OpenMM residues"
)
@requires_rdkit
def test_from_pdb(self):
with pytest.raises(UnassignedChemistryInPDBError) as exc_info:
Topology.from_pdb(get_data_file_path("proteins/5tbm_complex_solv.pdb"))
# Make sure that the error message above doesn't contain the "multiple chains" hint
assert "input has multiple chain identifiers" not in exc_info.value.args[0].join("")
ligand = Molecule.from_file(get_data_file_path("molecules/PT2385.sdf"))
stereoisomer1 = Molecule.from_smiles("[C@H](Cl)(F)/C=C/F")
stereoisomer2 = Molecule.from_smiles(r"[C@@H](Cl)(F)/C=C\F")
top = Topology.from_pdb(
get_data_file_path("proteins/5tbm_complex_solv.pdb"),
unique_molecules=[
ligand,
Molecule.from_smiles("[H]S[H]"),
# Unlike bond order and formal charge, the stereo is
# assigned by 3D geometry, so providing stereoisomer1 should allow
# us to load stereoisomers 1 and 2 correctly
stereoisomer1,
],
)
assert top.box_vectors is None
res_iter = top.hierarchy_iterator("residues")
assert len([*res_iter]) == 130
chain_iter = top.hierarchy_iterator("chains")
assert len([*chain_iter]) == 19
assert top.molecule(1).is_isomorphic_with(ligand)
water = Molecule.from_smiles("O")
assert top.molecule(2).is_isomorphic_with(water)
assert top.molecule(3).is_isomorphic_with(water)
assert top.molecule(4).is_isomorphic_with(water)
assert top.molecule(5).is_isomorphic_with(water)
# Ensure the stereo twins were loaded correctly
assert top.molecule(6).is_isomorphic_with(stereoisomer1)
assert not (top.molecule(6).is_isomorphic_with(stereoisomer2))
assert top.molecule(7).is_isomorphic_with(stereoisomer2)
assert not (top.molecule(7).is_isomorphic_with(stereoisomer1))
# Test loading monoatomic ions added by pdbfixer
cl_minus = Molecule.from_smiles("[Cl-]")
assert top.molecule(8).is_isomorphic_with(cl_minus)
assert top.molecule(9).is_isomorphic_with(cl_minus)
na_plus = Molecule.from_smiles("[Na+]")
assert top.molecule(10).is_isomorphic_with(na_plus)
assert top.molecule(11).is_isomorphic_with(na_plus)
# Test loading monoatomic ions added as SMILES
assert top.molecule(12).is_isomorphic_with(Molecule.from_smiles("[Li+]"))
assert top.molecule(13).is_isomorphic_with(Molecule.from_smiles("[K+]"))
assert top.molecule(14).is_isomorphic_with(Molecule.from_smiles("[Rb+]"))
assert top.molecule(15).is_isomorphic_with(Molecule.from_smiles("[Cs+]"))
assert top.molecule(16).is_isomorphic_with(Molecule.from_smiles("[F-]"))
assert top.molecule(17).is_isomorphic_with(Molecule.from_smiles("[Br-]"))
assert top.molecule(18).is_isomorphic_with(Molecule.from_smiles("[I-]"))
@requires_rdkit
def test_from_pdb_input_types(self):
import openmm.app
protein_path = get_data_file_path("proteins/ace-ala-nh2.pdb")
Topology.from_pdb(protein_path)
Topology.from_pdb(Path(protein_path))
with open(protein_path) as f:
Topology.from_pdb(f)
pdb_string = Path(protein_path).read_text()
with StringIO(pdb_string) as f:
Topology.from_pdb(f)
with pytest.raises(ValueError, match=r"Unexpected type.*PDBFile"):
Topology.from_pdb(openmm.app.PDBFile(protein_path))
@requires_rdkit
def test_from_pdb_two_polymers_metadata(self):
"""Test that a PDB with two capped polymers is loaded correctly"""
top = Topology.from_pdb(get_data_file_path("proteins/TwoMol_SER_CYS.pdb"))
assert top.molecule(0).is_isomorphic_with(
Molecule.from_smiles(
"[H][O][C]([H])([H])[C@@]([H])([C](=[O])[N]([H])[C]([H])([H])[H])[N]([H])[C](=[O])[C]([H])([H])[H]"
)
)
assert top.molecule(1).is_isomorphic_with(
Molecule.from_smiles(
"[H][S][C]([H])([H])[C@@]([H])([C](=[O])[N]([H])[C]([H])([H])[H])[N]([H])[C](=[O])[C]([H])([H])[H]"
)
)
expected_residues = (
(6, ("A", "1", " ", "ACE")),
(11, ("A", "2", " ", "SER")),
(6, ("A", "3", " ", "NME")),
(6, ("B", "1", " ", "ACE")),
(11, ("B", "2", " ", "CYS")),
(6, ("B", "3", " ", "NME")),
)
res_iter = top.hierarchy_iterator("residues")
for (n_atoms, identifier), residue in zip(expected_residues, res_iter):
assert residue.n_atoms == n_atoms
assert residue.identifier == identifier
assert ((abs(top.box_vectors - (np.eye(3, 3) * 48 * unit.angstrom)) / unit.angstrom) < 1e-10).all()
@requires_rdkit
def test_from_pdb_overlapping_unique_mols(self):
"""Test that even overlapping unique molecules can be loaded using from_pdb"""
po4 = Molecule.from_smiles("P(=O)([O-])([O-])([O-])")
phenylphosphate = Molecule.from_smiles("c1ccccc1OP(=O)([O-1])([O-1])")
# Load the topology with po4 listed as the first unique mol
top1 = Topology.from_pdb(
get_data_file_path("molecules/po4_phenylphosphate.pdb"),
unique_molecules=[po4, phenylphosphate],
)
assert po4.is_isomorphic_with(top1.molecule(0))
assert phenylphosphate.is_isomorphic_with(top1.molecule(1))
# Load the topology with phenylphosphate listed as the first unique mol
top2 = Topology.from_pdb(
get_data_file_path("molecules/po4_phenylphosphate.pdb"),
unique_molecules=[phenylphosphate, po4],
)
assert po4.is_isomorphic_with(top2.molecule(0))
assert phenylphosphate.is_isomorphic_with(top2.molecule(1))
@requires_rdkit
def test_from_pdb_unique_mol_ammonium(self):
"""
Test that Topology.from_pdb can load ammonium unique mol.
See https://github.com/openforcefield/openff-toolkit/issues/2051
"""
nh4 = Molecule.from_smiles("[NH4+]")
offtop = Topology.from_pdb(get_data_file_path("molecules/nh4.pdb"), unique_molecules=[nh4])
assert nh4.is_isomorphic_with(offtop.molecule(0))
@requires_rdkit
def test_from_pdb_additional_substructures(self):
"""Test that the _additional_substructures arg is wired up correctly"""
with pytest.raises(UnassignedChemistryInPDBError):
Topology.from_pdb(get_data_file_path("proteins/ace-ZZZ-gly-nme.pdb"))
# Make unnatural AA
# TODO: Should this be able to support defined stereo?
mol = Molecule.from_smiles("N[CH]([CH](C)O[P@](=O)(OCNCO)[O-])C(=O)", allow_undefined_stereo=True)
# Get the indices of an N term and C term hydrogen for removal
leaving_atoms = mol.chemical_environment_matches("[H:1]N([H])CC(=O)[H:2]")[0]
# Label the atoms with whether they're leaving
for atom in mol.atoms:
if atom.molecule_atom_index not in leaving_atoms:
atom.metadata["substructure_atom"] = True
else:
atom.metadata["substructure_atom"] = False
top = Topology.from_pdb(
get_data_file_path("proteins/ace-ZZZ-gly-nme.pdb"),
_additional_substructures=[mol],
)
expected_mol = Molecule.from_file(get_data_file_path("proteins/ace-ZZZ-gly-nme.sdf"))
assert top.molecule(0).is_isomorphic_with(expected_mol, atom_stereochemistry_matching=False)
@requires_rdkit
def test_from_pdb_molecule_atom_ordering_noncontiguous(self):
"""
Test that from_pdb correctly raises an error when the PDB atom ordering has atoms
in the same molecule on noncontiguous lines.
See https://github.com/openforcefield/openff-toolkit/issues/2093
"""
with pytest.raises(
PDBMoleculeHasNoncontiguousAtomIndicesError, match="Atom indices 23 and 48 are in molecule 0"
):
Topology.from_pdb(get_data_file_path("proteins/split_chain.pdb"))
# Ensure that following the prior error message's advice and naively reordering the PDB lines works
top = Topology.from_pdb(get_data_file_path("proteins/split_chain_reordered.pdb"))
# Check for sanity by ensuring that no bonds have unreasonable geometry
for mol in top.molecules:
for bond in mol.bonds:
length = np.linalg.norm(mol.conformers[0][bond.atom1_index] - mol.conformers[0][bond.atom2_index])
assert 0.4 < length.m_as(unit.angstrom) < 2.5
@requires_pkg("mdtraj")
def test_from_mdtraj(self):
"""Test construction of an OpenFF Topology from an MDTraj Topology object"""
import mdtraj as md
pdb_path = get_data_file_path("systems/test_systems/1_cyclohexane_1_ethanol.pdb")
trj = md.load(pdb_path)
with pytest.raises(MissingUniqueMoleculesError, match="requires a list of Molecule objects"):
Topology.from_mdtraj(trj.top)
unique_molecules = [Molecule.from_smiles(mol_name) for mol_name in ["C1CCCCC1", "CCO"]]
top = Topology.from_mdtraj(trj.top, unique_molecules=unique_molecules)
assert top.n_molecules == 2
assert top.n_bonds == 26
@requires_rdkit
def test_to_file_units_check(self):
"""
Checks that writing a PDB file with different coordinate representations results in the same output.
- Angstrom "openff units" (default behavior if using Molecule.conformers[0])
- nanometer "openff units"
- unitless NumPy array
- converted OpenMM quantity
"""
topology = Topology.from_pdb(
get_data_file_path("systems/test_systems/1_ethanol.pdb"), unique_molecules=[Molecule.from_smiles("CCO")]
)
positions_angstrom = topology.get_positions().to("angstrom")
def _check_file(topology, coordinates):
# Write the molecule to PDB and ensure that the X coordinate of the first atom is 10.172
count = 1
with tempfile.NamedTemporaryFile(suffix=".pdb") as iofile:
topology.to_file(iofile.name, coordinates)
data = open(iofile.name).readlines()
for line in data:
if line.startswith("HETATM") and count == 1:
count = count + 1
coord = line.split()[-6]
assert coord == "10.172"
_check_file(topology, coordinates=positions_angstrom)
_check_file(topology, coordinates=positions_angstrom.to(unit.nanometer))
_check_file(topology, coordinates=positions_angstrom.m)
_check_file(topology, coordinates=positions_angstrom.to_openmm())
with pytest.raises(ValueError, match=r"Could not process.*list.*"):
_check_file(topology, coordinates=positions_angstrom.m.tolist())
@requires_rdkit
def test_to_file_fileformat_lettercase(self):
"""
Checks if fileformat specifier is indpendent of upper/lowercase
"""
topology = Topology.from_pdb(
get_data_file_path("systems/test_systems/1_ethanol.pdb"), unique_molecules=[Molecule.from_smiles("CCO")]
)
positions = topology.get_positions().to("angstrom")
count = 1
with tempfile.NamedTemporaryFile(suffix=".pdb") as iofile:
topology.to_file(iofile.name, positions, file_format="pDb")
data = open(iofile.name).readlines()
for line in data:
if line.startswith("HETATM") and count == 1:
count = count + 1
coord = line.split()[-6]
assert coord == "10.172"
@requires_rdkit
def test_to_file_fileformat_invalid(self):