-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathtopology.py
3133 lines (2598 loc) · 113 KB
/
topology.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
# =============================================================================================
"""
Class definitions to represent a molecular system and its chemical components
.. todo::
* Create MoleculeImage, ParticleImage, AtomImage, VirtualSiteImage here. (Or ``MoleculeInstance``?)
* Create ``MoleculeGraph`` to represent fozen set of atom elements and bonds that can used as a key for compression
* Add hierarchical way of traversing Topology (chains, residues)
* Make all classes hashable and serializable.
* JSON/BSON representations of objects?
* Use `attrs <http://www.attrs.org/>`_ for object setter boilerplate?
"""
import itertools
from collections import OrderedDict
from collections.abc import MutableMapping
import numpy as np
try:
from openmm import app, unit
from openmm.app import Aromatic, Double, Single, Triple
except ImportError:
from simtk import unit
from simtk.openmm import app
from simtk.openmm.app import Aromatic, Double, Single, Triple
from openff.toolkit.typing.chemistry import ChemicalEnvironment
from openff.toolkit.utils.exceptions import (
DuplicateUniqueMoleculeError,
InvalidBoxVectorsError,
InvalidPeriodicityError,
MissingUniqueMoleculesError,
NotBondedError,
)
from openff.toolkit.utils.serialization import Serializable
from openff.toolkit.utils.toolkits import (
ALLOWED_AROMATICITY_MODELS,
ALLOWED_CHARGE_MODELS,
ALLOWED_FRACTIONAL_BOND_ORDER_MODELS,
DEFAULT_AROMATICITY_MODEL,
GLOBAL_TOOLKIT_REGISTRY,
)
class _TransformedDict(MutableMapping):
"""A dictionary that transform and sort keys.
The function __keytransform__ can be inherited to apply an arbitrary
key-altering function before accessing the keys.
The function __sortfunc__ can be inherited to specify a particular
order over which to iterate over the dictionary.
"""
def __init__(self, *args, **kwargs):
self.store = OrderedDict()
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
return self.store[self.__keytransform__(key)]
def __setitem__(self, key, value):
self.store[self.__keytransform__(key)] = value
def __delitem__(self, key):
del self.store[self.__keytransform__(key)]
def __iter__(self):
return iter(sorted(self.store, key=self.__sortfunc__))
def __len__(self):
return len(self.store)
def __keytransform__(self, key):
return key
@staticmethod
def __sortfunc__(key):
return key
# TODO: Encapsulate this atom ordering logic directly into Atom/Bond/Angle/Torsion classes?
class ValenceDict(_TransformedDict):
"""Enforce uniqueness in atom indices."""
@staticmethod
def key_transform(key):
"""Reverse tuple if first element is larger than last element."""
# Ensure key is a tuple.
key = tuple(key)
assert len(key) > 0 and len(key) < 5, "Valence keys must be at most 4 atoms"
# Reverse the key if the first element is bigger than the last.
if key[0] > key[-1]:
key = tuple(reversed(key))
return key
@staticmethod
def index_of(key, possible=None):
"""
Generates a canonical ordering of the equivalent permutations of ``key`` (equivalent rearrangements of indices)
and identifies which of those possible orderings this particular ordering is. This method is useful when
multiple SMARTS patterns might match the same atoms, but local molecular symmetry or the use of
wildcards in the SMARTS could make the matches occur in arbitrary order.
This method can be restricted to a subset of the canonical orderings, by providing
the optional ``possible`` keyword argument. If provided, the index returned by this method will be
the index of the element in ``possible`` after undergoing the same canonical sorting as above.
Parameters
----------
key : iterable of int
A valid key for ValenceDict
possible : iterable of iterable of int, optional. default=``None``
A subset of the possible orderings that this match might take.
Returns
-------
index : int
"""
assert len(key) < 4
refkey = __class__.key_transform(key)
if len(key) == 2:
permutations = OrderedDict(
{(refkey[0], refkey[1]): 0, (refkey[1], refkey[0]): 1}
)
elif len(key) == 3:
permutations = OrderedDict(
{
(refkey[0], refkey[1], refkey[2]): 0,
(refkey[2], refkey[1], refkey[0]): 1,
}
)
else:
# For a proper, only forward/backward makes sense
permutations = OrderedDict(
{
(refkey[0], refkey[1], refkey[2], refkey[3]): 0,
(refkey[3], refkey[1], refkey[2], refkey[0]): 1,
}
)
if possible is not None:
i = 0
# If the possible permutations were provided, ensure that `possible` is a SUBSET of `permutations`
assert all([p in permutations for p in possible]), (
"Possible permutations " + str(possible) + " is impossible!"
)
# TODO: Double-check whether this will generalize. It seems like this would fail if ``key``
# were in ``permutations``, but not ``possible``
for k in permutations:
if all([x == y for x, y in zip(key, k)]):
return i
if k in possible:
i += 1
else:
# If the possible permutations were NOT provided, then return the unique index of this permutation.
return permutations[key]
def __keytransform__(self, key):
return __class__.key_transform(key)
class SortedDict(_TransformedDict):
"""Enforce uniqueness of atom index tuples, without any restrictions on atom reordering."""
def __keytransform__(self, key):
"""Sort tuple from lowest to highest."""
# Ensure key is a tuple.
key = tuple(sorted(key))
# Reverse the key if the first element is bigger than the last.
return key
class UnsortedDict(_TransformedDict):
...
class TagSortedDict(_TransformedDict):
"""
A dictionary where keys, consisting of tuples of atom indices, are kept unsorted, but only allows one permutation of a key
to exist. Certain situations require that atom indices are not transformed in any
way, such as when the tagged order of a match is needed downstream. For example a
parameter using charge increments needs the ordering of the tagged match, and so
transforming the atom indices in any way will cause that information to be lost.
Because deduplication is needed, we still must avoid the expected situation
where we must not allow two permutations of the same atoms to coexist. For example,
a parameter may have matched the indices (2, 0, 1), however a parameter with higher
priority also matches the same indices, but the tagged order is (1, 0, 2). We need
to make sure both keys don't exist, or else two parameters will apply to
the same atoms. We allow the ability to query using either permutation and get
identical behavior. The defining feature here, then, is that the stored indices are
in tagged order, but one can supply any permutation and it will resolve to the
stored value/parameter.
As a subtle behavior, one must be careful if an external key is used that was not
supplied from the TagSortedDict object itself. For example:
>>> x = TagSortedDict({(2, 5, 0): 100})
>>> y = x[(5, 0, 2)]
The variable y will be 100, but this does not mean the tagged order is (5, 0, 2)
as it was supplied from the external tuple. One should either use keys only from
__iter__ (e.g. `for k in x`) or one must transform the key:
>>> key = (5, 0, 2)
>>> y = x[key]
>>> key = x.key_transform(key)
Where `key` will now be `(2, 5, 0)`, as it is the key stored. One can overwrite
this key with the new one as expected:
>>> key = (5, 0, 2)
>>> x[key] = 50
Now the key `(2, 5, 0)` will no longer exist, as it was replaced with `(5, 0, 2)`.
"""
def __init__(self, *args, **kwargs):
# Because keytransform is O(n) due to needing to check the sorted keys,
# we cache the sorted keys separately to make keytransform O(1) at
# the expense of storage. This is also better in the long run if the
# key is long and repeatedly sorting isn't a negligible cost.
# Set this before calling super init, since super will call the get/set
# methods implemented here as it populates self via args/kwargs,
# which will automatically populate _sorted
self._sorted = SortedDict()
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
"""
Set the key to value, but only allow one permutation of key to exist. The
key argument will replace the old permutation:value if it exists.
"""
key = tuple(key)
tr_key = self.__keytransform__(key)
if key != tr_key:
# this means our new key is a permutation of an existing, so we should
# replace it
del self.store[tr_key]
self.store[key] = value
# save the sorted version for faster keytransform
self._sorted[key] = key
def __keytransform__(self, key):
"""Give the key permutation that is currently stored"""
# we check if there is a permutation clash by saving the sorted version of
# each key. If the sorted version of the key exists, then the return value
# corresponds to the explicit permutation we are storing in self (the public
# facing key). This permutation may or may not be the same as the key argument
# supplied. If the key is not present, then no transformation should be done
# and we should return the key as is.
# As stated in __init__, the alternative is to, on each call, sort the saved
# permutations and check if it is equal to the sorted supplied key. In this
# sense, self._sorted is a cache/lookup table.
key = tuple(key)
return self._sorted.get(key, key)
def key_transform(self, key):
key = tuple(key)
return self.__keytransform__(key)
def clear(self):
"""
Clear the contents
"""
self.store.clear()
self._sorted.clear()
class ImproperDict(_TransformedDict):
"""Symmetrize improper torsions."""
@staticmethod
def key_transform(key):
"""Reorder tuple in numerical order except for element[1] which is the central atom; it retains its position."""
# Ensure key is a tuple
key = tuple(key)
assert len(key) == 4, "Improper keys must be 4 atoms"
# Retrieve connected atoms
connectedatoms = [key[0], key[2], key[3]]
# Sort connected atoms
connectedatoms.sort()
# Re-store connected atoms
key = tuple([connectedatoms[0], key[1], connectedatoms[1], connectedatoms[2]])
return key
@staticmethod
def index_of(key, possible=None):
"""
Generates a canonical ordering of the equivalent permutations of ``key`` (equivalent rearrangements of indices)
and identifies which of those possible orderings this particular ordering is. This method is useful when
multiple SMARTS patterns might match the same atoms, but local molecular symmetry or the use of
wildcards in the SMARTS could make the matches occur in arbitrary order.
This method can be restricted to a subset of the canonical orderings, by providing
the optional ``possible`` keyword argument. If provided, the index returned by this method will be
the index of the element in ``possible`` after undergoing the same canonical sorting as above.
Parameters
----------
key : iterable of int
A valid key for ValenceDict
possible : iterable of iterable of int, optional. default=``None``
A subset of the possible orderings that this match might take.
Returns
-------
index : int
"""
assert len(key) == 4
refkey = __class__.key_transform(key)
permutations = OrderedDict(
{
(refkey[0], refkey[1], refkey[2], refkey[3]): 0,
(refkey[0], refkey[1], refkey[3], refkey[2]): 1,
(refkey[2], refkey[1], refkey[0], refkey[3]): 2,
(refkey[2], refkey[1], refkey[3], refkey[0]): 3,
(refkey[3], refkey[1], refkey[0], refkey[2]): 4,
(refkey[3], refkey[1], refkey[2], refkey[0]): 5,
}
)
if possible is not None:
assert all(
[p in permutations for p in possible]
), "Possible permuation is impossible!"
i = 0
for k in permutations:
if all([x == y for x, y in zip(key, k)]):
return i
if k in possible:
i += 1
else:
return permutations[key]
def __keytransform__(self, key):
return __class__.key_transform(key)
# =============================================================================================
# TOPOLOGY OBJECTS
# =============================================================================================
# =============================================================================================
# TopologyAtom
# =============================================================================================
class TopologyAtom(Serializable):
"""
A TopologyAtom is a lightweight data structure that represents a single openff.toolkit.topology.molecule.Atom in
a Topology. A TopologyAtom consists of two references -- One to its fully detailed "atom", an
openff.toolkit.topology.molecule.Atom, and another to its parent "topology_molecule", which occupies a spot in
the parent Topology's TopologyMolecule list.
As some systems can be very large, there is no always-existing representation of a TopologyAtom. They are created on
demand as the user requests them.
.. warning :: This API is experimental and subject to change.
"""
def __init__(self, atom, topology_molecule):
"""
Create a new TopologyAtom.
Parameters
----------
atom : An openff.toolkit.topology.molecule.Atom
The reference atom
topology_molecule : An openff.toolkit.topology.TopologyMolecule
The TopologyMolecule that this TopologyAtom belongs to
"""
# TODO: Type checks
self._atom = atom
self._topology_molecule = topology_molecule
@property
def atom(self):
"""
Get the reference Atom for this TopologyAtom.
Returns
-------
an openff.toolkit.topology.molecule.Atom
"""
return self._atom
@property
def atomic_number(self):
"""
Get the atomic number of this atom
Returns
-------
int
"""
return self._atom.atomic_number
@property
def element(self):
"""
Get the element name of this atom.
Returns
-------
openmm.app.element.Element
"""
return self._atom.element
@property
def topology_molecule(self):
"""
Get the TopologyMolecule that this TopologyAtom belongs to.
Returns
-------
openff.toolkit.topology.TopologyMolecule
"""
return self._topology_molecule
@property
def molecule(self):
"""
Get the reference Molecule that this TopologyAtom belongs to.
Returns
-------
openff.toolkit.topology.molecule.Molecule
"""
return self._topology_molecule.reference_molecule
@property
def topology_atom_index(self):
"""
Get the index of this atom in its parent Topology.
Returns
-------
int
The index of this atom in its parent topology.
"""
mapped_molecule_atom_index = self._topology_molecule._ref_to_top_index[
self._atom.molecule_atom_index
]
return (
self._topology_molecule.atom_start_topology_index
+ mapped_molecule_atom_index
)
@property
def topology_particle_index(self):
"""
Get the index of this particle in its parent Topology.
Returns
-------
int
The index of this atom in its parent topology.
"""
# This assumes that the particles in a topology are listed with all atoms from all TopologyMolecules
# first, followed by all VirtualSites from all TopologyMolecules second
return self.topology_atom_index
@property
def topology_bonds(self):
"""
Get the TopologyBonds connected to this TopologyAtom.
Returns
-------
iterator of openff.toolkit.topology.TopologyBonds
"""
for bond in self._atom.bonds:
reference_mol_bond_index = bond.molecule_bond_index
yield self._topology_molecule.bond(reference_mol_bond_index)
def __eq__(self, other):
return (self._atom == other._atom) and (
self._topology_molecule == other._topology_molecule
)
def __repr__(self):
return "TopologyAtom {} with reference atom {} and parent TopologyMolecule {}".format(
self.topology_atom_index, self._atom, self._topology_molecule
)
def to_dict(self):
"""Convert to dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
@classmethod
def from_dict(cls, d):
"""Static constructor from dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
# @property
# def bonds(self):
# """
# Get the Bonds connected to this TopologyAtom.
#
# Returns
# -------
# iterator of openff.toolkit.topology.molecule.Bonds
# """
# for bond in self._atom.bonds:
# yield bond
# TODO: Add all atom properties here? Or just make people use TopologyAtom.atom for that?
# =============================================================================================
# TopologyBond
# =============================================================================================
class TopologyBond(Serializable):
"""
A TopologyBond is a lightweight data structure that represents a single openff.toolkit.topology.molecule.Bond in
a Topology. A TopologyBond consists of two references -- One to its fully detailed "bond", an
openff.toolkit.topology.molecule.Bond, and another to its parent "topology_molecule", which occupies a spot in
the parent Topology's TopologyMolecule list.
As some systems can be very large, there is no always-existing representation of a TopologyBond. They are created on
demand as the user requests them.
.. warning :: This API is experimental and subject to change.
"""
def __init__(self, bond, topology_molecule):
"""
Parameters
----------
bond : An openff.toolkit.topology.molecule.Bond
The reference bond.
topology_molecule : An openff.toolkit.topology.TopologyMolecule
The TopologyMolecule that this TopologyBond belongs to.
"""
# TODO: Type checks
self._bond = bond
self._topology_molecule = topology_molecule
@property
def bond(self):
"""
Get the reference Bond for this TopologyBond.
Returns
-------
an openff.toolkit.topology.molecule.Bond
"""
return self._bond
@property
def topology_molecule(self):
"""
Get the TopologyMolecule that this TopologyBond belongs to.
Returns
-------
openff.toolkit.topology.TopologyMolecule
"""
return self._topology_molecule
@property
def topology_bond_index(self):
"""
Get the index of this bond in its parent Topology.
Returns
-------
int
The index of this bond in its parent topology.
"""
return (
self._topology_molecule.bond_start_topology_index
+ self._bond.molecule_bond_index
)
@property
def molecule(self):
"""
Get the reference Molecule that this TopologyBond belongs to.
Returns
-------
openff.toolkit.topology.molecule.Molecule
"""
return self._topology_molecule.reference_molecule
@property
def bond_order(self):
"""
Get the order of this TopologyBond.
Returns
-------
int : bond order
"""
return self._bond.bond_order
@property
def atoms(self):
"""
Get the TopologyAtoms connected to this TopologyBond.
Returns
-------
iterator of openff.toolkit.topology.TopologyAtom
"""
for ref_atom in self._bond.atoms:
yield TopologyAtom(ref_atom, self._topology_molecule)
def to_dict(self):
"""Convert to dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
@classmethod
def from_dict(cls, d):
"""Static constructor from dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
# =============================================================================================
# TopologyVirtualSite
# =============================================================================================
class TopologyVirtualSite(Serializable):
"""A TopologyVirtualSite is a lightweight data structure that represents a single
openff.toolkit.topology.molecule.VirtualSite in a Topology.
A TopologyVirtualSite consists of two references -- One to its fully detailed
"VirtualSite", an openff.toolkit.topology.molecule.VirtualSite, and another to its
parent "topology_molecule", which occupies a spot in the parent Topology's
TopologyMolecule list.
As some systems can be very large, there is no always-existing representation of a
TopologyVirtualSite. They are created on demand as the user requests them.
.. warning :: This API is experimental and subject to change.
"""
def __init__(self, virtual_site, topology_molecule):
"""
Parameters
----------
virtual_site : An openff.toolkit.topology.molecule.VirtualSite
The reference virtual site
topology_molecule : An openff.toolkit.topology.TopologyMolecule
The TopologyMolecule that this TopologyVirtualSite belongs to
"""
from openff.toolkit.topology import VirtualSite
assert isinstance(virtual_site, VirtualSite)
assert isinstance(topology_molecule, TopologyMolecule)
self._virtual_site = virtual_site
self._topology_molecule = topology_molecule
self._topology_virtual_particle_start_index = None
def invalidate_cached_data(self):
self._topology_virtual_particle_start_index = None
@property
def virtual_site(self):
"""
Get the reference VirtualSite for this TopologyVirtualSite.
Returns
-------
an openff.toolkit.topology.molecule.VirtualSite
"""
return self._virtual_site
@property
def topology_molecule(self):
"""
Get the TopologyMolecule that this TopologyVirtualSite belongs to.
Returns
-------
openff.toolkit.topology.TopologyMolecule
"""
return self._topology_molecule
@property
def topology_virtual_site_index(self):
"""
Get the index of this virtual site in its parent Topology.
Returns
-------
int
The index of this virtual site in its parent topology.
"""
return (
self._topology_molecule.virtual_site_start_topology_index
+ self._virtual_site.molecule_virtual_site_index
)
@property
def n_particles(self):
"""
Get the number of particles represented by this VirtualSite
Returns
-------
int : The number of particles
"""
return self._virtual_site.n_particles
@property
def topology_virtual_particle_start_index(self):
"""
Get the index of the first virtual site particle in its parent Topology.
Returns
-------
int
The index of this particle in its parent topology.
"""
# This assumes that the particles in a topology are listed with all
# atoms from all TopologyMolecules first, followed by all VirtualSites
# from all TopologyMolecules second
# If the cached value is not available, generate it
if self._topology_virtual_particle_start_index is None:
particle_start_index = self.topology_molecule.topology.n_topology_atoms
for molecule in self._topology_molecule._topology.topology_molecules:
if self._topology_molecule != molecule:
particle_start_index += sum(
v_site.n_particles for v_site in molecule.virtual_sites
)
continue
for v_site in molecule.virtual_sites:
if self != v_site:
particle_start_index += v_site.n_particles
continue
# we found the v-site we were looking for.
self._topology_virtual_particle_start_index = particle_start_index
return particle_start_index
# need a safety catch to ensure we don't fall through without ever finding
# the right virtual site.
raise ValueError("This virtual site could not be found in the topology")
return self._topology_virtual_particle_start_index
@property
def particles(self):
"""
Get an iterator to the reference particles that this TopologyVirtualSite
contains.
Returns
-------
iterator of TopologyVirtualParticles
"""
for vptl in self.virtual_site.particles:
yield TopologyVirtualParticle(
self._virtual_site, vptl, self._topology_molecule, self
)
@property
def molecule(self):
"""
Get the reference Molecule that this TopologyVirtualSite belongs to.
Returns
-------
openff.toolkit.topology.molecule.Molecule
"""
return self._topology_molecule.reference_molecule
@property
def type(self):
"""
Get the type of this virtual site
Returns
-------
str : The class name of this virtual site
"""
return self._virtual_site.type
def __eq__(self, other):
return (
type(self) == type(other)
and self._virtual_site == other._virtual_site
and self._topology_molecule == other._topology_molecule
)
def to_dict(self):
"""Convert to dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
@classmethod
def from_dict(cls, d):
"""Static constructor from dictionary representation."""
# Implement abstract method Serializable.to_dict()
raise NotImplementedError() # TODO
# =============================================================================================
# TopologyVirtualParticle
# =============================================================================================
class TopologyVirtualParticle(Serializable):
def __init__(
self, virtual_site, virtual_particle, topology_molecule, topology_virtual_site
):
from openff.toolkit.topology import VirtualParticle, VirtualSite
assert isinstance(virtual_site, VirtualSite)
assert isinstance(virtual_particle, VirtualParticle)
assert isinstance(topology_virtual_site, TopologyVirtualSite)
assert isinstance(topology_molecule, TopologyMolecule)
# TODO: Type checks
self._virtual_site = virtual_site
self._virtual_particle = virtual_particle
self._topology_molecule = topology_molecule
self._topology_virtual_site = topology_virtual_site
@property
def molecule(self):
"""
Get the reference Molecule that this TopologyVirtualParticle belongs to.
Returns
-------
openff.toolkit.topology.molecule.Molecule
"""
return self._topology_molecule.reference_molecule
@property
def virtual_site(self):
"""
Get the reference VirtualSite for this TopologyVirtualSite.
Returns
-------
an openff.toolkit.topology.molecule.VirtualSite
"""
return self._virtual_site
@property
def virtual_particle(self):
"""
Get the reference VirtualParticle for this TopologyVirtualParticle.
Returns
-------
an openff.toolkit.topology.molecule.VirtualSite
"""
return self._virtual_particle
@property
def type(self):
"""
Get the type of this virtual site
Returns
-------
str : The class name of this virtual site
"""
return self._virtual_site.type
def atom(self, index):
"""Get the atom at a specific index in this TopologyVirtualParticle
Parameters
----------
index : int
The index of the atom in the reference VirtualParticle to retrieve
Returns
-------
TopologyAtom
"""
reference_atoms = self._topology_molecule.reference_molecule.atoms
return TopologyAtom(
reference_atoms[self._virtual_particle.orientation[index]],
self.topology_molecule,
)
@property
def atoms(self):
"""
Get the TopologyAtoms involved in this TopologyVirtualParticle.
Returns
-------
iterator of openff.toolkit.topology.TopologyAtom
"""
ref_atoms = self._topology_molecule.reference_molecule.atoms
for ref_index in self._virtual_particle.orientation:
yield TopologyAtom(ref_atoms[ref_index], self._topology_molecule)
@property
def topology_molecule(self):
"""
Get the TopologyMolecule that this TopologyVirtualSite belongs to.
Returns
-------
openff.toolkit.topology.TopologyMolecule
"""
return self._topology_molecule
@property
def topology_particle_index(self):
"""
Get the index of this particle in its parent Topology.
Returns
-------
idx : int
The index of this particle in its parent topology.
"""
# This assumes that the particles in a topology are listed with all atoms from all TopologyMolecules
# first, followed by all VirtualSites from all TopologyMolecules second
orientation_key = self._virtual_particle.orientation
offset = None
# vsite is a topology vsite, which has a regular vsite
for i, ornt in enumerate(self._virtual_site.orientations):
if ornt == orientation_key:
offset = i
break
assert offset is not None
return (
offset + self._topology_virtual_site.topology_virtual_particle_start_index
)
@property
def topology_parent_atom_index(self) -> int:
"""Returns the index of the 'parent' atom as determined by the virtual site type
in the topology.
"""
from openff.toolkit.typing.engines.smirnoff import VirtualSiteHandler
parent_index = VirtualSiteHandler.VirtualSiteType.type_to_parent_index(
self._virtual_particle.virtual_site.type
)
parent_reference_atom_index = self._virtual_particle.orientation[parent_index]
mapped_molecule_atom_index = self._topology_molecule._ref_to_top_index[
parent_reference_atom_index
]
return (
self._topology_molecule.atom_start_topology_index
+ mapped_molecule_atom_index
)
def __eq__(self, other):
return (
type(other) == type(self)
and self._virtual_particle == other._virtual_particle