-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmulti_mol.py
2551 lines (2161 loc) · 105 KB
/
multi_mol.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
"""A Module for the :class:`MultiMolecule` class.
Index
-----
.. currentmodule:: FOX
.. autosummary::
MultiMolecule
API
---
.. autoclass:: FOX.MultiMolecule
:members:
:noindex:
"""
from __future__ import annotations
import os
import copy
import operator
import warnings
import functools
import sys
from os import PathLike
from collections import abc, defaultdict
from itertools import (
chain, combinations_with_replacement, zip_longest, islice, repeat, permutations
)
from typing import (
Sequence, Optional, Union, List, Hashable, Callable, Iterable, Dict, Tuple, Any, Mapping,
overload, TypeVar, Type, Container, cast, TYPE_CHECKING, Sized, Iterator, NoReturn,
SupportsIndex,
)
import numpy as np
import pandas as pd
from scipy import constants
from scipy.fftpack import fft
from scipy.spatial.distance import cdist
from scm.plams import Molecule, Atom, Bond, PeriodicTable, Units
from nanoutils import group_by_values, Literal
from .. import __version__
from ..utils import slice_iter, lattice_to_volume
from .multi_mol_magic import _MultiMolecule, AliasTuple
from ..io.read_kf import read_kf
from ..io.read_xyz import read_multi_xyz
from ..functions.rdf import get_rdf, get_rdf_df
from ..functions.adf import get_adf_df, _adf_inner_cdktree, _adf_inner
from ..functions.molecule_utils import fix_bond_orders, separate_mod
from ..functions.periodic import parse_periodic
from ..functions.debye import get_debye_scattering
if TYPE_CHECKING:
import numpy.typing as npt
try:
import dask
DASK_EX: Optional[Exception] = None
except Exception as ex:
DASK_EX = ex
_warn = ImportWarning(str(ex))
_warn.__cause__ = ex
warnings.warn(_warn)
del _warn
try:
from ase import Atoms
ASE_EX: Optional[ImportError] = None
except ImportError as ex:
ASE_EX = ex
__all__ = ['MultiMolecule']
MT = TypeVar('MT', bound='MultiMolecule')
_DType = TypeVar("_DType", bound=np.dtype)
_T = TypeVar("_T")
MolSubset = Union[None, slice, int]
AtomSubset = Union[
None, slice, range, int, str, Sequence[int], Sequence[str], Sequence[Sequence[int]]
]
def neg_exp(x: np.ndarray) -> np.ndarray:
"""Return :math:`e^{-x}`."""
return np.exp(-x)
class _GetNone:
def __getitem__(self, key: object) -> None:
return None
def _parse_atom_pairs(
mol: MultiMolecule,
atom_pairs: Iterable[tuple[str, str]],
) -> dict[str, list[npt.NDArray[np.intp]]]:
"""Helper function for translating atom-pairs into a dict of indice-array-pairs."""
pair_dict = {}
for atoms in atom_pairs:
key = " ".join(atoms)
idx_list = []
try:
for at in atoms:
idx = mol.atoms.get(at)
if idx is None:
super_at, slc = mol.atoms_alias[at]
idx = mol.atoms[super_at][slc]
idx_list.append(idx)
except KeyError as ex:
raise ValueError(f"Unknown atom type: {ex}") from None
pair_dict[key] = idx_list
return pair_dict
class MultiMolecule(_MultiMolecule):
"""A class designed for handling a and manipulating large numbers of molecules.
More specifically, different conformations of a single molecule as derived from, for example,
an intrinsic reaction coordinate calculation (IRC) or a molecular dymanics trajectory (MD).
The class has access to four attributes (further details are provided under parameters):
Parameters
----------
coords : :class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(m, n, 3)`
A 3D array with the cartesian coordinates of :math:`m` molecules with :math:`n` atoms.
atoms : :class:`dict[str, list[str]] <dict>`
A dictionary with atomic symbols as keys and matching atomic indices as values.
Stored in the :attr:`MultiMolecule.atoms` attribute.
bonds : :class:`np.ndarray[np.int64] <numpy.ndarray>`, shape :math:`(k, 3)`
A 2D array with indices of the atoms defining all :math:`k` bonds
(columns 1 & 2) and their respective bond orders multiplied by 10 (column 3).
Stored in the :attr:`MultiMolecule.bonds` attribute.
properties : :class:`plams.Settings <scm.plams.core.settings.Settings>`
A Settings instance for storing miscellaneous user-defined (meta-)data.
Is devoid of keys by default.
Stored in the :attr:`MultiMolecule.properties` attribute.
lattice : :class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(m, 3, 3)` or :math:`(3, 3)`, optional
Lattice vectors for periodic systems.
For non-periodic systems this value should be :data:`None`.
Attributes
----------
atoms : :class:`dict[str, list[str]] <dict>`
A dictionary with atomic symbols as keys and matching atomic indices as values.
bonds : :class:`np.ndarray[np.int64] <numpy.ndarray>`, shape :math:`(k, 3)`
A 2D array with indices of the atoms defining all :math:`k` bonds
(columns 1 & 2) and their respective bond orders multiplied by 10 (column 3).
properties : :class:`plams.Settings <scm.plams.core.settings.Settings>`
A Settings instance for storing miscellaneous user-defined (meta-)data.
Is devoid of keys by default.
lattice : :class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(m, 3, 3)` or :math:`(3, 3)`, optional
Lattice vectors for periodic systems.
For non-periodic systems this value should be :data:`None`.
""" # noqa: E501
@overload
def round(self: MT, decimals: int = ..., *, inplace: Literal[False] = ...) -> MT: ... # type: ignore[misc] # noqa: E501
@overload
def round(self, decimals: int = ..., *, inplace: Literal[True] = ...) -> None: ...
def round(self, decimals=0, *, inplace=False): # noqa: E301
"""Round the Cartesian coordinates of this instance to a given number of decimals.
Parameters
----------
decimals : :class:`int`
The number of decimals per element.
inplace : :class:`bool`
Instead of returning the new coordinates, perform an inplace update of this instance.
"""
if inplace:
self[:] = super().round(decimals)
return None
else:
ret = self.copy()
ret[:] = super().round(decimals)
return ret
def delete_atoms(self: MT, atom_subset: AtomSubset) -> MT:
"""Create a copy of this instance with all atoms in **atom_subset** removed.
Parameters
----------
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`FOX.MultiMolecule`
A new molecule with all atoms in **atom_subset** removed.
Raises
------
TypeError
Raised if **atom_subset** is :data:`None`.
"""
if atom_subset is None:
raise TypeError("'None' is an invalid value for 'atom_subset'")
# Define subsets
at_subset = self._get_atom_subset(atom_subset, as_array=True)
bool_ar = np.ones(self.shape[1], dtype=bool)
bool_ar[at_subset] = False
# Delete atoms
ret = self[:, bool_ar] # Boolean-array slicing always creates a copy
ret.__dict__ = copy.deepcopy(self.__dict__)
# Update :attr:`.MultiMolecule.atoms`
symbols = self.symbol[bool_ar]
ret.atoms = group_by_values(enumerate(symbols))
# Update :attr:`MultiMolecule.atoms_alias`
if len(ret.atoms_alias):
alias_dct = {}
for k1, (k2, idx_ar) in ret.atoms_alias.items():
idx_ar2 = self.atoms[k2][idx_ar]
bool_slc = bool_ar[idx_ar2]
if not bool_slc.any():
pass
elif bool_slc.all():
alias_dct[k1] = AliasTuple(k2, idx_ar)
else:
idx_ar_new = np.arange(idx_ar2, dtype=np.intp)[bool_slc]
alias_dct[k1] = AliasTuple(k2, idx_ar_new)
ret.atoms_alias = alias_dct
return ret
def get_supercell(self: MT, supercell_size: tuple[int, int, int]) -> MT:
"""Construct a new supercell by duplicating the molecule.
Parameters
----------
supercell_size : :class:`tuple[int, int, int]`
The number of new unit cells along each of the three Cartesian axes.
Returns
-------
:class:`FOX.MultiMolecule`
The new supercell constructed from **self**.
"""
if self.lattice is None:
raise ValueError(f"Cannot construct a supercell from a {self.__class__.__name__} "
"without a lattice")
# Parse and validate th
ar = np.array(supercell_size).astype(np.int64, copy=False, casting="same_kind")
if ar.shape != (3,):
raise ValueError('`duplicates` expected a sequence of length 3')
elif not (ar >= 1).all():
raise ValueError('`duplicates` values must be larger than or equal to 1')
mult = np.array(
[(i, j, k) for i in range(ar[0]) for j in range(ar[1]) for k in range(ar[2])]
)
lat = self.lattice if self.lattice.ndim == 2 else self.lattice[None, ...]
lat_trans = (lat[:, None, ...] * mult[None, ..., None]).sum(axis=-1)
mol_trans = lat_trans[..., None, :] + self[:, None, ...]
if mol_trans.shape[1] == 1:
return mol_trans[..., 0]
else:
mol, other = mol_trans[..., 0], mol_trans[..., 1:]
return mol.concatenate(other[..., 1:], lattice=lat * ar)
def concatenate(
self: MT,
other: Iterable[MT],
lattice: None | npt.ArrayLike = None,
axis: Literal[1] = 1,
) -> MT:
"""Concatenate one or more molecules along the user-specified axis.
Parameters
----------
other : :class:`Iterable[FOX.MultiMolecule] <collections.abc.Iterable>`
The to-be concatenated molecules.
lattice : :class:`np.ndarray <numpy.ndarray>`, optional
The lattice of the new molecule.
Returns
-------
:class:`FOX.MultiMolecule`
The newly concatenated molecule.
"""
if axis != 1:
raise NotImplementedError
mol_list = [self, *other]
if any(m.lattice is not None for m in mol_list) and lattice is None:
raise ValueError("Cannot concatenate lattice-containing molecules without explicitly "
"specifying the new `lattice`")
elif any(len(m.atoms_alias) for m in mol_list):
raise NotImplementedError
elif len({m.shape[0] for m in mol_list}) != 1:
raise ValueError("All `MultiMolecule` instances must be of the same length")
# Construct the new atoms
proto_atoms = defaultdict(list)
offset = 0
for i, m in enumerate(mol_list):
if i:
offset += m.shape[1]
for k, v in m.atoms.items():
proto_atoms[k](v + offset)
atoms = {k: np.fromiter(chain.from_iterable(v), np.int64) for k, v in proto_atoms.items()}
# Construct the new coordinates
coords_shape = (self.shape[0], sum(m.shape[1] for m in mol_list), 3)
coords = np.empty(coords_shape, dtype=np.float64)
i, j = 0, 0
for m in mol_list:
j += m.shape[1]
coords[:, i:j] = m
i += m.shape[1]
# Construct the new bonds
bonds_shape = (sum(m.bonds.shape[0] for m in mol_list), 3)
bonds = np.empty(bonds_shape, dtype=np.int64)
i, j = 0, 0
for m in mol_list:
j += m.bonds.shape[0]
bonds[i:j] = m.bonds
i += m.bonds.shape[0]
cls = type(self)
return cls(coords, atoms, bonds, self.properties.copy(), {}, lattice)
def add_atoms(self: MT, coords: np.ndarray, symbols: Union[str, Iterable[str]] = 'Xx') -> MT:
"""Create a copy of this instance with all atoms in **atom_subset** appended.
Examples
--------
.. code:: python
>>> import numpy as np
>>> from FOX import MultiMolecule, example_xyz
>>> mol = MultiMolecule.from_xyz(example_xyz)
>>> coords: np.ndarray = np.random.rand(73, 3) # Add 73 new atoms with random coords
>>> symbols = 'Br'
>>> mol_new: MultiMolecule = mol.add_atoms(coords, symbols)
>>> print(repr(mol))
MultiMolecule(..., shape=(4905, 227, 3), dtype='float64')
>>> print(repr(mol_new))
MultiMolecule(..., shape=(4905, 300, 3), dtype='float64')
Parameters
----------
coords : array-like
A :math:`(3,)`, :math:`(n, 3)`, :math:`(m, 3)` or :math:`(m, n, 3)` array-like object
with :code:`m == len(self)`.
Represents the Cartesian coordinates of the to-be added atoms.
symbols : :class:`str` or :class:`Iterable[str] <collections.abc.Iterable>`
One or more atomic symbols of the to-be added atoms.
Returns
-------
:class:`FOX.MultiMolecule`
A new molecule with all atoms in **atom_subset** appended.
"""
# Reshape the passed coordinates
coords = np.array(coords, dtype=float, ndmin=3, copy=False)
i, j, k = coords.shape
if i == len(self):
coords_ = coords.reshape(len(self), 1, 3) if k == 1 else coords
elif i == 3 and j == k == 1:
coords_ = np.empty((len(self), 1, 3))
coords_[:] = coords.reshape(1, 1, 3)
else:
coords_ = np.empty((len(self), i, 3))
coords_[:] = coords.reshape(1, i, 3)
j = coords_.shape[1]
# Append
cls = type(self)
ret = cls(np.hstack([self, coords_]))
ret.__dict__ = copy.deepcopy(self.__dict__)
# Update atomic symbols & indices
symbols = repeat(symbols, j) if isinstance(symbols, str) else islice(symbols, j)
dct = {k: v.tolist() for k, v in ret.atoms.items()}
atoms_append = {k: v.append for k, v in dct.items()}
for i, item in enumerate(symbols, self.shape[1]):
try:
atoms_append[item](i)
except KeyError:
dct[item] = list_ = [i]
atoms_append[item] = list_.append
ret.atoms = dct
return ret
def guess_bonds(self, atom_subset: AtomSubset = None) -> None:
"""Guess bonds within the molecules based on atom type and inter-atomic distances.
Bonds are guessed based on the first molecule in this instance
Performs an inplace modification of **self.bonds**
Parameters
----------
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
A tuple of atomic symbols. Bonds are guessed between all atoms
whose atomic symbol is in **atom_subset**.
If :data:`None`, guess bonds for all atoms in this instance.
"""
at_subset = self._get_atom_subset(atom_subset, as_array=True)
at_subset.sort()
# Guess bonds
mol = self.as_Molecule(mol_subset=0, atom_subset=atom_subset)[0]
mol.guess_bonds()
fix_bond_orders(mol)
self.bonds = MultiMolecule.from_Molecule(mol, subset='bonds').bonds
# Update indices in **self.bonds** to account for **atom_subset**
self.atom1 = at_subset[self.atom1]
self.atom2 = at_subset[self.atom2]
self.bonds[:, 0:2].sort(axis=1)
idx = self.bonds[:, 0:2].argsort(axis=0)[:, 0]
self.bonds = self.bonds[idx]
@overload
def random_slice(self: MT, start: int = ..., stop: Optional[int] = ..., p: float = ..., inplace: Literal[False] = ...) -> MT: ... # type: ignore[misc] # noqa: E501
@overload
def random_slice(self, start: int = ..., stop: Optional[int] = ..., p: float = ..., inplace: Literal[True] = ...) -> None: ... # noqa: E501
def random_slice(self, start=0, stop=None, p=0.5, inplace=False): # noqa: E301
"""Construct a new :class:`MultiMolecule` instance by randomly slicing this instance.
The probability of including a particular element is equivalent to **p**.
Parameters
----------
start : :class:`int`
Start of the interval.
stop : :class:`int`, optional
End of the interval.
p : :class:`float`
The probability of including each particular molecule in this instance.
Values must be between ``0`` (0%) and ``1`` (100%).
inplace : :class:`bool`
Instead of returning the new coordinates, perform an inplace update of this instance.
Returns
-------
:class:`FOX.MultiMolecule` or :data:`None`
If **inplace** is :data:`True`, return a new molecule.
Raises
------
ValueError
Raised if **p** is smaller than ``0.0`` or larger than ``1.0``.
"""
if p <= 0.0 or p >= 1.0:
raise ValueError("The supplied probability, 'p': {:f}, must be larger "
"than 0.0 and smaller than 1.0".format(p))
stop = stop or self.shape[0]
idx_range = np.arange(start, stop)
size = int(p * len(idx_range))
idx = np.random.choice(idx_range, size=size, replace=False)
if inplace:
self[:] = self[idx]
return None
else:
return self[idx].copy()
@overload
def reset_origin(self, mol_subset: MolSubset = ..., atom_subset: AtomSubset = ..., inplace: Literal[True] = ..., rot_ref: Optional[npt.ArrayLike] = ...) -> None: ... # type: ignore[misc] # noqa: E501
@overload
def reset_origin(self: MT, mol_subset: MolSubset = ..., atom_subset: AtomSubset = ..., inplace: Literal[False] = ..., rot_ref: Optional[npt.ArrayLike] = ...) -> MT: ... # noqa: E501
def reset_origin(self, mol_subset=None, atom_subset=None, inplace=True, rot_ref=None): # noqa: E301,E501
"""Reallign all molecules in this instance.
All molecules in this instance are rotating and translating, by performing a partial partial
Procrustes superimposition with respect to the first molecule in this instance.
The superimposition is carried out with respect to the first molecule in this instance.
Parameters
----------
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
inplace : :class:`bool`
Instead of returning the new coordinates, perform an inplace update of this instance.
Returns
-------
:class:`FOX.MultiMolecule` or :data:`None`
If **inplace** is :data:`True`, return a new :class:`MultiMolecule` instance.
"""
# Prepare slices
i = self._get_mol_subset(mol_subset)
j = self._get_atom_subset(atom_subset)
# Remove translations
coords = self[i, j, :] - self[i, j, :].mean(axis=1)[:, None, :]
if rot_ref is None:
ref_ar = coords[0]
else:
ref_ar = np.asarray(rot_ref)
# Peform a singular value decomposition on the covariance matrix
H = np.swapaxes(coords, 1, 2) @ ref_ar
U, _, Vt = np.linalg.svd(H)
V, Ut = np.swapaxes(Vt, 1, 2), np.swapaxes(U, 1, 2)
# Construct the rotation matrix
rotmat = np.ones_like(U)
rotmat[:, 2, 2] = np.linalg.det(V @ Ut)
rotmat *= V@Ut
# Return or perform an inplace update of this instance
if inplace:
self[i, j, :] = coords @ np.swapaxes(rotmat, 1, 2)
return None
else:
return coords @ rotmat
@overload
def sort(self, sort_by: Union[str, Sequence[int]] = ..., reverse: bool = ..., inplace: Literal[True] = ...) -> None: ... # type: ignore[misc] # noqa: E501
@overload
def sort(self: MT, sort_by: Union[str, Sequence[int]] = ..., reverse: bool = ..., inplace: Literal[False] = ...) -> MT: ... # noqa: E501
def sort(self, sort_by='symbol', reverse=False, inplace=True): # noqa: E301
"""Sort the atoms in this instance and **self.atoms**, performing in inplace update.
Parameters
----------
sort_by : :class:`str` or :class:`Sequence[int] <collections.abc.Sequence>`
The property which is to be used for sorting.
Accepted values: ``"symbol"`` (*i.e.* alphabetical), ``"atnum"``, ``"mass"``,
``"radius"`` or ``"connectors"``.
See the plams.PeriodicTable_ module for more details.
Alternatively, a user-specified sequence of indices can be provided for sorting.
reverse : :class:`bool`
Sort in reversed order.
inplace : :class:`bool`
Instead of returning the new coordinates, perform an inplace update of this instance.
Returns
-------
:class:`FOX.MultiMolecule` or :data:`None`
If **inplace** is :data:`True`, return a new :class:`MultiMolecule` instance.
"""
# Create and, potentially, sort a list of indices
if isinstance(sort_by, str):
sort_by_array = self._get_atomic_property(prop=sort_by)
_idx_range = range(self.shape[0])
idx_range = np.array([i for _, i in sorted(zip(sort_by_array, _idx_range))])
else:
idx_range = np.asarray(sort_by)
assert sort_by.shape[0] == self.shape[1]
# Reverse or not
if reverse:
idx_range.reverse()
# Inplace update or return a copy
if inplace:
mol = self
else:
mol = self.copy()
# Sort this instance
mol[:] = mol[:, idx_range]
# Refill **self.atoms**
symbols = mol.symbol[idx_range]
atoms_dct = {}
for i, at in enumerate(symbols):
try:
atoms_dct[at].append(i)
except KeyError:
atoms_dct[at] = [i]
mol.atoms = atoms_dct
# Sort **self.bonds**
if mol.bonds is not None:
mol.atom1 = idx_range[mol.atom1]
mol.atom2 = idx_range[mol.atom2]
mol.bonds[:, 0:2].sort(axis=1)
idx = mol.bonds[:, 0:2].argsort(axis=0)[:, 0]
mol.bonds = mol.bonds[idx]
# Inplace update or return a copy
if inplace:
return None
else:
return mol
@overload
def residue_argsort(self, concatenate: Literal[True] = ...) -> np.ndarray: ...
@overload
def residue_argsort(self, concatenate: Literal[False]) -> List[List[int]]: ...
def residue_argsort(self, concatenate=True): # noqa: E301
"""Return the indices that would sort this instance by residue number.
Residues are defined based on moleculair fragments based on **self.bonds**.
Parameters
----------
concatenate : :class:`bool`
If :data:`False`, returned a nested list with atomic indices.
Each sublist contains the indices of a single residue.
Returns
-------
:class:`np.ndarray[np.int64] <numpy.ndarray>`, shape :math:`(n,)`
A 1D array of indices that would sort :math:`n` atoms this instance.
"""
# Define residues
plams_mol = self.as_Molecule(mol_subset=0)[0]
frags = separate_mod(plams_mol)
symbol = self.symbol
# Sort the residues
core = []
ligands = []
for frag in frags:
if len(frag) == 1:
core += frag
else:
i = np.array(frag)
argsort = np.argsort(symbol[i])
ligands.append(i[argsort].tolist())
core.sort()
ligands.sort()
ret = [core] + ligands
if concatenate:
return np.concatenate(ret)
return ret
def get_center_of_mass(self, mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> np.ndarray:
"""Get the center of mass.
Parameters
----------
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(m, 3)`
A 2D array with the centres of mass of :math:`m` molecules with :math:`n` atoms.
"""
coords = self.as_mass_weighted(mol_subset, atom_subset)
return coords.sum(axis=1) / self.mass.sum()
def get_bonds_per_atom(self, atom_subset: AtomSubset = None) -> np.ndarray:
"""Get the number of bonds per atom in this instance.
Parameters
----------
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:math:`n` |np.ndarray|_ [|np.int64|_]:
A 1D array with the number of bonds per atom, for all :math:`n` atoms in this instance.
"""
j = self._get_atom_subset(atom_subset, as_array=True)
if self.bonds is None:
return np.zeros(len(j), dtype=int)
return np.bincount(self.atom12.ravel(), minlength=self.shape[1])[j]
"""################################## Root Mean Squared ###################################"""
def _get_time_averaged_prop(self, method: Callable,
atom_subset: AtomSubset = None,
**kwargs: Any) -> pd.DataFrame:
r"""A method for constructing time-averaged properties.
Parameters
----------
method : :class:`Callable[..., ArrayLike] <collections.abc.Callable>`
A function, method or class used for constructing a specific time-averaged property.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
\**kwargs : :data:`~typing.Any`
Keyword arguments that will be supplied to **method**.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A DataFrame containing a time-averaged property.
"""
# Prepare arguments
loop, at_subset = self._get_loop(atom_subset)
# Get the time-averaged property
if loop:
data = [method(atom_subset=at, **kwargs) for at in at_subset]
else:
data = method(atom_subset=at_subset, **kwargs)
# Construct and return the dataframe
idx = pd.RangeIndex(0, self.shape[1], name='Abritrary atomic index')
column_range, data = self._get_rmsf_columns(data, idx, loop=loop, atom_subset=at_subset)
columns = pd.Index(column_range, name='Atoms')
return pd.DataFrame(data, index=idx, columns=columns)
def _get_average_prop(self, method: Callable,
atom_subset: AtomSubset = None,
**kwargs: Any) -> pd.DataFrame:
r"""A method for constructing properties averaged over atomic subsets.
Parameters
----------
Method : :class:`Callable[..., ArrayLike] <collections.abc.Callable>`
A function, method or class used for constructing a specific atomic subset-averaged
property.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
\**kwargs : :data:`~typing.Any`
Keyword arguments that will be supplied to **method**.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A DataFrame containing an atomic subset-averaged property.
"""
# Prpare arguments
loop, at_subset = self._get_loop(atom_subset)
# Calculate and averaged property
if loop:
data = np.array([method(atom_subset=at, **kwargs) for at in at_subset]).T
else:
data = method(atom_subset=atom_subset, **kwargs).T
# Construct and return the dataframe
column_range = self._get_rmsd_columns(loop, atom_subset)
columns = pd.Index(column_range, name='Atoms')
return pd.DataFrame(data, columns=columns)
def init_average_velocity(self, timestep: float = 1.0,
rms: bool = False,
mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> pd.DataFrame:
"""Calculate the average atomic velocty.
The average velocity (in fs/A) is calculated for all atoms in **atom_subset** over the
course of a trajectory.
The velocity is averaged over all atoms in a particular atom subset.
Parameters
----------
timestep : :class:`float`
The stepsize, in femtoseconds, between subsequent frames.
rms : :class:`bool`
Calculate the root-mean squared average velocity instead.
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if
:data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A dataframe holding :math:`m-1` velocities averaged over one or more atom subsets.
"""
kwargs = {'mol_subset': mol_subset, 'timestep': timestep, 'rms': rms}
df = self._get_average_prop(self.get_average_velocity, atom_subset, **kwargs)
df.index.name = 'Time / fs'
return df
def init_time_averaged_velocity(self, timestep: float = 1.0,
rms: bool = False,
mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> pd.DataFrame:
"""Calculate the time-averaged velocty.
The time-averaged velocity (in fs/A) is calculated for all atoms in **atom_subset** over the
course of a trajectory.
Parameters
----------
timestep : :class:`float`
The stepsize, in femtoseconds, between subsequent frames.
rms : :class:`bool`
Calculate the root-mean squared time-averaged velocity instead.
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A dataframe holding :math:`m-1` time-averaged velocities.
"""
kwargs = {'mol_subset': mol_subset, 'timestep': timestep, 'rms': rms}
return self._get_time_averaged_prop(self.get_time_averaged_velocity, atom_subset, **kwargs)
def init_rmsd(self, mol_subset: MolSubset = None,
atom_subset: AtomSubset = None,
reset_origin: bool = True) -> pd.DataFrame:
"""Initialize the RMSD calculation, returning a dataframe.
Parameters
----------
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
reset_origin : :class:`bool`
Reset the origin of each molecule in this instance by means of
a partial Procrustes superimposition, translating and rotating the molecules.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A dataframe of RMSDs with one column for every string or list of ints in
**atom_subset**.
Keys consist of atomic symbols (*e.g.* ``"Cd"``) if **atom_subset** contains strings,
otherwise a more generic 'series ' + str(int) scheme is adopted (*e.g.* ``"series 2"``).
Molecular indices are used as index.
"""
if reset_origin:
self.reset_origin()
kwargs = {'mol_subset': mol_subset}
df = self._get_average_prop(self.get_rmsd, atom_subset, **kwargs)
df.index.name = 'XYZ frame number'
return df
def init_rmsf(self, mol_subset: MolSubset = None,
atom_subset: AtomSubset = None,
reset_origin: bool = True) -> pd.DataFrame:
"""Initialize the RMSF calculation, returning a dataframe.
Parameters
----------
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
reset_origin : :class:`bool`
Reset the origin of each molecule in this instance by means of
a partial Procrustes superimposition, translating and rotating the molecules.
Returns
-------
:class:`pd.DataFrame <pandas.DataFrame>`
A dataframe of RMSFs with one column for every string or list of ints in
**atom_subset**.
Keys consist of atomic symbols (*e.g.* ``"Cd"``) if **atom_subset** contains strings,
otherwise a more generic 'series ' + str(int) scheme is adopted (*e.g.* ``"series 2"``).
Molecular indices are used as indices.
"""
if reset_origin:
self.reset_origin()
kwargs = {'mol_subset': mol_subset}
return self._get_time_averaged_prop(self.get_rmsf, atom_subset, **kwargs)
def get_average_velocity(self, timestep: float = 1.0,
rms: bool = False,
mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> np.ndarray:
"""Return the mean or root-mean squared velocity.
Parameters
----------
timestep : :class:`float`
The stepsize, in femtoseconds, between subsequent frames.
rms : :class:`bool`
Calculate the root-mean squared average velocity instead.
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if
:data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(m-1,)`
A 1D array holding :math:`m-1` velocities averaged over one or more atom subsets.
"""
if not rms:
return self.get_velocity(timestep, mol_subset=mol_subset,
atom_subset=atom_subset).mean(axis=1)
else:
v = self.get_velocity(timestep, mol_subset=mol_subset, atom_subset=atom_subset)
return MultiMolecule(v, self.atoms).get_rmsd(mol_subset)
def get_time_averaged_velocity(self, timestep: float = 1.0,
rms: bool = False,
mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> np.ndarray:
"""Return the mean or root-mean squared velocity (mean = time-averaged).
Parameters
----------
timestep : :class:`float`
The stepsize, in femtoseconds, between subsequent frames.
rms : :class:`bool`
Calculate the root-mean squared average velocity instead.
mol_subset : :class:`slice`, optional
Perform the calculation on a subset of molecules in this instance, as
determined by their moleculair index.
Include all :math:`m` molecules in this instance if :data:`None`.
atom_subset : :class:`Sequence[str] <collections.abc.Sequence>`, optional
Perform the calculation on a subset of atoms in this instance, as
determined by their atomic index or atomic symbol.
Include all :math:`n` atoms per molecule in this instance if :data:`None`.
Returns
-------
:class:`np.ndarray[np.float64] <numpy.ndarray>`, shape :math:`(n,)`
A 1D array holding :math:`n` time-averaged velocities.
"""
if not rms:
return self.get_velocity(timestep, mol_subset=mol_subset,
atom_subset=atom_subset).mean(axis=0)
else:
v = self.get_velocity(timestep, mol_subset=mol_subset, atom_subset=atom_subset)
return MultiMolecule(v, self.atoms).get_rmsf(mol_subset)
def get_velocity(self, timestep: float = 1.0,
norm: bool = True,
mol_subset: MolSubset = None,
atom_subset: AtomSubset = None) -> np.ndarray:
"""Return the atomic velocties.
The velocity (in fs/A) is calculated for all atoms in **atom_subset** over the course of a
trajectory.