-
Notifications
You must be signed in to change notification settings - Fork 637
/
groups.py
4028 lines (3357 loc) · 154 KB
/
groups.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
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the GNU Public Licence, v2 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""\
==========================================================
Core objects: Containers --- :mod:`MDAnalysis.core.groups`
==========================================================
The :class:`~MDAnalysis.core.universe.Universe` instance contains all the
particles in the system (which MDAnalysis calls :class:`Atom`). Groups of
:class:`atoms<Atom>` are handled as :class:`AtomGroup` instances. The
:class:`AtomGroup` is probably the most important object in MDAnalysis because
virtually everything can be accessed through it. :class:`AtomGroup` instances
can be easily created (e.g., from an :meth:`AtomGroup.select_atoms` selection or
simply by slicing).
For convenience, chemically meaningful groups of :class:`Atoms<Atom>` such as a
:class:`Residue` or a :class:`Segment` (typically a whole molecule or all of the
solvent) also exist as containers, as well as groups of these units
(:class:`ResidueGroup`, :class:`SegmentGroup`).
Classes
=======
Collections
-----------
.. autoclass:: AtomGroup
:members:
:inherited-members:
.. autoclass:: ResidueGroup
:members:
:inherited-members:
.. autoclass:: SegmentGroup
:members:
:inherited-members:
.. autoclass:: UpdatingAtomGroup
:members:
Chemical units
--------------
.. autoclass:: Atom
:members:
:inherited-members:
.. autoclass:: Residue
:members:
:inherited-members:
.. autoclass:: Segment
:members:
:inherited-members:
Levels
------
Each of the above classes has a *level* attribute. This can be used to verify
that two objects are of the same level, or to access a particular class::
u = mda.Universe()
ag = u.atoms[:10]
at = u.atoms[11]
ag.level == at.level # Returns True
ag.level.singular # Returns Atom class
at.level.plural # Returns AtomGroup class
"""
from __future__ import absolute_import, division
from six.moves import zip
from six import string_types
from collections import namedtuple
import numpy as np
import functools
import itertools
import numbers
import os
import warnings
from numpy.lib.utils import deprecate
from .. import _ANCHOR_UNIVERSES
from ..lib import util
from ..lib.util import cached, warn_if_not_unique, unique_int_1d
from ..lib import distances
from ..lib import transformations
from ..lib import mdamath
from ..selections import get_writer as get_selection_writer_for
from . import selection
from . import flags
from ..exceptions import NoDataError
from . import topologyobjects
from ._get_readers import get_writer_for
def _unpickle(uhash, ix):
try:
u = _ANCHOR_UNIVERSES[uhash]
except KeyError:
# doesn't provide as nice an error message as before as only hash of universe is stored
# maybe if we pickled the filename too we could do better...
raise RuntimeError(
"Couldn't find a suitable Universe to unpickle AtomGroup onto "
"with Universe hash '{}'. Available hashes: {}"
"".format(uhash, ', '.join([str(k)
for k in _ANCHOR_UNIVERSES.keys()])))
return u.atoms[ix]
def _unpickle_uag(basepickle, selections, selstrs):
bfunc, bargs = basepickle[0], basepickle[1:][0]
basegroup = bfunc(*bargs)
return UpdatingAtomGroup(basegroup, selections, selstrs)
def make_classes():
"""Make a fresh copy of all classes
Returns
-------
Two dictionaries. One with a set of :class:`_TopologyAttrContainer` classes
to serve as bases for :class:`~MDAnalysis.core.universe.Universe`\ -specific
MDA container classes. Another with the final merged versions of those
classes. The classes themselves are used as hashing keys.
"""
bases = {}
classes = {}
groups = (AtomGroup, ResidueGroup, SegmentGroup)
components = (Atom, Residue, Segment)
# The 'GBase' middle man is needed so that a single topologyattr
# patching applies automatically to all groups.
GBase = bases[GroupBase] = _TopologyAttrContainer._subclass(is_group=True)
for cls in groups:
bases[cls] = GBase._subclass(is_group=True)
# CBase for patching all components
CBase = bases[ComponentBase] = _TopologyAttrContainer._subclass(
is_group=False)
for cls in components:
bases[cls] = CBase._subclass(is_group=False)
# Initializes the class cache.
for cls in groups + components:
classes[cls] = bases[cls]._mix(cls)
return bases, classes
class _TopologyAttrContainer(object):
"""Class factory for receiving sets of :class:`TopologyAttr` objects.
:class:`_TopologyAttrContainer` is a convenience class to encapsulate the
functions that deal with:
* the import and namespace transplant of
:class:`~MDAnalysis.core.topologyattrs.TopologyAttr` objects;
* the copying (subclassing) of itself to create distinct bases for the
different container classes (:class:`AtomGroup`, :class:`ResidueGroup`,
:class:`SegmentGroup`, :class:`Atom`, :class:`Residue`, :class:`Segment`,
and subclasses thereof);
* the mixing (subclassing and co-inheritance) with the container classes.
The mixed subclasses become the final container classes specific to each
:class:`~MDAnalysis.core.universe.Universe`.
"""
@classmethod
def _subclass(cls, is_group):
"""Factory method returning :class:`_TopologyAttrContainer` subclasses.
Parameters
----------
is_group : bool
The :attr:`_is_group` of the returned class will be set to
`is_group`. This is used to distinguish between Groups
(:class:`AtomGroup` etc.) and Components (:class:`Atom` etc.) in
internal methods when considering actions such as addition of
objects or adding
:class:`TopologyAttributes<MDAnalysis.core.topologyattrs.TopologyAttr>`
to them.
Returns
-------
type
A subclass of :class:`_TopologyAttrContainer`, with the same name.
"""
newcls = type(cls.__name__, (cls,), {'_is_group': bool(is_group)})
if is_group:
newcls._SETATTR_WHITELIST = {
'positions', 'velocities', 'forces', 'dimensions',
'atoms', 'residue', 'residues', 'segment', 'segments',
}
else:
newcls._SETATTR_WHITELIST = {
'position', 'velocity', 'force', 'dimensions',
'atoms', 'residue', 'residues', 'segment',
}
return newcls
@classmethod
def _mix(cls, other):
"""Creates a subclass with ourselves and another class as parents.
Classes mixed at this point override :meth:`__new__`, causing further
instantiations to shortcut to :meth:`~object.__new__` (skipping the
cache-fetch process for :class:`_MutableBase` subclasses).
The new class will have an attribute `_derived_class` added, pointing
to itself. This pointer instructs which class to use when
slicing/adding instances of the new class. At initialization time, the
new class may choose to point `_derived_class` to another class (as is
done in the initialization of :class:`UpdatingAtomGroup`).
Parameters
----------
other : type
The class to mix with ourselves.
Returns
-------
type
A class of parents :class:`_ImmutableBase`, *other* and this class.
Its name is the same as *other*'s.
"""
newcls = type(other.__name__, (_ImmutableBase, other, cls), {})
newcls._derived_class = newcls
return newcls
@classmethod
def _add_prop(cls, attr):
"""Add `attr` into the namespace for this class
Parameters
----------
attr : A :class:`TopologyAttr` object
"""
def getter(self):
return attr.__getitem__(self)
def setter(self, values):
return attr.__setitem__(self, values)
if cls._is_group:
setattr(cls, attr.attrname,
property(getter, setter, None, attr.groupdoc))
cls._SETATTR_WHITELIST.add(attr.attrname)
else:
setattr(cls, attr.singular,
property(getter, setter, None, attr.singledoc))
cls._SETATTR_WHITELIST.add(attr.singular)
def __setattr__(self, attr, value):
# `ag.this = 42` calls setattr(ag, 'this', 42)
if not (attr.startswith('_') or # 'private' allowed
attr in self._SETATTR_WHITELIST or # known attributes allowed
hasattr(self, attr)): # preexisting (eg properties) allowed
raise AttributeError(
"Cannot set arbitrary attributes to a {}".format(
'Group' if self._is_group else 'Component'))
# if it is, we allow the setattr to proceed by deferring to the super
# behaviour (ie do it)
super(_TopologyAttrContainer, self).__setattr__(attr, value)
class _MutableBase(object):
"""
Base class that merges appropriate :class:`_TopologyAttrContainer` classes.
Implements :meth:`__new__`. In it the instantiating class is fetched from
:attr:`~MDAnalysis.core.universe.Universe._classes`. If there is a cache
miss, a merged class is made
with a base from :attr:`~MDAnalysis.core.universe.Universe._class_bases`
and cached.
The classes themselves are used as the cache dictionary keys for simplcity
in cache retrieval.
"""
def __new__(cls, *args, **kwargs):
# This pre-initialization wrapper must be pretty generic to
# allow for different initialization schemes of the possible classes.
# All we really need here is to fish a universe out of the arg list.
# The AtomGroup cases get priority and are fished out first.
try:
u = args[-1].universe
except (IndexError, AttributeError):
try:
# older AtomGroup init method..
u = args[0][0].universe
except (TypeError, IndexError, AttributeError):
from .universe import Universe
# Let's be generic and get the first argument that's either a
# Universe, a Group, or a Component, and go from there.
# This is where the UpdatingAtomGroup args get matched.
for arg in args+tuple(kwargs.values()):
if isinstance(arg, (Universe, GroupBase,
ComponentBase)):
u = arg.universe
break
else:
raise TypeError("No universe, or universe-containing "
"object passed to the initialization of "
"{}".format(cls.__name__))
try:
return object.__new__(u._classes[cls])
except KeyError:
# Cache miss. Let's find which kind of class this is and merge.
try:
parent_cls = next(u._class_bases[parent]
for parent in cls.mro()
if parent in u._class_bases)
except StopIteration:
raise TypeError("Attempted to instantiate class '{}' but "
"none of its parents are known to the "
"universe. Currently possible parent "
"classes are: {}".format(cls.__name__,
str(sorted(u._class_bases.keys()))))
newcls = u._classes[cls] = parent_cls._mix(cls)
return object.__new__(newcls)
class _ImmutableBase(object):
"""Class used to shortcut :meth:`__new__` to :meth:`object.__new__`.
"""
# When mixed via _TopologyAttrContainer._mix this class has MRO priority.
# Setting __new__ like this will avoid having to go through the
# cache lookup if the class is reused (as in ag._derived_class(...)).
__new__ = object.__new__
def _only_same_level(function):
@functools.wraps(function)
def wrapped(self, other):
if not isinstance(other, (ComponentBase, GroupBase)): # sanity check
raise TypeError("Can't perform '{}' between objects:"
" '{}' and '{}'".format(
function.__name__,
type(self).__name__,
type(other).__name__))
if self.level != other.level:
raise TypeError("Can't perform '{}' on different level objects"
"".format(function.__name__))
if self.universe is not other.universe:
raise ValueError(
"Can't operate on objects from different Universes")
return function(self, other)
return wrapped
class GroupBase(_MutableBase):
"""Base class from which a :class:`<~MDAnalysis.core.universe.Universe`\ 's
Group class is built.
Instances of :class:`GroupBase` provide the following operations that
conserve element repetitions and order:
+-------------------------------+------------+----------------------------+
| Operation | Equivalent | Result |
+===============================+============+============================+
| ``len(s)`` | | number of elements (atoms, |
| | | residues or segment) in |
| | | the group |
+-------------------------------+------------+----------------------------+
| ``s == t`` | | test if ``s`` and ``t`` |
| | | contain the same elements |
| | | in the same order |
+-------------------------------+------------+----------------------------+
| ``x in s`` | | test if component ``x`` is |
| | | part of group ``s`` |
+-------------------------------+------------+----------------------------+
| ``s.concatenate(t)`` | ``s + t`` | new Group with elements |
| | | from ``s`` and from ``t`` |
+-------------------------------+------------+----------------------------+
| ``s.subtract(t)`` | | new Group with elements |
| | | from ``s`` that are not |
| | | in ``t`` |
+-------------------------------+------------+----------------------------+
The following operations treat the Group as set. Any result will have any
duplicate entries removed and the Group will be sorted.
+-------------------------------+------------+----------------------------+
| Operation | Equivalent | Result |
+===============================+============+============================+
| ``s.isdisjoint(t)`` | | ``True`` if ``s`` and |
| | | ``t`` do not share |
| | | elements |
+-------------------------------+------------+----------------------------+
| ``s.issubset(t)`` | | test if all elements of |
| | | ``s`` are part of ``t`` |
+-------------------------------+------------+----------------------------+
| ``s.is_strict_subset(t)`` | | test if all elements of |
| | | ``s`` are part of ``t``, |
| | | and ``s != t`` |
+-------------------------------+------------+----------------------------+
| ``s.issuperset(t)`` | | test if all elements of |
| | | ``t`` are part of ``s`` |
+-------------------------------+------------+----------------------------+
| ``s.is_strict_superset(t)`` | | test if all elements of |
| | | ``t`` are part of ``s``, |
| | | and ``s != t`` |
+-------------------------------+------------+----------------------------+
| ``s.union(t)`` | ``s | t`` | new Group with elements |
| | | from both ``s`` and ``t`` |
+-------------------------------+------------+----------------------------+
| ``s.intersection(t)`` | ``s & t`` | new Group with elements |
| | | common to ``s`` and ``t`` |
+-------------------------------+------------+----------------------------+
| ``s.difference(t)`` | ``s - t`` | new Group with elements of |
| | | ``s`` that are not in ``t``|
+-------------------------------+------------+----------------------------+
| ``s.symmetric_difference(t)`` | ``s ^ t`` | new Group with elements |
| | | that are part of ``s`` or |
| | | ``t`` but not both |
+-------------------------------+------------+----------------------------+
"""
def __init__(self, *args):
try:
if len(args) == 1:
# list of atoms/res/segs, old init method
ix = [at.ix for at in args[0]]
u = args[0][0].universe
else:
# current/new init method
ix, u = args
except (AttributeError, # couldn't find ix/universe
TypeError): # couldn't iterate the object we got
raise TypeError(
"Can only initialise a Group from an iterable of Atom/Residue/"
"Segment objects eg: AtomGroup([Atom1, Atom2, Atom3]) "
"or an iterable of indices and a Universe reference "
"eg: AtomGroup([0, 5, 7, 8], u).")
# indices for the objects I hold
self._ix = np.asarray(ix, dtype=np.intp)
self._u = u
self._cache = dict()
def __hash__(self):
return hash((self._u, self.__class__, tuple(self.ix.tolist())))
def __len__(self):
return len(self.ix)
def __getitem__(self, item):
# supports
# - integer access
# - boolean slicing
# - fancy indexing
# because our _ix attribute is a numpy array
# it can be sliced by all of these already,
# so just return ourselves sliced by the item
if isinstance(item, numbers.Integral):
return self.level.singular(self.ix[item], self.universe)
else:
if isinstance(item, list) and item: # check for empty list
# hack to make lists into numpy arrays
# important for boolean slicing
item = np.array(item)
# We specify _derived_class instead of self.__class__ to allow
# subclasses, such as UpdatingAtomGroup, to control the class
# resulting from slicing.
return self._derived_class(self.ix[item], self.universe)
def __repr__(self):
name = self.level.name
return ("<{}Group with {} {}{}>"
"".format(name.capitalize(), len(self), name,
"s"[len(self)==1:])) # Shorthand for a conditional plural 's'.
def __str__(self):
name = self.level.name
if len(self) <= 10:
return '<{}Group {}>'.format(name.capitalize(), repr(list(self)))
else:
return '<{}Group {}, ..., {}>'.format(name.capitalize(),
repr(list(self)[:3])[:-1],
repr(list(self)[-3:])[1:])
def __add__(self, other):
"""Concatenate the Group with another Group or Component of the same
level.
Parameters
----------
other : Group or Component
Group or Component with `other.level` same as `self.level`
Returns
-------
Group
Group with elements of `self` and `other` concatenated
"""
return self.concatenate(other)
def __radd__(self, other):
"""Using built-in sum requires supporting 0 + self. If other is
anything other 0, an exception will be raised.
Parameters
----------
other : int
Other should be 0, or else an exception will be raised.
Returns
-------
self
Group with elements of `self` reproduced
"""
if other == 0:
return self._derived_class(self.ix, self.universe)
else:
raise TypeError("unsupported operand type(s) for +:"
" '{}' and '{}'".format(type(self).__name__,
type(other).__name__))
def __sub__(self, other):
return self.difference(other)
@_only_same_level
def __eq__(self, other):
"""Test group equality.
Two groups are equal if they contain the same indices in
the same order. Groups that are not at the same level or that belong
to different :class:`Universes<MDAnalysis.core.universe.Universe>`
cannot be compared.
"""
o_ix = other.ix
return np.array_equal(self.ix, o_ix)
def __contains__(self, other):
if not other.level == self.level:
# maybe raise TypeError instead?
# eq method raises Error for wrong comparisons
return False
return other.ix in self.ix
def __or__(self, other):
return self.union(other)
def __and__(self, other):
return self.intersection(other)
def __xor__(self, other):
return self.symmetric_difference(other)
@property
def universe(self):
"""The underlying :class:`~MDAnalysis.core.universe.Universe` the group
belongs to.
"""
return self._u
@property
def ix(self):
"""Unique indices of the components in the Group.
- If this Group is an :class:`AtomGroup`, these are the
indices of the :class:`Atom` instances.
- If it is a :class:`ResidueGroup`, these are the indices of
the :class:`Residue` instances.
- If it is a :class:`SegmentGroup`, these are the indices of
the :class:`Segment` instances.
"""
return self._ix
@property
def ix_array(self):
"""Unique indices of the components in the Group.
For a Group, :attr:`ix_array` is the same as :attr:`ix`. This method
gives a consistent API between components and groups.
See Also
--------
:attr:`ix`
"""
return self._ix
@property
def dimensions(self):
"""Obtain a copy of the dimensions of the currently loaded Timestep"""
return self.universe.trajectory.ts.dimensions.copy()
@dimensions.setter
def dimensions(self, dimensions):
self.universe.trajectory.ts.dimensions = dimensions
@property
@cached('isunique')
def isunique(self):
"""Boolean indicating whether all components of the group are unique,
i.e., the group contains no duplicates.
Examples
--------
>>> ag = u.atoms[[2, 1, 2, 2, 1, 0]]
>>> ag
<AtomGroup with 6 atoms>
>>> ag.isunique
False
>>> ag2 = ag.unique
>>> ag2
<AtomGroup with 3 atoms>
>>> ag2.isunique
True
.. versionadded:: 0.19.0
"""
if len(self) <= 1:
return True
# Fast check for uniqueness
# 1. get sorted array of component indices:
s_ix = np.sort(self._ix)
# 2. If the group's components are unique, no pair of adjacent values in
# the sorted indices array are equal. We therefore compute a boolean
# mask indicating equality of adjacent sorted indices:
mask = s_ix[1:] == s_ix[:-1]
# 3. The group is unique if all elements in the mask are False. We could
# return ``not np.any(mask)`` here but using the following is faster:
return not np.count_nonzero(mask)
@warn_if_not_unique
def center(self, weights, pbc=None, compound='group'):
"""Weighted center of (compounds of) the group
Computes the weighted center of :class:`Atoms<Atom>` in the group.
Weighted centers per :class:`Residue`, :class:`Segment`, molecule, or
fragment can be obtained by setting the `compound` parameter
accordingly. If the weights of a compound sum up to zero, the
coordinates of that compound's weighted center will be ``nan`` (not a
number).
Parameters
----------
weights : array_like or None
Weights to be used. Setting `weights=None` is equivalent to passing
identical weights for all atoms of the group.
pbc : bool or None, optional
If ``True`` and `compound` is ``'group'``, move all atoms to the
primary unit cell before calculation. If ``True`` and `compound` is
``'segments'``, ``'residues'``, ``'molecules'``, or ``'fragments'``,
the center of each compound will be calculated without moving any
:class:`Atoms<Atom>` to keep the compounds intact. Instead, the
resulting position vectors will be moved to the primary unit cell
after calculation.
compound : {'group', 'segments', 'residues', 'molecules', 'fragments'}, optional
If ``'group'``, the weighted center of all atoms in the group will
be returned as a single position vector. Else, the weighted centers
of each :class:`Segment`, :class:`Residue`, molecule, or fragment
will be returned as an array of position vectors, i.e. a 2d array.
Note that, in any case, *only* the positions of :class:`Atoms<Atom>`
*belonging to the group* will be taken into account.
Returns
-------
center : numpy.ndarray
Position vector(s) of the weighted center(s) of the group.
If `compound` was set to ``'group'``, the output will be a single
position vector.
If `compound` was set to ``'segments'``, ``'residues'``,
``'molecules'``, or ``'fragments'``, the output will be a 2d array
of shape ``(n, 3)`` where ``n`` is the number of compounds.
Raises
------
ValueError
If `compound` is not one of ``'group'``, ``'segments'``,
``'residues'``, ``'molecules'``, or ``'fragments'``.
~MDAnalysis.exceptions.NoDataError
If `compound` is ``'molecule'`` but the topology doesn't
contain molecule information (molnums) or if `compound` is
``'fragments'`` but the topology doesn't contain bonds.
Examples
--------
To find the center of charge of a given :class:`AtomGroup`::
>>> sel = u.select_atoms('prop mass > 4.0')
>>> sel.center(sel.charges)
To find the centers of mass per residue of all CA :class:`Atoms<Atom>`::
>>> sel = u.select_atoms('name CA')
>>> sel.center(sel.masses, compound='residues')
Notes
-----
If the :class:`MDAnalysis.core.flags` flag *use_pbc* is set to
``True`` then the `pbc` keyword is used by default.
.. versionchanged:: 0.19.0 Added `compound` parameter
.. versionchanged:: 0.20.0 Added ``'molecules'`` and ``'fragments'``
compounds
"""
if pbc is None:
pbc = flags['use_pbc']
atoms = self.atoms
# enforce calculations in double precision:
dtype = np.float64
comp = compound.lower()
if comp == 'group':
if pbc:
coords = atoms.pack_into_box(inplace=False)
else:
coords = atoms.positions
# If there's no atom, return its (empty) coordinates unchanged.
if len(atoms) == 0:
return coords
if weights is None:
# promote coords to dtype if required:
coords = coords.astype(dtype, copy=False)
return coords.mean(axis=0)
# promote weights to dtype if required:
weights = weights.astype(dtype, copy=False)
return (coords * weights[:, None]).sum(axis=0) / weights.sum()
elif comp == 'residues':
compound_indices = atoms.resindices
elif comp == 'segments':
compound_indices = atoms.segindices
elif comp == 'molecules':
try:
compound_indices = atoms.molnums
except AttributeError:
raise NoDataError("Cannot use compound='molecules': "
"No molecule information in topology.")
elif comp == 'fragments':
try:
compound_indices = atoms.fragindices
except NoDataError:
raise NoDataError("Cannot use compound='fragments': "
"No bond information in topology.")
else:
raise ValueError("Unrecognized compound definition: {}\nPlease use"
" one of 'group', 'residues', 'segments', "
"'molecules', or 'fragments'.".format(compound))
# Sort positions and weights by compound index and promote to dtype if
# required:
sort_indices = np.argsort(compound_indices)
compound_indices = compound_indices[sort_indices]
coords = atoms.positions[sort_indices]
if weights is None:
coords = coords.astype(dtype, copy=False)
else:
weights = weights.astype(dtype, copy=False)
weights = weights[sort_indices]
# Get sizes of compounds:
unique_compound_indices, compound_sizes = np.unique(compound_indices,
return_counts=True)
n_compounds = len(unique_compound_indices)
unique_compound_sizes = unique_int_1d(compound_sizes)
# Allocate output array:
centers = np.zeros((n_compounds, 3), dtype=dtype)
# Compute centers per compound for each compound size:
for compound_size in unique_compound_sizes:
compound_mask = compound_sizes == compound_size
_compound_indices = unique_compound_indices[compound_mask]
atoms_mask = np.in1d(compound_indices, _compound_indices)
_coords = coords[atoms_mask].reshape((-1, compound_size, 3))
if weights is None:
_centers = _coords.mean(axis=1)
else:
_weights = weights[atoms_mask].reshape((-1, compound_size))
_centers = (_coords * _weights[:, :, None]).sum(axis=1)
_centers /= _weights.sum(axis=1)[:, None]
centers[compound_mask] = _centers
if pbc:
centers = distances.apply_PBC(centers, atoms.dimensions)
return centers
@warn_if_not_unique
def center_of_geometry(self, pbc=None, compound='group'):
"""Center of geometry of (compounds of) the group.
Computes the center of geometry (a.k.a. centroid) of
:class:`Atoms<Atom>` in the group. Centers of geometry per
:class:`Residue`, :class:`Segment`, molecule, or fragment can be
obtained by setting the `compound` parameter accordingly.
Parameters
----------
pbc : bool or None, optional
If ``True`` and `compound` is ``'group'``, move all atoms to the
primary unit cell before calculation. If ``True`` and `compound` is
``'segments'`` or ``'residues'``, the center of each compound will
be calculated without moving any :class:`Atoms<Atom>` to keep the
compounds intact. Instead, the resulting position vectors will be
moved to the primary unit cell after calculation.
compound : {'group', 'segments', 'residues', 'molecules', 'fragments'}, optional
If ``'group'``, the center of geometry of all :class:`Atoms<Atom>`
in the group will be returned as a single position vector. Else, the
centers of geometry of each :class:`Segment` or :class:`Residue`
will be returned as an array of position vectors, i.e. a 2d array.
Note that, in any case, *only* the positions of :class:`Atoms<Atom>`
*belonging to the group* will be taken into account.
Returns
-------
center : numpy.ndarray
Position vector(s) of the geometric center(s) of the group.
If `compound` was set to ``'group'``, the output will be a single
position vector.
If `compound` was set to ``'segments'`` or ``'residues'``, the
output will be a 2d array of shape ``(n, 3)`` where ``n`` is the
number of compounds.
Notes
-----
If the :class:`MDAnalysis.core.flags` flag *use_pbc* is set to
``True`` then the `pbc` keyword is used by default.
.. versionchanged:: 0.8 Added `pbc` keyword
.. versionchanged:: 0.19.0 Added `compound` parameter
.. versionchanged:: 0.20.0 Added ``'molecules'`` and ``'fragments'``
compounds
"""
return self.center(None, pbc=pbc, compound=compound)
centroid = center_of_geometry
@warn_if_not_unique
def accumulate(self, attribute, function=np.sum, compound='group'):
"""Accumulates the attribute associated with (compounds of) the group.
Accumulates the attribute of :class:`Atoms<Atom>` in the group.
The accumulation per :class:`Residue`, :class:`Segment`, molecule,
or fragment can be obtained by setting the `compound` parameter
accordingly. By default, the method sums up all attributes per compound,
but any function that takes an array and returns an acuumulation over a
given axis can be used. For multi-dimensional input arrays, the
accumulation is performed along the first axis.
Parameters
----------
attribute : str or array_like
Attribute or array of values to accumulate.
If a :class:`numpy.ndarray` (or compatible) is provided, its first
dimension must have the same length as the total number of atoms in
the group.
function : callable, optional
The function performing the accumulation. It must take the array of
attribute values to accumulate as its only positional argument and
accept an (optional) keyword argument ``axis`` allowing to specify
the axis along which the accumulation is performed.
compound : {'group', 'segments', 'residues', 'molecules', 'fragments'},\
optional
If ``'group'``, the accumulation of all attributes associated with
atoms in the group will be returned as a single value. Otherwise,
the accumulation of the attributes per :class:`Segment`,
:class:`Residue`, molecule, or fragment will be returned as a 1d
array. Note that, in any case, *only* the :class:`Atoms<Atom>`
*belonging to the group* will be taken into account.
Returns
-------
float or numpy.ndarray
Acuumulation of the `attribute`.
If `compound` is set to ``'group'``, the first dimension of the
`attribute` array will be contracted to a single value.
If `compound` is set to ``'segments'``, ``'residues'``,
``'molecules'``, or ``'fragments'``, the length of the first
dimension will correspond to the number of compounds. In all cases,
the other dimensions of the returned array will be of the original
shape (without the first dimension).
Raises
------
ValueError
If the length of a provided `attribute` array does not correspond to
the number of atoms in the group.
ValueError
If `compound` is not one of ``'group'``, ``'segments'``,
``'residues'``, ``'molecules'``, or ``'fragments'``.
~MDAnalysis.exceptions.NoDataError
If `compound` is ``'molecule'`` but the topology doesn't
contain molecule information (molnums), or if `compound` is
``'fragments'`` but the topology doesn't contain bonds.
Examples
--------
To find the total charge of a given :class:`AtomGroup`::
>>> sel = u.select_atoms('prop mass > 4.0')
>>> sel.accumulate('charges')
To find the total mass per residue of all CA :class:`Atoms<Atom>`::
>>> sel = u.select_atoms('name CA')
>>> sel.accumulate('masses', compound='residues')
To find the maximum atomic charge per fragment of a given
:class:`AtomGroup`::
>>> sel.accumulate('charges', compound="fragments", function=np.max)
.. versionadded:: 0.20.0
"""
atoms = self.atoms
if isinstance(attribute, string_types):
attribute_values = getattr(atoms, attribute)
else:
attribute_values = np.asarray(attribute)
if len(attribute_values) != len(atoms):
raise ValueError("The input array length ({}) does not match "
"the number of atoms ({}) in the group."
"".format(len(attribute_values), len(atoms)))
comp = compound.lower()
if comp == 'group':
return function(attribute_values, axis=0)
elif comp == 'residues':
compound_indices = atoms.resindices
elif comp == 'segments':
compound_indices = atoms.segindices
elif comp == 'molecules':
try:
compound_indices = atoms.molnums
except AttributeError:
raise NoDataError("Cannot use compound='molecules': "
"No molecule information in topology.")
elif comp == 'fragments':
try:
compound_indices = atoms.fragindices
except NoDataError:
raise NoDataError("Cannot use compound='fragments': "
"No bond information in topology.")
else:
raise ValueError("Unrecognized compound definition: '{}'. Please "
"use one of 'group', 'residues', 'segments', "
"'molecules', or 'fragments'.".format(compound))
higher_dims = list(attribute_values.shape[1:])
# Sort attribute values by compound
sort_indices = np.argsort(compound_indices)
compound_indices = compound_indices[sort_indices]
attribute_values = attribute_values[sort_indices]
# Get sizes of compounds:
unique_compound_indices, compound_sizes = np.unique(compound_indices,
return_counts=True)
n_compounds = len(unique_compound_indices)
unique_compound_sizes = unique_int_1d(compound_sizes)
# Allocate output array:
accumulation = np.zeros([n_compounds] + higher_dims)
# Compute sums per compound for each compound size:
for compound_size in unique_compound_sizes:
compound_mask = compound_sizes == compound_size
_compound_indices = unique_compound_indices[compound_mask]
atoms_mask = np.in1d(compound_indices, _compound_indices)
_elements = attribute_values[atoms_mask].reshape([-1, compound_size]
+ higher_dims)
_accumulation = function(_elements, axis=1)
accumulation[compound_mask] = _accumulation
return accumulation
def bbox(self, **kwargs):
"""Return the bounding box of the selection.