
     iL                    b   d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZmZmZmZ ddlmZ ddlmZmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ ddlmZ  ddlm!Z! ddl"m#Z# ddlm$Z$ ddl%m&Z&m'Z' d Z(d Z)d Z*d Z+ G d de,          Z- G d de,          Z. G d de,          Z/d Z0d Z1d Z2 G d d e.          Z3 G d! d"e3          Z4 G d# d$e3          Z5 G d% d&e3          Z6ej7         G d' d(e.                      Z8 G d) d*e8          Z9 G d+ d,e8          Z: G d- d.e8          Z;h d/Z< G d0 d1e4          Z= ed2g d3          Z> e>d4e9e4          Z? e>d5e:e5          Z@ e>d6e;e6          ZAe?e9_B        e?e4_B        e@e:_B        e@e5_B        eAe;_B        eAe6_B        d7 ZCdS )8a  ==========================================================
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

.. code-block:: python

    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

    )
namedtupleN   )_CONVERTERS_TOPOLOGY_ATTRS_TOPOLOGY_TRANSPLANTS_TOPOLOGY_ATTRNAMES)util)cachedwarn_if_not_uniqueunique_int_1dunique_int_1d_unsortedint_array_is_sorted)	distances)transformations)mdamath   )AccessorConverterWrapper)
get_writer)	selection)NoDataError)topologyobjects)get_writer_forget_converter_forc                     | j         |         S N)atoms)uixs     `/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/core/groups.py	_unpickler!      s    72;    c                      |||           S r    )r   r   clss      r    
_unpickle2r&      s    3r1::r"   c                 ^    | d         | dd          d         }} || }t          |||          S )Nr   r   )UpdatingAtomGroup)
basepickle
selectionsselstrsbfuncbargs	basegroups         r    _unpickle_uagr/      s9    a=*QRR."35EuIY
G<<<r"   c                     i } i }t           t          t          f}t          t          t
          f}t                              d          x}| t          <   |D ]}|                    d          | |<   t                              d          x}| t          <   |D ]}|                    d          | |<   ||z   D ] }| |         
                    |          ||<   !| |fS )ah  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.
    T)is_groupF)	AtomGroupResidueGroupSegmentGroupAtomResidueSegment_TopologyAttrContainer	_subclass	GroupBaseComponentBase_mix)basesclassesgroups
componentsGBaser%   CBases          r    make_classesrC      s     EG|4F)J  6???NNNEE) 4 4__d_33c

#9#C#C $D $ $ EE-   5 5__e_44c

 
" , ,Szs++'>r"   c                   z     e Zd ZdZed             Zed             Zed             Zed             Z fdZ	 xZ
S )r8   a  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`.
    c                 |    t          | j        | fdt          |          i          }|r
h d|_        n	h d|_        |S )a  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.
        	_is_group>	   r   forcesresiduesegmentresiduessegments	positions
dimensions
velocities>   r   forcerH   rI   positionrJ   velocityrM   )type__name__bool_SETATTR_WHITELIST)r%   r1   newclss      r    r9   z _TopologyAttrContainer._subclass   s^    ( clSF[$x..,IJJ 	
) 
) 
)F%%	) 	) 	)F% r"   c                 P    t          |j        t          | |fi           }||_        |S )a  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.
        )rR   rS   _ImmutableBase_derived_class)r%   otherrV   s      r    r<   z_TopologyAttrContainer._mix   s+    2 en~sE&BBGG &r"   c           
      V   fd}fd}| j         rLt          | j        t          ||dj                             | j                            j                   dS t          | j        t          ||dj                             | j                            j                   dS )zAdd `attr` into the namespace for this class

        Parameters
        ----------
        attr : A :class:`TopologyAttr` object
        c                 .                         |           S r   )__getitem__)selfattrs    r    getterz0_TopologyAttrContainer._add_prop.<locals>.getter  s    ##D)))r"   c                 0                         | |          S r   )__setitem__)r^   valuesr_   s     r    setterz0_TopologyAttrContainer._add_prop.<locals>.setter  s    ##D&111r"   N)	rF   setattrattrnamepropertygroupdocrU   addsingular	singledoc)r%   r_   r`   rd   s    `  r    	_add_propz _TopologyAttrContainer._add_prop  s    	* 	* 	* 	* 	*	2 	2 	2 	2 	2 = 	6t}==  
 "&&t}55555t~>>  
 "&&t}55555r"   c                    t          j        t                    5  t          | |j                   ddd           n# 1 swxY w Y   t          j        t                    5  t          | |j                   ddd           n# 1 swxY w Y   | j                            |j                   | j                            |j                   dS )zRemove `attr` from the namespace for this class.

        Parameters
        ----------
        attr : A :class:`TopologyAttr` object
        N)
contextlibsuppressAttributeErrordelattrrf   rj   rU   discard)r%   r_   s     r    	_del_propz _TopologyAttrContainer._del_prop*  s.     00 	( 	(C'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 00 	( 	(C'''	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	&&t}555&&t}55555s!   <A A  BB	Bc                    |                     d          sD|| j        v s;t          | |          s+t          d                    | j        rdnd                    t          t          |                               ||           d S )N_z'Cannot set arbitrary attributes to a {}Group	Component)	
startswithrU   hasattrrp   formatrF   superr8   __setattr__)r^   r_   value	__class__s      r    r|   z"_TopologyAttrContainer.__setattr__:  s     OOC  		t...tT"" / !9@@#~>GG;    	$d++77eDDDDDr"   )rS   
__module____qualname____doc__classmethodr9   r<   rl   rs   r|   __classcell__r~   s   @r    r8   r8      s          , , [,\   [8 6 6 [6: 6 6 [6E E E E E E E E Er"   r8   c                   &    e Zd ZdZd Zd ZddZdS )_MutableBasea  
    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.

    c                    	 |d         j         n# t          t          f$ r 	 |d         d         j         n# t          t          t          f$ rp ddl m} |t          |                                          z   D ](}t          ||t          t          f          r	|j          n)d| j
         }t          |          d Y nw xY wY nw xY w	 t                              j        |                    S # t          $ r 	 t          fd|                                 D                       }n\# t"          $ rO d| j
         dt%          t'          j                                                             }t          |          d w xY w|                    |           x}j        | <   t                              |          cY S w xY w)	Nr   r   )UniversezKNo universe, or universe-containing object passed to the initialization of c              3   D   K   | ]}|j         v j         |         V  d S r   )_class_bases).0parentr   s     r    	<genexpr>z'_MutableBase.__new__.<locals>.<genexpr>z  sC       " "// N6*////" "r"   z Attempted to instantiate class 'z\' but none of its parents are known to the universe. Currently possible parent classes are: )universe
IndexErrorrp   	TypeErrorr   tuplerc   
isinstancer:   r;   rS   object__new___classesKeyErrornextmroStopIterationstrsortedr   keysr<   )	r%   argskwargsr   argerrmsg
parent_clsrV   r   s	           @r    r   z_MutableBase.__new__Z  s.   
	6R!AAN+ 	6 	6 	66GAJ'z>: 6 6 6......
  %"8"88 	6 	6C!#)]'KLL L
J;><J J  $F++5 6		6(	*>>!*S/222 	* 	* 	*2! " " " ""%''))" " "  


 ! 2 2 2<s| < < 6!."5"5"7"78899< <   ''T12 (2s';';;FQZ_>>&)))))#	*s[    C7CBB>;C=B>>CC$C- -
F>8-D&%F>&AE??<F>=F>c                    t          |           j        }|t          v rt          |         \  }}}t          |t                    r|}d}n|dz   }d}t          | |          sSt          |t                    rdnd}d}	|j        }
|
dk    r|dz   }
t          |	                    |||
|                    d}	t          |	                    |||	                    |                                	                    d
d          }d                    ||          }	|t          v r&t          |         }|	d                    |          z  }	t          |	          )Nrg   z()methodz0{attr} is a {method} of {clstype}, not {selfcls}r:   rv   )r_   r   clstypeselfclsz;{selfcls}.{attrname} not available; this requires {topattr})r   rf   topattrru    z#{selfcls} has no attribute {attr}. )r   r_   zDid you mean {match}?)match)rR   rS   r   r   rg   rp   rz   r   lowerreplacer   )r^   r_   r   r   methr   rf   attrtypemnameerrclsnamecleanr   s                r    __getattr__z_MutableBase.__getattr__  s   t**%(((%:4%@"GT7$)) $%$;# dG,, &0x&@&@N

hH!*k))%/G$JJ%' ' '	     .  "JJ '(G      JJLL((b11E7>>d ?  C ++++E2.55E5BBB %%%r"   Tc                    t          | j        j        |          }|s|S |rt          j        nt          j        }	 | j        j        n# t          $ r
 | j        Y nw xY wfd|j        j	        D             } ||d          }||         S )a  
        Get bonded connections between atoms as a
        :class:`~MDAnalysis.core.topologyobjects.TopologyGroup`.

        Parameters
        ----------
        typename : str
            group name. One of {"bonds", "angles", "dihedrals",
            "impropers", "ureybradleys", "cmaps"}
        outside : bool (optional)
            Whether to include connections involving atoms outside
            this group.

        Returns
        -------
        TopologyGroup
            containing the bonded group of choice, i.e. bonds, angles,
            dihedrals, impropers, ureybradleys or cmaps.

        .. versionadded:: 1.1.0
        c                 :    g | ]}t          j        |          S r$   )npisin)r   colindicess     r    
<listcomp>z0_MutableBase.get_connections.<locals>.<listcomp>  s%    ???#W%%???r"   r   axis)
getattrr   r   r   anyallix_arrayrp   _bixT)r^   typenameoutsideugroupfuncseenmaskr   s          @r    get_connectionsz_MutableBase.get_connections  s    . ,h77 	M ,rvvbf	$j)GG 	$ 	$ 	$mGGG	$???????tDq!!!d|s   A AAN)T)rS   r   r   r   r   r   r   r$   r"   r    r   r   K  sR         .* .* .*`/& /& /&b! ! ! ! ! !r"   r   c                        e Zd ZdZej        ZdS )rX   zAClass used to shortcut :meth:`__new__` to :meth:`object.__new__`.N)rS   r   r   r   r   r   r$   r"   r    rX   rX     s        KK
 nGGGr"   rX   c                 F     t          j                    fd            }|S )zFRaises deprecation warning if 'pbc' is set and assigns value to 'wrap'c                     |                     dd           2t          j        dt                     |                    d          |d<    | g|R i |S )NpbczbThe 'pbc' kwarg has been deprecated and will be removed in version 3.0., please use 'wrap' insteadwrap)getwarningswarnDeprecationWarningpopgroupr   r   functions      r    wrappedz_pbc_to_wrap.<locals>.wrapped  sl    ::eT"".M, #	   $ZZ..F6Nx///////r"   	functoolswrapsr   r   s   ` r    _pbc_to_wrapr     s:     _X
0 
0 
0 
0 
0 Nr"   c                 F     t          j                    fd            }|S )z?Raises ValueError when both 'wrap' and 'unwrap' are set to Truec                     |                     d          r$|                     d          rt          d           | g|R i |S )Nr   unwrapz/both 'wrap' and 'unwrap' can not be set to true)r   
ValueErrorr   s      r    r   z&check_wrap_and_unwrap.<locals>.wrapped  s[    ::f 	P&**X"6"6 	PNOOOx///////r"   r   r   s   ` r    check_wrap_and_unwrapr     s:     _X0 0 0 0 0
 Nr"   c                 F     t          j                    fd            }|S )Nc           	         t          |t          t          f          sMt          d                    j        t          |           j        t          |          j                            | j        |j        k    r't          d                    j                            | j        |j        urt          d           | |          S )Nz1Can't perform '{}' between objects: '{}' and '{}'z-Can't perform '{}' on different level objectsz1Can't operate on objects from different Universes)
r   r;   r:   r   rz   rS   rR   levelr   r   )r^   rZ   r   s     r    r   z!_only_same_level.<locals>.wrapped  s    %-!;<< 	!!'%JJ'KK(" "   :$$6(+,,   =..C   xe$$$r"   r   r   s   ` r    _only_same_levelr     s8    _X% % % % %* Nr"   c                       e Zd ZdZd Zd Zd Zd Z fdZd Z	d Z
d	 Zd
 Zd Zed             Zd Zd Zd Zd Zed             Zed             Zed             Zed             Zej        d             Ze ed          d                         Ze ed          d                         Ze ed          d                         Ze ed          d                         ZdCdZd  Z dDd!Z!e"e#e$dEd#                                    Z%e"e#e$dEd$                                    Z&e&Z'e"e(j)        d"fd%            Z*e#dDd&            Z+e#dDd'            Z,d( Z-d) Z.dFd+Z/dGd-Z0dHd/Z1dId2Z2dJd4Z3d5 Z4d6 Z5d7 Z6ed8             Z7ed9             Z8ed:             Z9ed;             Z:ed<             Z;ed=             Z<d> Z=ed?             Z>d@ Z?edA             Z@dB ZA xZBS )Kr:   a  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         |
    +-------------------------------+------------+----------------------------+
    c                    	 t          |          dk    r&d |d         D             }|d         d         j        }n|\  }}n'# t          t          f$ r d}t          |          d w xY wt	          j        |t          j                  }|j        dk    rt          d          || _	        || _
        t                      | _        d S )Nr   c                     g | ]	}|j         
S r$   )r   )r   ats     r    r   z&GroupBase.__init__.<locals>.<listcomp>i  s    ...be...r"   r   zCan 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).dtypezGroup index must be 1d)lenr   rp   r   r   asarrayintpndimr   _ix_udict_cache)r^   r   r   r   r   s        r    __init__zGroupBase.__init__e  s    	.4yyA~~..d1g...GAJ' A
 
	. 
	. 
	.
2  F##-
	. Z"'***7Q;;5666ffs   >A $A%c                     t          | j        | j        t          | j                                                  f          S r   )hashr   r~   r   r   tolistr^   s    r    __hash__zGroupBase.__hash__  s/    TWdneDGNN4D4D.E.EFGGGr"   c                 *    t          | j                  S r   )r   r   r   s    r    __len__zGroupBase.__len__  s    47||r"   c                 P   |t          d          t          |t          j                  r+| j                            | j        |         | j                  S t          |t                    r|rt          j
        |          }|                     | j        |         | j                  S )Nz%None cannot be used to index a group.)r   r   numbersIntegralr   rj   r   r   listr   arrayrY   )r^   items     r    r]   zGroupBase.__getitem__  s     <CDDDg.// 	E:&&twt}dmDDD$%% &$ & x~~
 &&twt}dmDDDr"   c                    t          |           j        }|t          v ryt          |         }||j        k    r7||j        k    r,d}t          |                    |||j                            d}t          |                    |j                            t          t          |           
                    |          S )Nz8{selfcls} has no attribute {attr}. Do you mean {plural}?)r   r_   plural5This Universe does not contain {singular} informationrj   )rR   rS   r   rj   rf   rp   rz   r   r{   r:   r   r^   r_   r   r%   r   r~   s        r    r   zGroupBase.__getattr__  s    t**%?""!$'Cs|##(<(<,  %JJwT#,JOO   N!#**cl*"C"CDDDD))55d;;;r"   c           	          | j         j        }d                    |                                t	          |           |dt	          |           dk    d                    S )Nz<{}Group with {} {}{}>sr   )r   namerz   
capitalizer   r^   r  s     r    __repr__zGroupBase.__repr__  sQ    z*11OOs4yy$CIIN4D4D0E
 
 	
r"   c           	         | j         j        }t          |           dk    rBd                    |                                t          t          |                               S d                    |                                t          t          |           d d                   d d         t          t          |           dd                    dd                    S )N
   z<{}Group {}>z<{}Group {}, ..., {}>   r   r   )r   r  r   rz   r	  reprr   r
  s     r    __str__zGroupBase.__str__  s    zt99??!(():):Dd<L<LMMM*11!!T$ZZ^$$SbS)T$ZZ_%%abb)  r"   c                 ,    |                      |          S )a]  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

        )concatenater^   rZ   s     r    __add__zGroupBase.__add__  s     &&&r"   c                     |dk    r |                      | j        | j                  S t          d                    t          |           j        t          |          j                            )a_  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

        r   0unsupported operand type(s) for +: '{}' and '{}')rY   r   r   r   rz   rR   rS   r  s     r    __radd__zGroupBase.__radd__  sd     A::&&tw>>>!!'JJ'e)=" "  r"   c                 ,    |                      |          S r   )
differencer  s     r    __sub__zGroupBase.__sub__  s    u%%%r"   c                 D    |j         }t          j        | j         |          S )a  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.
        )r   r   array_equalr^   rZ   o_ixs      r    __eq__zGroupBase.__eq__  s     x~dgt,,,r"   c                 B    |j         | j         k    sdS |j        | j        v S )NF)r   r   r  s     r    __contains__zGroupBase.__contains__  s'    {dj(( 5x47""r"   c                 ,    |                      |          S r   )unionr  s     r    __or__zGroupBase.__or__  s    zz%   r"   c                 ,    |                      |          S r   )intersectionr  s     r    __and__zGroupBase.__and__  s      '''r"   c                 ,    |                      |          S r   )symmetric_differencer  s     r    __xor__zGroupBase.__xor__  s    ((///r"   c                     | j         S )zaThe underlying :class:`~MDAnalysis.core.universe.Universe` the group
        belongs to.
        r   r   s    r    r   zGroupBase.universe  s    
 wr"   c                     | j         S )a  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.

        r   r   s    r    r   zGroupBase.ix  s     xr"   c                     | j         S )zUnique 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`
        r/  r   s    r    r   zGroupBase.ix_array   s     xr"   c                 ^    | j         j        j        j        }||S |                                S )z@Obtain a copy of the dimensions of the currently loaded Timestep)r   
trajectorytsrM   copy)r^   dimss     r    rM   zGroupBase.dimensions-  s,     }'*5<K99;;r"   c                 2    || j         j        j        _        d S r   )r   r2  r3  rM   )r^   rM   s     r    rM   zGroupBase.dimensions6  s    1; #...r"   sorted_uniquec                 .    |                      d          S )NTr   asuniquer   s    r    r7  zGroupBase.sorted_unique:  s     }}D})))r"   unsorted_uniquec                 .    |                      d          S )NFr9  r:  r   s    r    r<  zGroupBase.unsorted_unique?  s     }}E}***r"   issortedc                 *    t          | j                  S r   )r   r   r   s    r    r>  zGroupBase.issortedD  s     #47+++r"   isuniquec                     t          |           dk    rdS t          | j                  j        d         | j        j        d         k    S )a  Boolean indicating whether all components of the group are unique,
        i.e., the group contains no duplicates.

        Examples
        --------

        .. testsetup:: GroupBase.isunique

            from MDAnalysis.tests.datafiles import PDB, XTC
            import MDAnalysis as mda
            u = mda.Universe(PDB, XTC)

        .. doctest:: GroupBase.isunique

            >>> 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

        See Also
        --------
        asunique


        .. versionadded:: 0.19.0
        r   Tr   )r   r   r   shaper   s    r    r@  zGroupBase.isuniqueI  s?    F t99>>4TW%%+A.$'-2BBBr"   Fc                 x   	 |rdnd}| j         |         S # t          $ r Y nw xY w| j        r+|s| | j         d<   | S | j        r| | j         d<   | | j         d<   | S |rx|r&t	          j        | j        d          \  }}|| _        nt          | j                  }||         }d|j         d<   d|j         d<   ||j         d<   ||j         d<   || j         d<   |S t          | j                  }|r]t	          j
        | j                  }	t          |          D ]-\  }
}t	          j        | j        |k              d         }|
|	|<   .|	| _        t          |          }|rd| j         v r| j        | j         d<   | j        S ||         }d|j         d<   ||j         d<   ||j         d<   || j         d<   |r|| j         d<   ||j         d<   |S )Nr7  r<  T)return_inverser@  r>  r   )r   r   r@  r>  r   uniquer   _unique_restore_maskr   r   
zeros_like	enumeratewherer   r7  )r^   r   r   set_maskr  	unique_ixrestore_mask_uniquer   r   ixrc   r>  s                 r    	_asuniquezGroupBase._asuniquep  s5   	&,C??2CD;t$$ 	 	 	D	 = 	 15-.} 15-./3O, 	 3*,)GD+ + +'	< -9)))$'22	I&G)-GN:&)-GN:&.5GN?+07GN,-+2DK(N(11 	-=))D!'** ! !1$'Q,//2 V(,D%&w// 	&4;66-1-?DK)*%%.%)z"%-z",3())0%& 	6+2DK(.5GN?+s    
""c                    |dk    r| j         j        }n|dk    r| j         j        }n|dk    r.	 | j         j        }n# t          $ r d}t          |          d w xY w|dk    r.	 | j         j        }nW# t
          $ r d}t          |          d w xY w|dk    rt          d          t          d	                    |                    |S )
NrJ   rK   	moleculeszECannot use compound='molecules': No molecule information in topology.	fragmentszACannot use compound='fragments': No bond information in topology.r   z,This method does not accept compound='group'zkUnrecognized compound definition: {}
Please use one of 'residues', 'segments', 'molecules', or 'fragments'.)	r   
resindices
segindicesmolnumsrp   r   fragindicesr   rz   )r^   compoundcompound_indicesr   s       r    _get_compound_indiceszGroupBase._get_compound_indices  s(   z!!#z4###z4$$4#':#5  ! 4 4 4/  "&))t34 $$4#':#9   4 4 4/  "&))t34   KLLL##)6(#3#3  
  s   ; A"A/ /Bc                    |                      |          }t          j        |          }||         }||dk             }t          |          }t          j        t          j        |          dk               }|r5|rt          j        |d          }nt          j        |          }||         }g }	g }
|D ]}|	                    ||k               |r4|
                    |||k                                 d|                     Q|
                    t          j	        ||k              d                             d|                     |
|	t          |          fS )ap  Splits a group's compounds into groups of equal compound size.

        Grouping equal sizes together facilitates subsequent vectorization.

        For a 10-atom molecule with atoms organized into compounds C0 through
        C2::

           at.id:  0  1  2  3  4  5  6  7  8  9
        compound: C0 C0 C0 C0 C1 C1 C2 C2 C2 C2

        this function will yield an `atom_masks` list with two submasks: one
        for compounds of size 2 and one for compounds of size 4:
        [array([[4, 5]]),
         array([[1, 2, 3, 0],
                [8, 7, 6, 9]])]

        (Note that atom order within component submasks may be lost unless a
        `stable_sort` is requested)
        These submasks can be used directly to fancy-index arrays of the same
        length as self (including :class:`AtomGroups<AtomGroup>`).

        This function also returns `compound_masks`, the boolean mapping of
        each of the `atom_masks` submask into the original compound order::
        [array([False,  True, False]),
         array([ True, False,  True])]

        Parameters
        ----------
        compound : {'segments', 'residues', 'molecules', 'fragments'}
            The compound type to base splitting on.
        stable_sort : bool, optional
            Whether to ensure that, when needed, sorting does not affect an
            atom's order within a compound (at a cost to performance). E.g.,
            for an unwrap operation it is important that the first atom of a
            compound is always the same, whereas a center-of-geometry
            computation wouldn't care.

        Returns
        -------
        atom_masks : list of numpy.ndarray
            Integer masks for fancy-indexing atoms/weights lists; masks are
            already shaped as ``(number of compounds of a given size,
            compound_size)``.
        compound_masks : list of numpy.ndarray
            1D boolean masks for fancy-indexing lists of compounds. Translate
            the distribution of the compounds in each mask of `atom_masks` into
            their original order.
        n_compounds : int
            The number of individual compounds.
        r   stablekindr   )rZ  r   bincountr   r   diffargsortappendreshaperI  r   )r^   rX  stable_sortrY  compound_sizessize_per_atomunique_compound_sizesneeds_sortingsort_indicescompound_masks
atom_maskscompound_sizes               r    _split_by_compound_indicesz$GroupBase._split_by_compound_indices  s   t  55h??%566&'78'!(;< -n = = rw'7881<== 		8  <!z*:JJJ  "z*:;;),7M
2 	 	M!!.M"ABBB !! -!?@HHM     !!H]m;<<Q?GGM     >3~+>+>>>r"   r   c           	      J   | j         }t          j        }|                                }|dk    r|r|                    d          }n"|r|                    |dd          }n|j        }t          |          dk    r|S |-|                    |d          }|	                    d          S |                    |d          }t          j
        d	||dddf                   |                                z  S |                     |          \  }	}
}|r|                    |dd          }n|j        }||                    |d          }n|                    |d          }t          j        |d
f|          }t          |
|	          D ]y\  }}||         }||	                    d          }nN||         }t          j
        d||dddddf                   }||                    d          dddf         z  }|||<   z|rt          j        ||j                  }|S )a  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.
        wrap : bool, optional
            If ``True`` and `compound` is ``'group'``, move all atoms to the
            primary unit cell before calculation.
            If ``True`` and `compound` is not ``'group'`` 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. Default [``False``].
        unwrap : bool, optional
            If ``True``, compounds will be unwrapped before computing their
             centers.
        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'``.
        ValueError
            If both 'wrap' and 'unwrap' set to true.
        ~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`:

        .. testsetup:: GroupBase.center

            from MDAnalysis.tests.datafiles import PDB, XTC
            import MDAnalysis as mda
            u = mda.Universe(PSF, DCD)

        .. doctest:: GroupBase.center

            >>> sel = u.select_atoms('prop mass > 4.0')
            >>> sel.center(sel.charges)
            array([-0.22925091, -0.04771193, -0.16728489])

        To find the centers of mass per residue of all CA :class:`Atoms<Atom>`:

        .. doctest:: GroupBase.center
           :options: +NORMALIZE_WHITESPACE

            >>> sel = u.select_atoms('name CA')
            >>> sel.center(sel.masses, compound='residues')
            array([[ 11.66462231,   8.39347267,  -8.98323059],
                  [ 11.41483879,   5.43442154,  -6.51348448],
                  [  8.95975494,   5.61292315,  -3.61323047],
                  [  8.29006767,   3.07599092,  -0.79665166],
                  [  5.01112604,   3.76389837,   1.130355  ],
                  ...


        .. versionchanged:: 0.19.0 Added `compound` parameter
        .. versionchanged:: 0.20.0 Added ``'molecules'`` and ``'fragments'``
            compounds
        .. versionchanged:: 0.20.0 Added `unwrap` parameter
        .. versionchanged:: 1.0.0 Removed flags affecting default behaviour
        .. versionchanged::
           2.1.0 Renamed `pbc` kwarg to `wrap`. `pbc` is still accepted but
           is deprecated and will be removed in version 3.0.
        r   FinplaceN)rX  	referencerp  r   r4  r   ij,ij->jr  r   r   ijk,ijk->ik)r   r   float64r   pack_into_boxr   rL   r   astypemeaneinsumsumrm  emptyzipr   	apply_PBCrM   )r^   weightsr   r   rX  r   r   compcoordsrk  rj  n_compoundscenterscompound_mask	atom_mask_coords_centers_weightss                     r    centerzGroupBase.center*  sh   H 
 
~~7?? ),,U,;; )!T5 &   5zzQu599{{{***nnUn77G	*fgaaag.>??'++--O ++D11 	2^[
  	%\\44\OOFF_F?]]5u]55FFnnUn77G (K+5999(+NJ(G(G 
	. 
	.$M9Y'G"<<Q<//"9-9!7HQQQ4Z,@  HLLaL00D99%-GM"" 	E)'53CDDGr"   c                 4    |                      d|||          S )a	  Center of geometry of (compounds of) the group

        .. math::
            \boldsymbol R = \frac{\sum_i \boldsymbol r_i}{\sum_i 1}

        where :math:`\boldsymbol r_i` of :class:`Atoms<Atom>` :math:`i`.
        Centers of geometry per :class:`Residue` or per :class:`Segment` can
        be obtained by setting the `compound` parameter accordingly.

        Parameters
        ----------
        wrap : bool, 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. Default False.
        unwrap : bool, optional
            If ``True``, compounds will be unwrapped before computing their
            centers.
        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.


        .. versionchanged:: 0.8 Added `pbc` keyword
        .. versionchanged:: 0.19.0 Added `compound` parameter
        .. versionchanged:: 0.20.0 Added ``'molecules'`` and ``'fragments'``
            compounds
        .. versionchanged:: 0.20.0 Added `unwrap` parameter
        .. versionchanged:: 1.0.0 Removed flags affecting default behaviour
        .. versionchanged::
           2.1.0 Renamed `pbc` kwarg to `wrap`. `pbc` is still accepted but
           is deprecated and will be removed in version 3.0.
        N)r   rX  r   )r  )r^   r   r   rX  s       r    center_of_geometryzGroupBase.center_of_geometry  s    n {{4dXf{MMMr"   c                    | j         }t          |t                    rt          ||          }nqt	          j        |          }t          |          t          |          k    r=t          d                    t          |          t          |                              |	                                }|dk    r ||d          S | 
                    |          \  }}}	t          |j        dd                   }
t	          j        |	g|
z             }t          ||          D ]\  }}||         } ||d          }|||<    |S )aa  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`:

        .. testsetup:: GroupBase.center

            from MDAnalysis.tests.datafiles import PSF, DCD
            import MDAnalysis as mda
            u = mda.Universe(PSF, DCD)

        .. doctest:: GroupBase.center

            >>> sel = u.select_atoms('prop mass > 4.0')
            >>> sel.accumulate('charges')
            -251.68500316143036

        To find the total mass per residue of all CA :class:`Atoms<Atom>`:

        .. doctest:: GroupBase.center
           :options: +NORMALIZE_WHITESPACE

            >>> sel = u.select_atoms('name CA')
            >>> sel.accumulate('masses', compound='residues')
            array([12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011,
                   12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011,
                   12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011,
                   12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011,
                   12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011, 12.011,
                   ...

        To find the maximum atomic charge per fragment of a given
        :class:`AtomGroup`:

        .. doctest:: GroupBase.center

            >>> import numpy as np
            >>> sel.accumulate('charges', compound="fragments", function=np.max)
            array([0.20999999])


        .. versionadded:: 0.20.0
        zQThe input array length ({}) does not match the number of atoms ({}) in the group.r   r   r   r   N)r   r   r   r   r   r   r   r   rz   r   rm  r   rB  r{  r|  )r^   	attributer   rX  r   attribute_valuesr  rk  rj  r  higher_dimsaccumulationr  r  	_elements_accumulations                   r    
accumulatezGroupBase.accumulate	  sa   L 
i%% 		&ui88!z)44#$$E

22 vc"233SZZ@@   ~~7??8,15555 ++D11 	2^[ +1!""566 x ;<<(+NJ(G(G 	8 	8$M9(3I$HYQ777M*7L''r"   c                     | j         }|r|                    d          }n|j        }t          j        |                    d          |                    d          g          S )ap  Return the bounding box of the selection.

        The lengths A,B,C of the orthorhombic enclosing box are ::

          L = AtomGroup.bbox()
          A,B,C = L[1] - L[0]

        Parameters
        ----------
        wrap : bool, optional
            If ``True``, move all :class:`Atoms<Atom>` to the primary unit cell
            before calculation. [``False``]

        Returns
        -------
         corners : numpy.ndarray
            2x3 array giving corners of bounding box as
            ``[[xmin, ymin, zmin], [xmax, ymax, zmax]]``.


        .. versionadded:: 0.7.2
        .. versionchanged:: 0.8 Added *pbc* keyword
        .. versionchanged:: 1.0.0 Removed flags affecting default behaviour
        .. versionchanged::
           2.1.0 Renamed `pbc` kwarg to `wrap`. `pbc` is still accepted but
           is deprecated and will be removed in version 3.0.
        Fro  r   r   )r   rv  rL   r   r   minmax)r^   r   	atomgrouprO  s       r    bboxzGroupBase.bbox  s`    < J	 	$'''66AA#AxA16777r"   c           
      X   | j         j        }|r-|                    d          }|                    d          }n|j        }|                    d          }t          j        t          j        t          j        t          j	        ||z
            d                              }||fS )a  Return the bounding sphere of the selection.

        The sphere is calculated relative to the
        :meth:`center of geometry<center_of_geometry>`.

        Parameters
        ----------
        wrap : bool, optional
            If ``True``, move all atoms to the primary unit cell before
            calculation. [``False``]

        Returns
        -------
        R : float
            Radius of the bounding sphere.
        center : numpy.ndarray
            Coordinates of the sphere center as ``[xcen, ycen, zcen]``.


        .. versionadded:: 0.7.3
        .. versionchanged:: 0.8 Added *pbc* keyword
        .. versionchanged::
           2.1.0 Renamed `pbc` kwarg to `wrap`. `pbc` is still accepted but
           is deprecated and will be removed in version 3.0.
        Fro  Tr   r   r   )
r   r<  rv  r  rL   r   sqrtr  rz  square)r^   r   r  rO  centroidRs         r    bspherezGroupBase.bsphere  s    6 J.	 	@'''66A 333>>HH#A 333??HGBF26")AL"9"9BBBCCDD({r"   c                     t          j        |          }|ddddf         }|dddf         }|                     |g d                              |          S )a  Apply homogenous transformation matrix `M` to the coordinates.

        :class:`Atom` coordinates are rotated and translated in-place.

        Parameters
        ----------
        M : array_like
            4x4 matrix with the rotation in ``R = M[:3, :3]`` and the
            translation in ``t = M[:3, 3]``.

        Returns
        -------
        self

        See Also
        --------
        MDAnalysis.lib.transformations : module of all coordinate transforms

        Notes
        -----
        The rotation :math:`\mathsf{R}` is about the origin and is applied
        before the translation :math:`\mathbf{t}`:

        .. math::

           \mathbf{x}' = \mathsf{R}\mathbf{x} + \mathbf{t}

        Nr  r   r   r   )r   r   rotate	translate)r^   Mr  ts       r    	transformzGroupBase.transform  s]    : JqMMbqb"1"fIbqb!eH{{1iii((221555r"   c                     | j         j        }t          j        |          }|j        j        j        j        |j        xx         |z  cc<   | S )a  Apply translation vector `t` to the selection's coordinates.

        :class:`Atom` coordinates are translated in-place.

        Parameters
        ----------
        t : array_like
            vector to translate coordinates with

        Returns
        -------
        self

        See Also
        --------
        MDAnalysis.lib.transformations : module of all coordinate transforms

        Notes
        -----
        The method applies a translation to the :class:`AtomGroup`
        from current coordinates :math:`\mathbf{x}` to new coordinates
        :math:`\mathbf{x}'`:

        .. math::

            \mathbf{x}' = \mathbf{x} + \mathbf{t}

        )	r   r<  r   r   r   r2  r3  rL   r   )r^   r  r  vectors       r    r  zGroupBase.translate  sK    : J.	A%(293DEEEOEEEr"   r  c                    t          j        |          }t          j        |          }| j        j        }t	          t          j        |                    }|r|                    |            |j        j        j	        j
        }|j        }t          j        ||         |j                  ||<   |r|                    |           | S )a  Apply a rotation matrix `R` to the selection's coordinates.
        :math:`\mathsf{R}` is a 3x3 orthogonal matrix that transforms a vector
        :math:`\mathbf{x} \rightarrow \mathbf{x}'`:

        .. math::

            \mathbf{x}' = \mathsf{R}\mathbf{x}

        :class:`Atom` coordinates are rotated in-place.

        Parameters
        ----------
        R : array_like
            3x3 rotation matrix
        point : array_like, optional
            Center of rotation

        Returns
        -------
        self

        Notes
        -----
        By default, rotates about the origin ``point=(0, 0, 0)``. To rotate
        a group ``g`` around its center of geometry, use
        ``g.rotate(R, point=g.center_of_geometry())``.

        See Also
        --------
        rotateby : rotate around given axis and angle
        MDAnalysis.lib.transformations : module of all coordinate transforms

        )r   r   r   r<  rT   count_nonzeror  r   r2  r3  rL   r   dotr   )r^   r  pointr  require_translationrO  idxs          r    r  zGroupBase.rotate%  s    D JqMM
5!! J.	"2#3E#:#:;; 	('''),6#$$# 	'&&&r"   Nc                     t          j        |          }t          j        |          }||                                 }t          j        |          }t	          j        |||          }|                     |          S )a  Apply a rotation to the selection's coordinates.

        Parameters
        ----------
        angle : float
            Rotation angle in degrees.
        axis : array_like
            Rotation axis vector.
        point : array_like, optional
            Center of rotation. If ``None`` then the center of geometry of this
            group is used.

        Returns
        -------
        self

        Notes
        -----
        The transformation from current coordinates :math:`\mathbf{x}`
        to new coordinates :math:`\mathbf{x}'` is

        .. math::

          \mathbf{x}' = \mathsf{R}\,(\mathbf{x}-\mathbf{p}) + \mathbf{p}

        where :math:`\mathsf{R}` is the rotation by `angle` around the
        `axis` going through `point` :math:`\mathbf{p}`.

        See Also
        --------
        MDAnalysis.lib.transformations.rotation_matrix :
            calculate :math:`\mathsf{R}`

        N)r  )r   radiansr   r  r   rotation_matrixr  )r^   angler   r  alphar  s         r    rotatebyzGroupBase.rotatebyW  sq    F 
5!!z$=++--E
5!!+E4uEEE~~a   r"   Tc                 0    |                      ||          S )a  Shift all :class:`Atoms<Atom>` in this group to the primary unit
        cell.

        Parameters
        ----------
        box : array_like
            Box dimensions, can be either orthogonal or triclinic information.
            Cell dimensions must be in an identical to format to those returned
            by :attr:`MDAnalysis.coordinates.timestep.Timestep.dimensions`,
            ``[lx, ly, lz, alpha, beta, gamma]``. If ``None``, uses these
            timestep dimensions.
        inplace : bool
            ``True`` to change coordinates in place.

        Returns
        -------
        coords : numpy.ndarray
            Shifted atom coordinates.

        Notes
        -----
        All atoms will be moved so that they lie between 0 and boxlength
        :math:`L_i` in all dimensions, i.e. the lower left corner of the
        simulation box is taken to be at (0,0,0):

        .. math::

           x_i' = x_i - \left\lfloor\frac{x_i}{L_i}\right\rfloor

        The default is to take unit cell information from the underlying
        :class:`~MDAnalysis.coordinates.timestep.Timestep` instance. The optional
        argument `box` can be used to provide alternative unit cell information
        (in the MDAnalysis standard format
        ``[Lx, Ly, Lz, alpha, beta, gamma]``).

        Works with either orthogonal or triclinic box types.

        .. note::
           :meth:`pack_into_box` is identical to :meth:`wrap` with all default
           keywords.

        .. note::
            :meth:`AtomGroup.pack_into_box` is currently faster than
            :meth:`ResidueGroup.pack_into_box` or
            :meth:`SegmentGroup.pack_into_box`.


        .. versionadded:: 0.8
        )boxrp  r  )r^   r  rp  s      r    rv  zGroupBase.pack_into_box  s    d yyS'y222r"   r   comc                    || j         }|t          d          nRt          j        |t          j                  }t          j        |dk              r|j        dk    rt          d          | j        }| j        s|j	        }|j
        }|}|                                }|dvr"t          d                    |                    t          |          d	k    r t          j        d
t          j                  S |dk    st          |          dk    rt          j        |j        |          }	n|                                }
|
dk    r*t%          | j        j        d          st+          d          n(|
dk    r"t          d                    |                    |j        }	|
dk    rk|                    d|          }t          j        t          j        |                    r-|dk    rdnd}t          d                    ||                    n|                    d|          }|                    t          j        d          }t          j        ||          }||z
  }|dk    r|	|z  }	n^|                    |          }t9          |          }d	}|D ]5}t          j        ||k              }|	|xx         ||         z  cc<   |dz  }6|r|	|_        | j        s|	|         }	|	S )a/  Shift the contents of this group back into the primary unit cell
        according to periodic boundary conditions.

        Specifying a `compound` will keep the :class:`Atoms<Atom>` in each
        compound together during the process. If `compound` is different from
        ``'atoms'``, each compound as a whole will be shifted so that its
        `center` lies within the primary unit cell.

        Parameters
        ----------
        compound : {'atoms', 'group', 'segments', 'residues', 'molecules', \
                    'fragments'}, optional
            Which type of compound to keep together during wrapping. Note that,
            in any case, *only* the positions of :class:`Atoms<Atom>`
            *belonging to the group* will be taken into account.
        center : {'com', 'cog'}
            How to define the center of a given group of atoms. If `compound` is
            ``'atoms'``, this parameter is meaningless and therefore ignored.
        box : array_like, optional
            The unitcell dimensions of the system, which can be orthogonal or
            triclinic and must be provided in the same format as returned by
            :attr:`MDAnalysis.coordinates.timestep.Timestep.dimensions`:
            ``[lx, ly, lz, alpha, beta, gamma]``.
            If ``None``, uses the
            dimensions of the current time step.
        inplace: bool, optional
            If ``True``, coordinates will be changed in place.

        Returns
        -------
        numpy.ndarray
            Array of wrapped atom coordinates of dtype `np.float32` and shape
            ``(len(self.atoms.n_atoms), 3)``

        Raises
        ------
        ValueError
            If `compound` is not one of ``'atoms'``, ``'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 or if
            `center` is ``'com'`` but the topology doesn't contain masses.

        Notes
        -----
        All atoms of the group will be moved so that the centers of its
        compounds lie within the primary periodic image. For orthorhombic unit
        cells, the primary periodic image is defined as the half-open interval
        :math:`[0,L_i)` between :math:`0` and boxlength :math:`L_i` in all
        dimensions :math:`i\in\{x,y,z\}`, i.e., the origin of the of the
        simulation box is taken to be at the origin :math:`(0,0,0)` of the
        euclidian coordinate system. A compound center residing at position
        :math:`x_i` in dimension :math:`i` will be shifted to :math:`x_i'`
        according to

        .. math::

           x_i' = x_i - \left\lfloor\frac{x_i}{L_i}\right\rfloor\,.

        When specifying a `compound`, the translation is calculated based on
        each compound. The same translation is applied to all atoms
        within this compound, meaning it will not be broken by the shift.
        This might however mean that not all atoms of a compound will be
        inside the unit cell after wrapping, but rather will be the center of
        the compound.
        Be aware of the fact that only atoms *belonging to the group* will be
        taken into account!

        `center` allows to define how the center of each group is computed.
        This can be either ``'com'`` for center of mass, or ``'cog'`` for
        center of geometry.


        `box` allows a unit cell to be given for the transformation. If not
        specified, the :attr:`~MDAnalysis.coordinates.timestep.Timestep.dimensions`
        information from the current
        :class:`~MDAnalysis.coordinates.timestep.Timestep` will be used.

        .. note::
            :meth:`AtomGroup.wrap` is currently faster than
            :meth:`ResidueGroup.wrap` or :meth:`SegmentGroup.wrap`.

        See Also
        --------
        :meth:`pack_into_box`
        :meth:`unwrap`
        :meth:`MDAnalysis.lib.distances.apply_PBC`


        .. versionadded:: 0.9.2
        .. versionchanged:: 0.20.0
           The method only acts on atoms *belonging to the group* and returns
           the wrapped positions as a :class:`numpy.ndarray`.
           Added optional argument `inplace`.
        NzhNo dimensions information in Universe.  Either use the 'box' argument or set the '.dimensions' attributer           )   zInvalid box: Box has invalid shape or not all box dimensions are positive. You can specify a valid box using the 'box' argument.)r   r   rK   rJ   rR  rS  zUnrecognized compound definition '{}'. Please use one of 'atoms', 'group', 'segments', 'residues', 'molecules', or 'fragments'.r   )r   r  r   r   r  massesz<Cannot perform wrap with center='com', this requires masses.cogzFUnrecognized center definition '{}'. Please use one of 'com' or 'cog'.F)r   rX  r   thez
one of thezQCannot use compound='{0}' with center='com' because {1} {0}'s total mass is zero.rr  )rM   r   r   r   float32r   rB  r   r@  r<  rF  r   rz   r   zerosr   r}  rL   ry   r   	_topologyr   center_of_massr   isnanr  rw  rZ  r   rI  )r^   rX  r  r  rp  r   _atomsrL  r  rL   ctrctrpos	specifiertargetshiftsrY  unique_compound_indices	shift_idxrN  r   s                       r    r   zGroupBase.wrap  sE   F ;/C{ 7    *S
333C6#)$$ 	T(9(9 :   
} 	*F 5LE~~ 
 
 
  6(##	   u::??8F"*55557??c%jjAoo!+EOSAAII,,..Ce|| tw0(;; %0  
  117   I e||--54-HH6"(6**++ )-lI$((.tY(?(?   11ut1LL]]2:E]::F(55Ff_FwV#		 $)#>#>t#D#D  +88H*I*I'	0 # #A8$4$9::DdOOOvi'88OOONII 	('EO} 	0!,/Ir"   rS  c           
         | j         }t          |d          st          | j        j         d          |j        }|X	 |                                }|dvrt          n7# t          t          f$ r# t          d	                    |                    w xY w|dk    rt          |d          st          d          |                                }|d	k    rt          j        |d
          }|t          |          dk    r|dk    re|j        }|                                }	t          j        |	d          rt          d          t          j        d||dddf                   }
|
|	z  }
n|                    d          }
|
                    t          j        d
          }
t+          j        |
| j                  }|||
z
  z  }n|                    ||du           d         }|j        }|D ]Y}|D ]!}t          j        ||         d
          ||<   "|/|dk    r|j        |         }|                    d          }	t          j        t          j        |	d                    r"t          d	                    |                    t          j        d||         |dddddf                   }
|
|	dddf         z  }
n||                             d          }
|
                    t          j        d
          }
t+          j        |
| j                  }||xx         |dddddf         |
dddddf         z
  z  cc<   [|r||_        |j        s||j                 }|S )a  Move atoms of this group so that bonds within the
        group's compounds aren't split across periodic boundaries.

        This function is most useful when atoms have been packed into the
        primary unit cell, causing breaks mid-molecule, with the molecule then
        appearing on either side of the unit cell. This is problematic for
        operations such as calculating the center of mass of the molecule. ::

           +-----------+       +-----------+
           |           |       |           |
           | 6       3 |       |         3 | 6
           | !       ! |       |         ! | !
           |-5-8   1-2-|  ==>  |       1-2-|-5-8
           | !       ! |       |         ! | !
           | 7       4 |       |         4 | 7
           |           |       |           |
           +-----------+       +-----------+

        Parameters
        ----------
        compound : {'group', 'segments', 'residues', 'molecules', \
                    'fragments'}, optional
            Which type of compound to unwrap. Note that, in any case, all
            atoms within each compound must be interconnected by bonds, i.e.,
            compounds must correspond to (parts of) molecules.
        reference : {'com', 'cog', None}, optional
            If ``'com'`` (center of mass) or ``'cog'`` (center of geometry), the
            unwrapped compounds will be shifted so that their individual
            reference point lies within the primary unit cell.
            If ``None``, no such shift is performed.
        inplace : bool, optional
            If ``True``, coordinates are modified in place.

        Returns
        -------
        coords : numpy.ndarray
            Unwrapped atom coordinate array of shape ``(n, 3)``.

        Raises
        ------
        NoDataError
            If `compound` is ``'molecules'`` but the underlying topology does
            not contain molecule information, or if `reference` is ``'com'``
            but the topology does not contain masses.
        ValueError
            If `reference` is not one of ``'com'``, ``'cog'``, or ``None``, or
            if `reference` is ``'com'`` and the total mass of any `compound` is
            zero.

        Note
        ----
        Be aware of the fact that only atoms *belonging to the group* will
        be unwrapped! If you want entire molecules to be unwrapped, make sure
        that all atoms of these molecules are part of the group.
        An AtomGroup containing all atoms of all fragments in the group ``ag``
        can be created with::

          all_frag_atoms = sum(ag.fragments)


        See Also
        --------
        :func:`~MDAnalysis.lib.mdamath.make_whole`,
        :meth:`wrap`,
        :meth:`pack_into_box`,
        :func:`~MDanalysis.lib.distances.apply_PBC`


        .. versionadded:: 0.20.0
        bondsz.unwrap() not available; this AtomGroup lacks defined bonds. To resolve this, you can either:
1. Guess the bonds at universe creation using `guess_bonds = True`, or
2. Create a universe using a topology format where bonds are pre-defined.N)r  r  zEUnrecognized reference '{}'. Please use one of 'com', 'cog', or None.r  r  zACannot perform unwrap with reference='com', this requires masses.r   Fro  r   r  zWCannot perform unwrap with reference='com' because the total mass of the group is zero.rs  r   rr  )rd  r   zdCannot perform unwrap with reference='com' because the total mass of at least one of the {} is zero.rt  )r   ry   r   r~   rS   r<  r   r   rp   rz   r   
make_wholer   r  rz  r   isclosery  rx  rw  r  r   r}  rM   rm  rL   r   r@  rF  )r^   rX  rq  rp  r   unique_atomsr  rL   r  
total_massrefposr  rk  r  r   s                  r    r   zGroupBase.unwrap|  s   N 
ug&& 	>* \ \ \   ,  %OO--	N22$$ 3"J/    006y0A0A   glH&E&E(   ~~ 7??*<GGGI$Y!););%%)0F!'Jz*c22 (9  
  Yz9fQQQWoNNFj(FF&^^^33Frz>>",VT_EEVf_,	 &@@)t"3 A  J %.I'  	%  D&-&8$T*E' ' 'IdOO ( E))!-!4Y!?%+ZZQZ%7%7
6"*Z"="=>> ",!2 39&,,	# #  "$)%i0"111aaa:." "
 *QQQW"55!*9!5!:!:!:!B!B#]]2:E]BBF&0IIFi(((qqq$z*VAAAtQQQJ-??(((  	/%.L"~ 	>!%"<=Is   A 4Bc                 D    | dd         }|                     |            |S )zTGet another group identical to this one.


        .. versionadded:: 0.19.0
        N)_set_unique_caches_fromr^   r   s     r    r4  zGroupBase.copy+  s*     QQQ%%d+++r"   c                 "   	 |j         d         | j         d<   | j        r
| | j         d<   n# t          $ r Y nw xY w	 |j         d         | j         d<   | j        r&| j                             d          r| | j         d<   d S d S d S # t          $ r Y d S w xY w)Nr@  r<  r>  r7  )r   r@  r   r>  r   r  s     r    r  z!GroupBase._set_unique_caches_from5  s    	6&+l:&>DK
# } 615-.	  	 	 	D		8&+l:&>DK
# } 8;??:.. 837DK0008 88 8	  	 	 	DD	s   ) 
66B   
BBc                      t                      }t          |t          t          f          rX|}t          |t                    r|                    d          }t           |           fdt                    D             S |d         }t           |          t                    D ]O}t          |          dk    r |k             ||<   % |k                                 |dd                   ||<   Pt          j
        |          S )a  Group together items in this group according to values of *topattr*

        Parameters
        ----------
        topattrs: str or list
           One or more topology attributes to group components by.
           Single arguments are passed as a string. Multiple arguments
           are passed as a list.

        Returns
        -------
        dict
            Unique values of the multiple combinations of topology attributes
            as keys, Groups as values.

        Example
        -------
        To group atoms with the same mass together:

        .. testsetup:: GroupBase.groupby

            from MDAnalysis.tests.datafiles import PSF, DCD
            import MDAnalysis as mda
            u = mda.Universe(PSF, DCD)
            ag = u.atoms

        .. doctest:: GroupBase.groupby
           :options: +NORMALIZE_WHITESPACE

            >>> ag.groupby('masses')
            {32.06: <AtomGroup with 7 atoms>,
             1.008: <AtomGroup with 1685 atoms>,
             12.011: <AtomGroup with 1040 atoms>,
             14.007: <AtomGroup with 289 atoms>,
             15.999: <AtomGroup with 320 atoms>}

        To group atoms with the same residue name and mass together:

        .. doctest:: GroupBase.groupby
           :options: +NORMALIZE_WHITESPACE

            >>> group_dict = ag.groupby(['resnames', 'masses'])
            >>> dict(sorted(group_dict.items()))
            {('ALA', 1.008): <AtomGroup with 95 atoms>,
             ('ALA', 12.011): <AtomGroup with 57 atoms>,
             ('ALA', 14.007): <AtomGroup with 19 atoms>,
             ('ALA', 15.999): <AtomGroup with 19 atoms>,
             ('ARG', 1.008): <AtomGroup with 169 atoms>,
             ...

        .. doctest:: GroupBase.groupby

            >>> ag.groupby(['resnames', 'masses'])['ALA', 15.999]
            <AtomGroup with 19 atoms>


        .. versionadded:: 0.16.0
        .. versionchanged:: 0.18.0 The function accepts multiple attributes
        zutf-8c                 *    i | ]}||k             S r$   r$   )r   rN  r^   tas     r    
<dictcomp>z%GroupBase.groupby.<locals>.<dictcomp>  s#    666AtB!G}666r"   r   r   N)r   r   r   bytesdecoder   setr   groupbyr	   flatten_dict)r^   topattrsresr_   rN  r  s   `    @r    r  zGroupBase.groupbyH  s   z ffhe-- 	*D(E** 0w//t$$B66666c"gg6666 A;Dt$$BWW A Ax==A%%!"']CFF!"']228ABB<@@CFF$S)))r"   c                 x    |j         }|                     t          j        | j        |g          | j                  S )a  Concatenate with another Group or Component of the same level.

        Duplicate entries and original order is preserved. It is synomymous to
        the `+` operator.

        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

        Example
        -------
        The order of the original contents (including duplicates)
        are preserved when performing a concatenation.

        .. testsetup:: GroupBase.concatenate

            from MDAnalysis.tests.datafiles import PDB, XTC
            import MDAnalysis as mda
            u = mda.Universe(PDB, XTC)

        .. doctest:: GroupBase.concatenate

            >>> ag1 = u.select_atoms('name O')
            >>> ag2 = u.select_atoms('name N')
            >>> ag3 = ag1 + ag2  # or ag1.concatenate(ag2)
            >>> ag3[:3].names
            array(['O', 'O', 'O'], dtype=object)
            >>> ag3[-3:].names
            array(['N', 'N', 'N'], dtype=object)


        .. versionadded:: 0.16.0
        )r   rY   r   r  r   r   r  s      r    r  zGroupBase.concatenate  s;    R ~""NDGT?++T]
 
 	
r"   c                 v    |j         }|                     t          j        | j        |          | j                  S )a  Group of elements either in this Group or another

        On the contrary to concatenation, this method sort the elements and
        removes duplicate ones. It is synomymous to the `|` operator.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with the combined elements of `self` and `other`, without
            duplicate elements

        Example
        -------
        In contrast to :meth:`concatenate`, any duplicates are dropped
        and the result is sorted.

        .. testsetup:: GroupBase.union

            from MDAnalysis.tests.datafiles import PDB, XTC
            import MDAnalysis as mda
            u = mda.Universe(PDB, XTC)

        .. doctest:: GroupBase.union

            >>> ag1 = u.select_atoms('name O')
            >>> ag2 = u.select_atoms('name N')
            >>> ag3 = ag1 | ag2  # or ag1.union(ag2)
            >>> ag3[:3].names
            array(['N', 'O', 'N'], dtype=object)

        See Also
        --------
        concatenate, intersection


        .. versionadded:: 0.16
        )r   rY   r   union1dr   r   r  s      r    r$  zGroupBase.union  s2    X ~""2:dgt#<#<dmLLLr"   c                 v    |j         }|                     t          j        | j        |          | j                  S )a  Group of elements which are in both this Group and another

        This method removes duplicate elements and sorts the result. It is
        synomymous to the `&` operator.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with the common elements of `self` and `other`, without
            duplicate elements

        Example
        -------
        Intersections can be used when the select atoms string would
        become too complicated.  For example to find the water atoms
        which are within 4.0A of two segments:

        .. code-block:: python

            >>> shell1 = u.select_atoms('resname SOL and around 4.0 segid 1')
            >>> shell2 = u.select_atoms('resname SOL and around 4.0 segid 2')
            >>> common = shell1 & shell2  # or shell1.intersection(shell2)

        See Also
        --------
        union


        .. versionadded:: 0.16
        )r   rY   r   intersect1dr   r   r  s      r    r'  zGroupBase.intersection  s9    J ~""N47D))4=
 
 	
r"   c                 V    |j         }t          j        | j        |          }| |          S )a   Group with elements from this Group that don't appear in other

        The original order of this group is kept, as well as any duplicate
        elements. If an element of this Group is duplicated and appears in
        the other Group or Component, then all the occurences of that element
        are removed from the returned Group.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with the elements of `self` that are not in  `other`,
            conserves order and duplicates.

        Example
        -------
        Unlike :meth:`difference` this method will not sort or remove
        duplicates.

        .. testsetup:: GroupBase.subtract

            import MDAnalysis as mda
            from MDAnalysis.tests.datafiles import PSF, DCD
            u = mda.Universe(PSF,DCD)

        .. doctest:: GroupBase.subtract

            >>> ag1 = u.atoms[[3, 3, 2, 2, 1, 1]]
            >>> ag2 = u.atoms[2]
            >>> ag3 = ag1.subtract(ag2)
            >>> ag3.indices
            array([3, 3, 1, 1])

        See Also
        --------
        concatenate, difference


        .. versionadded:: 0.16
        )r   r   r   r   )r^   rZ   r  in_others       r    subtractzGroupBase.subtract!	  s+    \ ~747D))XIr"   c                 v    |j         }|                     t          j        | j        |          | j                  S )a  Elements from this Group that do not appear in another

        This method removes duplicate elements and sorts the result. As such,
        it is different from :meth:`subtract`. :meth:`difference` is synomymous
        to the `-` operator.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with the elements of `self` that are not in  `other`, without
            duplicate elements

        See Also
        --------
        subtract, symmetric_difference


        .. versionadded:: 0.16
        )r   rY   r   	setdiff1dr   r   r  s      r    r  zGroupBase.differenceS	  s1    4 ~""2<$#?#?IIIr"   c                 v    |j         }|                     t          j        | j        |          | j                  S )a  Group of elements which are only in one of this Group or another

        This method removes duplicate elements and the result is sorted. It is
        synomym to the `^` operator.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with the elements that are in `self` or in `other` but not in
            both, without duplicate elements

        Example
        -------

        .. testsetup:: GroupBase.symmetric_difference

            from MDAnalysis.tests.datafiles import PSF, DCD
            import MDAnalysis as mda
            u = mda.Universe(PSF, DCD)

        .. doctest:: GroupBase.symmetric_difference

            >>> ag1 = u.atoms[[0, 1, 5, 3, 3, 2]]
            >>> ag2 = u.atoms[[4, 4, 6, 2, 3, 5]]
            >>> ag3 = ag1 ^ ag2  # or ag1.symmetric_difference(ag2)
            >>> ag3.indices  # 0 and 1 are only in ag1, 4 and 6 are only in ag2
            array([0, 1, 4, 6])

        See Also
        --------
        difference


        .. versionadded:: 0.16
        )r   rY   r   setxor1dr   r   r  s      r    r*  zGroupBase.symmetric_differencep	  s2    T ~""2;tx#>#>HHHr"   c                 N    t          |                     |                    dk    S )ag  If the Group has no elements in common with the other Group

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        bool
            ``True`` if the two Groups do not have common elements


        .. versionadded:: 0.16
        r   )r   r'  r  s     r    
isdisjointzGroupBase.isdisjoint	  s%      4$$U++,,11r"   c                 |    t          |j                  }t          | j                  }|                    |          S )a  If all elements of this Group are part of another Group

        Note that an empty group is a subset of any group of the same level.

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        bool
            ``True`` if this Group is a subset of the other one


        .. versionadded:: 0.16
        )r  r   r   issubsetr^   rZ   r  s_ixs       r    r  zGroupBase.issubset	  s2    & 5>""47||}}T"""r"   c                 :    |                      |          o| |k     S )al  If this Group is a subset of another Group but not identical

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        bool
            ``True`` if this Group is a strict subset of the other one


        .. versionadded:: 0.16
        )r  r  s     r    is_strict_subsetzGroupBase.is_strict_subset	  s"      }}U##9DEM(99r"   c                 |    t          |j                  }t          | j                  }|                    |          S )a`  If all elements of another Group are part of this Group

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        bool
            ``True`` if this Group is a subset of the other one


        .. versionadded:: 0.16
        )r  r   r   
issupersetr  s       r    r  zGroupBase.issuperset	  s2    " 5>""47||t$$$r"   c                 :    |                      |          o| |k     S )ap  If this Group is a superset of another Group but not identical

        Parameters
        ----------
        other : Group or Component
            Group or Component with `other.level` same as `self.level`

        Returns
        -------
        bool
            ``True`` if this Group is a strict superset of the other one


        .. versionadded:: 0.16
        )r  r  s     r    is_strict_supersetzGroupBase.is_strict_superset	  s"      u%%;dem*;;r"   )FFF)FFr   )r  r   )NT)r   r  NT)rS  r  T)CrS   r   r   r   r   r   r   r]   r   r  r  r  r  r  r   r   r"  r%  r(  r+  rg   r   r   r   rM   rd   r
   r7  r<  r>  r@  rP  rZ  rm  r   r   r   r  r  r  r   rz  r  r  r  r  r  r  r  rv  r   r   r4  r  r  r  r$  r'  r  r  r*  r  r  r  r  r  r   r   s   @r    r:   r:   !  s       A AF  :H H H  E E E.< < < < <$
 
 
	 	 	' ' '"  2& & & 	- 	- 	-# # #! ! !( ( (0 0 0   X   X 
 
 X
   X < < < VO* *  X* V+ +  X+ VJ, ,  X, VJ#C #C  X#CJ6 6 6 6p     B_? _? _? _?B _ _ _  \ _B 4N 4N 4N  \ 4Nl "H-/Vg E E E EN $8 $8 $8 \$8L % % % \%N 6  6  6D! ! !F0 0 0 0d)! )! )! )!V23 23 23 23hD D D DLm m m m^  8 8 8&P* P* P*d +
 +
 +
Z ,M ,M ,M\ '
 '
 '
R / / /b J J J8 *I *I *IX2 2 2$ # # #,: : :$ % % %(< < < < < < <r"   r:   c                       e Zd ZdZ fdZd Zed             Zed             Zed             Z	e	j
        d             Z	ed             Zed	             Zej
        d
             Zed             Ze ed          d                         Zej
        d             Zed             Zd.dZed             Zej
        d             Zed             Zej
        d             Zed             Zej
        d             Zed             ZdddddddddZd Zd/d"Zed#             Zed$             Zed%             Zed&             Zed'             Zed(             Z ed)e           Z!	 	 	 	 d0d+Z"d1d-Z# xZ$S )2r2   a)  An ordered array of atoms.

    Can be initiated from an iterable of :class:`Atoms<Atom>`::

        ag = AtomGroup([Atom1, Atom2, Atom3])

    Or from providing a list of indices and the
    :class:`~MDAnalysis.core.universe.Universe` it should belong to::

        ag = AtomGroup([72, 14, 25], u)

    Alternatively, an :class:`AtomGroup` is generated by indexing/slicing
    another :class:`AtomGroup`, such as the group of all :class:`Atoms<Atom>` in
    the :class:`~MDAnalysis.core.universe.Universe` at
    :attr:`MDAnalysis.core.universe.Universe.atoms`.

    An :class:`AtomGroup` can be indexed and sliced like a list::

        ag[0], ag[-1]

    will return the first and the last :class:`Atom` in the group whereas the
    slice::

        ag[0:6:2]

    returns an :class:`AtomGroup` of every second element, corresponding to
    indices 0, 2, and 4.

    It also supports "advanced slicing" when the argument is a
    :class:`numpy.ndarray` or a :class:`list`::

        aslice = [0, 3, -1, 10, 3]
        ag[aslice]

    will return a new :class:`AtomGroup` of :class:`Atoms<Atom>` with those
    indices in the old :class:`AtomGroup`.

    Finally, :class:`AtomGroups<AtomGroup>` can be created from a selection.
    See :meth:`select_atoms`.

    .. note::

        :class:`AtomGroups<AtomGroup>` originating from a selection are sorted
        and duplicate elements are removed. This is not true for
        :class:`AtomGroups<AtomGroup>` produced by slicing. Thus, slicing can be
        used when the order of atoms is crucial (for instance, in order to
        define angles or dihedrals).

    :class:`AtomGroups<AtomGroup>` can be compared and combined using group
    operators. For instance, :class:`AtomGroups<AtomGroup>` can be concatenated
    using `+` or :meth:`concatenate`::

        ag_concat = ag1 + ag2  # or ag_concat = ag1.concatenate(ag2)

    When groups are concatenated, the order of the :class:`Atoms<Atom>` is
    conserved. If :class:`Atoms<Atom>` appear several times in one of the
    groups, the duplicates are kept in the resulting group. On the contrary to
    :meth:`concatenate`, :meth:`union` treats the :class:`AtomGroups<AtomGroup>`
    as sets so that duplicates are removed from the resulting group, and
    :class:`Atoms<Atom>` are ordered. The `|` operator is synomymous to
    :meth:`union`::

        ag_union = ag1 | ag2  # or ag_union = ag1.union(ag2)

    The opposite operation to :meth:`concatenate` is :meth:`subtract`. This
    method creates a new group with all the :class:`Atoms<Atom>` of the group
    that are not in a given other group; the order of the :class:`Atoms<Atom>`
    is kept, and so are duplicates. :meth:`difference` is the set version of
    :meth:`subtract`. The resulting group is sorted and deduplicated.

    All set methods are listed in the table below. These methods treat the
    groups as sorted and deduplicated sets of :class:`Atoms<Atom>`.

    +-------------------------------+------------+----------------------------+
    | 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         |
    +-------------------------------+------------+----------------------------+

    The following methods keep the order of the atoms as well as duplicates.

    +-------------------------------+------------+----------------------------+
    | 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          |
    +-------------------------------+------------+----------------------------+
    | ``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 `in` operator allows to test if an :class:`Atom` is in the
    :class:`AtomGroup`.

    :class:`AtomGroup` instances are always bound to a
    :class:`MDAnalysis.core.universe.Universe`. They cannot exist in isolation.

    During serialization, :class:`AtomGroup` will be pickled with its bound
    :class:`MDAnalysis.core.universe.Universe` which means after unpickling,
    a new :class:`MDAnalysis.core.universe.Universe` will be created and
    be attached by the new :class:`AtomGroup`. If the Universe is serialized
    with its :class:`AtomGroup`, they will still be bound together afterwards:

    .. testsetup:: AtomGroup

        import MDAnalysis as mda
        from MDAnalysis.tests.datafiles import PSF, DCD

    .. doctest:: AtomGroup

        >>> import pickle

        >>> u = mda.Universe(PSF, DCD)
        >>> g = u.atoms

        >>> g_pickled = pickle.loads(pickle.dumps(g))
        >>> print("g_pickled.universe is u: ", u is g_pickled.universe)
        g_pickled.universe is u:  False

        >>> g_pickled, u_pickled = pickle.loads(pickle.dumps((g, u)))
        >>> print("g_pickled.universe is u_pickled: ",
        ...       u_pickled is g_pickled.universe)
        g_pickled.universe is u_pickled:  True

    If multiple :class:`AtomGroup` are bound to the same
    :class:`MDAnalysis.core.universe.Universe`, they will bound to the same one
    after serialization:

    .. doctest:: AtomGroup

        >>> import pickle

        >>> u = mda.Universe(PSF, DCD)
        >>> g = u.atoms
        >>> h = u.atoms

        >>> g_pickled = pickle.loads(pickle.dumps(g))
        >>> h_pickled = pickle.loads(pickle.dumps(h))
        >>> print("g_pickled.universe is h_pickled.universe: ",
        ...       g_pickled.universe is h_pickled.universe)
        g_pickled.universe is h_pickled.universe:  False

        >>> g_pickled, h_pickled = pickle.loads(pickle.dumps((g, h)))
        >>> print("g_pickled.universe is h_pickled.universe: ",
        ...       g_pickled.universe is h_pickled.universe)
        g_pickled.universe is h_pickled.universe:  True

    The aforementioned two cases are useful for implementation of parallel
    analysis base classes. First, you always get an independent
    :class:`MDAnalysis.core.universe.Universe`
    in the new process; you don't have to worry about detaching and reattaching
    Universe with :class:`AtomGroup`. It also means the state of the
    new pickled AtomGroup will not be changed with the old Universe,
    So either the Universe has to pickled together with the AtomGroup
    (e.g. as a tuple, or as attributes of the object to be pickled), or the
    implicit new Universe (`AtomGroup.Universe`) needs to be used.
    Second, When multiple AtomGroup need to be pickled, they will recognize if
    they belong to the same Univese or not.
    Also keep in mind that they need to be pickled together.

    See Also
    --------
    :class:`MDAnalysis.core.universe.Universe`


    .. deprecated:: 0.16.2
       *Instant selectors* of :class:`AtomGroup` will be removed in the 1.0
       release.
    .. versionchanged:: 1.0.0
       Removed instant selectors, use select_atoms('name ...') to select
       atoms by name.
    .. versionchanged:: 2.0.0
       :class:`AtomGroup` can always be pickled with or without its universe,
       instead of failing when not finding its anchored universe.
    .. versionchanged:: 2.1.0
       Indexing an AtomGroup with ``None`` raises a ``TypeError``.
    c                     |dv rt          d|z             |dk    rt          d          t          t          |                               |          S )N)rN   rG   This Timestep has no rL    This Universe has no coordinates)r   r{   r2   r   )r^   r_   r~   s     r    r   zAtomGroup.__getattr__
  s[    +++5<===[  @AAAY%%11$777r"   c                 ,    t           | j        | j        ffS r   )r!   r   r   r   s    r    
__reduce__zAtomGroup.__reduce__
  s    DM47344r"   c                     | S )al  The :class:`AtomGroup` itself.

        See Also
        --------
        copy : return a true copy of the :class:`AtomGroup`


        .. versionchanged:: 0.19.0
           In previous versions, this returned a copy, but now
           the :class:`AtomGroup` itself is returned. This should
           not affect any code but only speed up calculations.

        r$   r   s    r    r   zAtomGroup.atoms
  	     r"   c                      t          |           S )zYNumber of atoms in the :class:`AtomGroup`.

        Equivalent to ``len(self)``.
        r   r   s    r    n_atomszAtomGroup.n_atoms
       4yyr"   c                     | j         j        t          | j                           }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )z{A sorted :class:`ResidueGroup` of the unique
        :class:`Residues<Residue>` present in the :class:`AtomGroup`.
        Tr@  r>  r7  r<  )r   rJ   r   rT  r   r^   rgs     r    rJ   zAtomGroup.residues
  S    
 ]#M$/$B$BC $	* $	*%'	/"')	#$	r"   c                    t          |t                    rt          j        |j        f          }n{t          |t
                    r|j        }n^	 d |D             }nP# t          $ rC d                    d	                    d |D                                 }t          |          d w xY wt          |t          j                  s]t          |          t          |           k    r=t          d                    t          |          t          |                               t          | |          D ]/\  }}| j        j        j                            |j        |           0d S )Nc                     g | ]	}|j         
S r$   )resindexr   rs     r    r   z&AtomGroup.residues.<locals>.<listcomp>      000q
000r"   zACan only set AtomGroup residues to Residue or ResidueGroup not {}, c              3   ^   K   | ](}t          |t                    t          |          V  )d S r   )r   r6   rR   r  s     r    r   z%AtomGroup.residues.<locals>.<genexpr>  K       " "()
1g8N8N" GG" " " " " "r"   z,Incorrect size: {} for AtomGroup of size: {})r   r6   	itertoolscycler  r3   rT  rp   rz   joinr   r   r   r|  r   r  tt	move_atomr   )r^   newr_ixr   r   r  s         r    rJ   zAtomGroup.residues	  s{    c7## 	2?CL?33DD\** 	2>DD200C000! 	2 	2 	2--3V		 " "-0" " "  . .   ''T1	2 $	00 	SYY#d))5K5K6#c((CII..   t__ 	; 	;EBM#&00::::	; 	;   A AB)c                 *    t          | j                  S )zNumber of unique :class:`Residues<Residue>` present in the
        :class:`AtomGroup`.

        Equivalent to ``len(self.residues)``.

        r   rJ   r   s    r    
n_residueszAtomGroup.n_residues*  s     4=!!!r"   c                     | j         j        t          | j                           }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )ziA sorted :class:`SegmentGroup` of the unique segments present in the
        :class:`AtomGroup`.
        Tr@  r>  r7  r<  r   rK   r   rU  r   r^   sgs     r    rK   zAtomGroup.segments4  r  r"   c                      t          d          )NzFCannot assign Segments to AtomGroup. Segments are assigned to ResiduesNotImplementedErrorr^   r  s     r    rK   zAtomGroup.segments@  s    !0
 
 	
r"   c                 *    t          | j                  S )ztNumber of unique segments present in the :class:`AtomGroup`.

        Equivalent to ``len(self.segments)``.
        r   rK   r   s    r    
n_segmentszAtomGroup.n_segmentsG       4=!!!r"   unique_restore_maskc                     | j         r d                    | j        j                  }nd                    | j        j                  }|dz  }t	          |          )Nz@{0}._unique_restore_mask is not available if the {0} is unique. zG{0}._unique_restore_mask is only available after accessing {0}.unique. zmIf you see this error message in an unmodified release version of MDAnalysis, this is almost certainly a bug!)r@  rz   r~   rS   RuntimeError)r^   msgs     r    rF  zAtomGroup._unique_restore_maskO  sj     = 		!6$."9:: C))/0G)H)H  	E	
 3r"   c                     || j         d<   d S )Nr)  )r   )r^   r   s     r    rF  zAtomGroup._unique_restore_maski  s    -1)***r"   c                 t    | j         dd         }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )a  An :class:`AtomGroup` containing sorted and unique
        :class:`Atoms<Atom>` only.

        Examples
        --------

        .. doctest:: AtomGroup.unique

            >>> import MDAnalysis as mda
            >>> from MDAnalysis.tests.datafiles import PSF, DCD
            >>> u = mda.Universe(PSF, DCD)
            >>> ag = u.atoms[[2, 1, 2, 2, 1, 0]]
            >>> ag
            <AtomGroup with 6 atoms>
            >>> ag.ix
            array([2, 1, 2, 2, 1, 0])
            >>> ag2 = ag.unique
            >>> ag2
            <AtomGroup with 3 atoms>
            >>> ag2.ix
            array([0, 1, 2])
            >>> ag2.unique is ag2
            False

        See Also
        --------

        asunique

        .. versionadded:: 0.16.0
        .. versionchanged:: 0.19.0 If the :class:`AtomGroup` is already unique,
            :attr:`AtomGroup.unique` now returns the group itself instead of a
            copy.
        .. versionchanged:: 2.0.0
            This function now always returns a copy.
        NTr@  r>  r7  r<  r7  r   r  s     r    rE  zAtomGroup.uniquem  sL    L "111%#'Z #'Z (-_%*/&'r"   Fc                 F    |                      || j        j        d          S )a_  Return a :class:`AtomGroup` containing unique
        :class:`Atoms<Atom>` only, with optional sorting.

        If the :class:`AtomGroup` is unique, this is the group itself.

        Parameters
        ----------
        sorted: bool (optional)
            Whether or not the returned AtomGroup should be sorted
            by index.

        Returns
        -------
        :class:`AtomGroup`
            Unique ``AtomGroup``


        Examples
        --------

        .. doctest:: AtomGroup.asunique

            >>> import MDAnalysis as mda
            >>> from MDAnalysis.tests.datafiles import PSF, DCD
            >>> u = mda.Universe(PSF, DCD)
            >>> ag = u.atoms[[2, 1, 0]]
            >>> ag2 = ag.asunique(sorted=False)
            >>> ag2 is ag
            True
            >>> ag2.ix
            array([2, 1, 0])
            >>> ag3 = ag.asunique(sorted=True)
            >>> ag3 is ag
            False
            >>> ag3.ix
            array([0, 1, 2])
            >>> u.atoms[[2, 1, 1, 0, 1]].asunique(sorted=False).ix
            array([2, 1, 0])


        .. versionadded:: 2.0.0
        T)r   r   rJ  )rP  r   r   r^   r   s     r    r;  zAtomGroup.asunique  s,    V ~~!4t  
 
 	
r"   c                 D    | j         j        j        j        | j                 S )a|  Coordinates of the :class:`Atoms<Atom>` in the :class:`AtomGroup`.

        A :class:`numpy.ndarray` with
        :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)``
        and :attr:`~numpy.ndarray.dtype`\ ``=numpy.float32``.

        The positions can be changed by assigning an array of the appropriate
        shape, i.e., either ``(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` to
        assign individual coordinates, or ``(3,)`` to assign the *same*
        coordinate to all :class:`Atoms<Atom>` (e.g.,
        ``ag.positions = array([0,0,0])`` will move all :class:`Atoms<Atom>`
        to the origin).

        .. note:: Changing positions is not reflected in any files; reading any
                  frame from the
                  :attr:`~MDAnalysis.core.universe.Universe.trajectory` will
                  replace the change with that from the file *except* if the
                  :attr:`~MDAnalysis.core.universe.Universe.trajectory` is held
                  in memory, e.g., when the
                  :meth:`~MDAnalysis.core.universe.Universe.transfer_to_memory`
                  method was used.

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the underlying :class:`~MDAnalysis.coordinates.timestep.Timestep`
            does not contain
            :attr:`~MDAnalysis.coordinates.timestep.Timestep.positions`.
        r   r2  r3  rL   r   r   s    r    rL   zAtomGroup.positions  s    > }'*4TW==r"   c                 N    | j         j        j        }||j        | j        d d f<   d S r   r3  r^   rc   r3  s      r    rL   zAtomGroup.positions  s+    ]%(#)TWaaaZ   r"   c                 l    | j         j        j        }t          j        |j        | j                           S )a  Velocities of the :class:`Atoms<Atom>` in the :class:`AtomGroup`.

        A :class:`numpy.ndarray` with
        :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)``
        and :attr:`~numpy.ndarray.dtype`\ ``=numpy.float32``.

        The velocities can be changed by assigning an array of the appropriate
        shape, i.e. either ``(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` to assign
        individual velocities or ``(3,)`` to assign the *same* velocity to all
        :class:`Atoms<Atom>` (e.g. ``ag.velocities = array([0,0,0])`` will give
        all :class:`Atoms<Atom>` zero :attr:`~Atom.velocity`).

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the underlying :class:`~MDAnalysis.coordinates.timestep.Timestep`
            does not contain
            :attr:`~MDAnalysis.coordinates.timestep.Timestep.velocities`.
        )r   r2  r3  r   r   rN   r   r^   r3  s     r    rN   zAtomGroup.velocities  s*    * ]%(xdg.///r"   c                 N    | j         j        j        }||j        | j        d d f<   d S r   r   r2  r3  rN   r   r5  s      r    rN   zAtomGroup.velocities  +    ]%($*dgqqqj!!!r"   c                 H    | j         j        j        }|j        | j                 S )aN  Forces on each :class:`Atom` in the :class:`AtomGroup`.

        A :class:`numpy.ndarray` with
        :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)``
        and :attr:`~numpy.ndarray.dtype`\ ``=numpy.float32``.

        The forces can be changed by assigning an array of the appropriate
        shape, i.e. either ``(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` to assign
        individual forces or ``(3,)`` to assign the *same* force to all
        :class:`Atoms<Atom>` (e.g. ``ag.forces = array([0,0,0])`` will give all
        :class:`Atoms<Atom>` a zero :attr:`~Atom.force`).

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the :class:`~MDAnalysis.coordinates.timestep.Timestep` does not
            contain :attr:`~MDAnalysis.coordinates.timestep.Timestep.forces`.
        r   r2  r3  rG   r   r7  s     r    rG   zAtomGroup.forces  s     ( ]%(y!!r"   c                 N    | j         j        j        }||j        | j        d d f<   d S r   r<  r5  s      r    rG   zAtomGroup.forces#  +    ]%( &	$'111*r"   c                 X    | j         j        j        }|                    | j                  S )ax  Temporary Timestep that contains the selection coordinates.

        A :class:`~MDAnalysis.coordinates.timestep.Timestep` instance,
        which can be passed to a trajectory writer.

        If :attr:`~AtomGroup.ts` is modified then these modifications
        will be present until the frame number changes (which
        typically happens when the underlying
        :attr:`~MDAnalysis.core.universe.Universe.trajectory` frame changes).

        It is not possible to assign a new
        :class:`~MDAnalysis.coordinates.timestep.Timestep` to the
        :attr:`AtomGroup.ts` attribute; change attributes of the object.
        )r   r2  r3  
copy_slicer   )r^   trj_tss     r    r3  zAtomGroup.ts(  s'      ),  ...r"   Tgh㈵>g:0yE>N)periodicrtolatolupdatingr   rdkit_kwargssmarts_kwargsc          	         
 |s"t          j        dt                      g          S |f|	z   }
                                D ]G\  }}t	          |t
                    s-t          d                    |j        j	        |                    Ht          
fd|D                       }|rt           ||          }n=t           fd|dd         D             |d                                                  }|S )aM  Select atoms from within this Group using a selection string.

        Returns an :class:`AtomGroup` sorted according to their index in the
        topology (this is to ensure that there are no duplicates, which can
        happen with complicated selections).

        Parameters
        ----------
        sel : str
          string of the selection, eg "name Ca", see below for possibilities.
        othersel : iterable of str
          further selections to perform.  The results of these selections
          will be appended onto the results of the first.
        periodic : bool (optional)
          for geometric selections, whether to account for atoms in different
          periodic images when searching
        atol : float, optional
            The absolute tolerance parameter for float comparisons.
            Passed to :func:``numpy.isclose``.
        rtol : float, optional
            The relative tolerance parameter for float comparisons.
            Passed to :func:``numpy.isclose``.
        updating : bool (optional)
          force the selection to be re evaluated each time the Timestep of the
          trajectory is changed.  See section on **Dynamic selections** below.
          [``True``]
        sorted: bool, optional
          Whether to sort the output AtomGroup by index.
        rdkit_kwargs : dict (optional)
          Arguments passed to the
          :class:`~MDAnalysis.converters.RDKit.RDKitConverter` when using
          selection based on SMARTS queries
        smarts_kwargs : dict (optional)
          Arguments passed internally to RDKit's `GetSubstructMatches
          <https://www.rdkit.org/docs/source/rdkit.Chem.rdchem.html#rdkit.Chem.rdchem.Mol.GetSubstructMatches>`_.

        **selgroups : keyword arguments of str: AtomGroup (optional)
          when using the "group" keyword in selections, groups are defined by
          passing them as keyword arguments.  See section on **preexisting
          selections** below.

        Raises
        ------
        TypeError
            If the arbitrary groups passed are not of type
            :class:`MDAnalysis.core.groups.AtomGroup`

        Examples
        --------
        All simple selection listed below support multiple arguments which are
        implicitly combined with an or operator. For example

        .. testsetup:: AtomGroup.select_atoms

            from MDAnalysis.tests.datafiles import PSF, DCD
            import MDAnalysis as mda
            universe = mda.Universe(PSF, DCD)

        .. doctest:: AtomGroup.select_atoms

            >>> sel = universe.select_atoms('resname MET GLY')
            >>> sel
            <AtomGroup with 245 atoms>

        is equivalent to

        .. doctest:: AtomGroup.select_atoms

            >>> sel = universe.select_atoms('resname MET or resname GLY')
            >>> sel
            <AtomGroup with 245 atoms>

        Will select all atoms with a residue name of either MET or GLY.

        Subselections can be grouped with parentheses.

        .. doctest:: AtomGroup.select_atoms

            >>> sel = universe.select_atoms("segid 4AKE and not ( name H* O* )")
            >>> sel
            <AtomGroup with 1336 atoms>

        Existing :class:`AtomGroup` objects can be passed as named arguments,
        which will then be available to the selection parser.

        .. testsetup:: AtomGroup.select_atoms.namedarguments

            from MDAnalysis.tests.datafiles import PSF, DCD
            import MDAnalysis as mda
            universe = mda.Universe(PSF, DCD)
            sel = universe.select_atoms("segid 4AKE and not ( name H* O* )")

        .. doctest:: AtomGroup.select_atoms, AtomGroup.select_atoms.namedarguments

            >>> universe.select_atoms("around 10 group notHO", notHO=sel)
            <AtomGroup with 2005 atoms>

        Selections can be set to update automatically on frame change, by
        setting the `updating` keyword argument to `True`.  This will return
        a :class:`UpdatingAtomGroup` which can represent the solvation shell
        around another object.

        .. testsetup:: AtomGroup.select_atoms.updating

            from MDAnalysis.tests.datafiles import PDB, XTC
            import MDAnalysis as mda
            universe = mda.Universe(PDB, XTC)

        .. doctest:: AtomGroup.select_atoms.updating
           :options: +NORMALIZE_WHITESPACE

            >>> universe.select_atoms("resname SOL and around 2.0 protein",
            ...       updating=True)
            <AtomGroup with 454 atoms, with selection
            'resname SOL and around 2.0 protein' on the entire Universe.>

        Notes
        -----

        If exact ordering of atoms is required (for instance, for
        :meth:`~AtomGroup.angle` or :meth:`~AtomGroup.dihedral` calculations)
        then one supplies selections *separately* in the required order. Also,
        when multiple :class:`AtomGroup` instances are concatenated with the
        ``+`` operator, then the order of :class:`Atom` instances is preserved
        and duplicates are *not* removed.


        See Also
        --------
        :ref:`selection-commands-label` for further details and examples.


        .. rubric:: Selection syntax


        The selection parser understands the following CASE SENSITIVE
        *keywords*:

        **Simple selections**

            protein, backbone, nucleic, nucleicbackbone
                selects all atoms that belong to a standard set of residues;
                a protein is identfied by a hard-coded set of residue names so
                it  may not work for esoteric residues.
            segid *seg-name*
                select by segid (as given in the topology), e.g. ``segid 4AKE``
                or ``segid DMPC``
            resid *residue-number-range*
                resid can take a single residue number or a range of numbers. A
                range consists of two numbers separated by a colon (inclusive)
                such as ``resid 1:5``. A residue number ("resid") is taken
                directly from the topology.
                If icodes are present in the topology, then these will be
                taken into account.  Ie 'resid 163B' will only select resid
                163 with icode B while 'resid 163' will select only residue 163.
                Range selections will also respect icodes, so 'resid 162-163B'
                will select all residues in 162 and those in 163 up to icode B.
            resnum *resnum-number-range*
                resnum is the canonical residue number; typically it is set to
                the residue id in the original PDB structure.
            resname *residue-name*
                select by residue name, e.g. ``resname LYS``
            name *atom-name*
                select by atom name (as given in the topology). Often, this is
                force field dependent. Example: ``name CA`` (for C&alpha; atoms)
                or ``name OW`` (for SPC water oxygen)
            type *atom-type*
                select by atom type; this is either a string or a number and
                depends on the force field; it is read from the topology file
                (e.g. the CHARMM PSF file contains numeric atom types). It has
                non-sensical values when a PDB or GRO file is used as a topology
            atom *seg-name*  *residue-number*  *atom-name*
                a selector for a single atom consisting of segid resid atomname,
                e.g. ``DMPC 1 C2`` selects the C2 carbon of the first residue of
                the DMPC segment
            altloc *alternative-location*
                a selection for atoms where alternative locations are available,
                which is often the case with high-resolution crystal structures
                e.g. `resid 4 and resname ALA and altloc B` selects only the
                atoms of ALA-4 that have an altloc B record.
            moltype *molecule-type*
                select by molecule type, e.g. ``moltype Protein_A``. At the
                moment, only the TPR format defines the molecule type.
            record_type *record_type*
                for selecting either ATOM or HETATM from PDB-like files.
                e.g. ``select_atoms('name CA and not record_type HETATM')``
            smarts *SMARTS-query*
                select atoms using Daylight's SMARTS queries, e.g. ``smarts
                [#7;R]`` to find nitrogen atoms in rings. Requires RDKit.
                All matches are combined as a single unique match. The `smarts`
                selection accepts two sets of key word arguments from
                `select_atoms()`: the ``rdkit_kwargs`` are passed internally to
                `RDKitConverter.convert()` and the ``smarts_kwargs`` are passed to
                RDKit's `GetSubstructMatches
                <https://www.rdkit.org/docs/source/rdkit.Chem.rdchem.html#rdkit.Chem.rdchem.Mol.GetSubstructMatches>`_.
                By default, the `useChirality` kwarg in ``rdkit_kwargs`` is set to true
                and maxMatches in ``smarts_kwargs`` is
                ``max(1000, 10 * n_atoms)``, where ``n_atoms`` is either
                ``len(AtomGroup)`` or ``len(Universe.atoms)``, whichever is
                applicable. Note that the number of matches can occasionally
                exceed the default value of maxMatches, causing too few atoms
                to be returned. If this occurs, a warning will be issued. The
                problem can be fixed by increasing the value of maxMatches.
                This behavior may be updated in the future.

                .. testsetup:: AtomGroup.select_atoms.smarts

                    from MDAnalysis.tests.datafiles import PSF, DCD
                    from MDAnalysis.topology.guessers import guess_types
                    import MDAnalysis as mda
                    universe = mda.Universe(PSF, DCD)
                    guessed_elements = guess_types(universe.atoms.names)
                    universe.add_TopologyAttr('elements', guessed_elements)

                .. doctest:: AtomGroup.select_atoms.smarts

                    >>> universe.select_atoms("smarts C", smarts_kwargs={"maxMatches": 100})
                    <AtomGroup with 100 atoms>

            chiral *R | S*
                select a particular stereocenter. e.g. ``name C and chirality
                S`` to select only S-chiral carbon atoms.  Only ``R`` and
                ``S`` will be possible options but other values will not raise
                an error.

            formalcharge *formal-charge*
                select atoms based on their formal charge, e.g.
                ``name O and formalcharge -1`` to select all oxygens with a
                negative 1 formal charge.

        **Boolean**

            not
                all atoms not in the selection, e.g. ``not protein`` selects
                all atoms that aren't part of a protein
            and, or
                combine two selections according to the rules of boolean
                algebra, e.g. ``protein and not resname ALA LYS``
                selects all atoms that belong to a protein, but are not in a
                lysine or alanine residue

        **Geometric**

            around *distance*  *selection*
                selects all atoms a certain cutoff away from another selection,
                e.g. ``around 3.5 protein`` selects all atoms not belonging to
                protein that are within 3.5 Angstroms from the protein
            point *x* *y* *z*  *distance*
                selects all atoms within a cutoff of a point in space, make sure
                coordinate is separated by spaces,
                e.g. ``point 5.0 5.0 5.0  3.5`` selects all atoms within 3.5
                Angstroms of the coordinate (5.0, 5.0, 5.0)
            prop [abs] *property*  *operator*  *value*
                selects atoms based on position, using *property*  **x**, **y**,
                or **z** coordinate. Supports the **abs** keyword (for absolute
                value) and the following *operators*: **<, >, <=, >=, ==, !=**.
                For example, ``prop z >= 5.0`` selects all atoms with z
                coordinate greater than 5.0; ``prop abs z <= 5.0`` selects all
                atoms within -5.0 <= z <= 5.0.
            sphzone *radius* *selection*
                Selects all atoms that are within *radius* of the center of
                geometry of *selection*
            sphlayer *inner radius* *outer radius* *selection*
                Similar to sphzone, but also excludes atoms that are within
                *inner radius* of the selection COG
            isolayer *inner radius* *outer radius* *selection*
                Similar to sphlayer, but will find layer around all reference
                layer, creating an iso-surface.
            cyzone *externalRadius* *zMax* *zMin* *selection*
                selects all atoms within a cylindric zone centered in the
                center of geometry (COG) of a given selection,
                e.g. ``cyzone 15 4 -8 protein and resid 42`` selects the
                center of geometry of protein and resid 42, and creates a
                cylinder of external radius 15 centered on the COG. In z, the
                cylinder extends from 4 above the COG to 8 below. Positive
                values for *zMin*, or negative ones for *zMax*, are allowed.
            cylayer *innerRadius* *externalRadius* *zMax* *zMin* *selection*
                selects all atoms within a cylindric layer centered in the
                center of geometry (COG) of a given selection,
                e.g. ``cylayer 5 10 10 -8 protein`` selects the center of
                geometry of protein, and creates a cylindrical layer of inner
                radius 5, external radius 10 centered on the COG. In z, the
                cylinder extends from 10 above the COG to 8 below. Positive
                values for *zMin*, or negative ones for *zMax*, are allowed.

        **Connectivity**

            byres *selection*
                selects all atoms that are in the same segment and residue as
                selection, e.g. specify the subselection after the byres keyword
            bonded *selection*
                selects all atoms that are bonded to selection
                eg: ``select name H and bonded name O`` selects only hydrogens
                bonded to oxygens

        **Index**

            bynum *index-range*
                selects all atoms within a range of (1-based) inclusive indices,
                e.g. ``bynum 1`` selects the first atom in the universe;
                ``bynum 5:10`` selects atoms 5 through 10 inclusive. All atoms
                in the :class:`~MDAnalysis.core.universe.Universe` are
                consecutively numbered, and the index runs from 1 up to the
                total number of atoms.
            index *index-range*
                selects all atoms within a range of (0-based) inclusive indices,
                e.g. ``index 0`` selects the first atom in the universe;
                ``index 5:10`` selects atoms 6 through 11 inclusive. All atoms
                in the :class:`~MDAnalysis.core.universe.Universe` are
                consecutively numbered, and the index runs from 0 up to the
                total number of atoms - 1.

        **Preexisting selections**

            group `group-name`
                selects the atoms in the :class:`AtomGroup` passed to the
                function as a keyword argument named `group-name`. Only the
                atoms common to `group-name` and the instance
                :meth:`~MDAnalysis.core.groups.AtomGroup.select_atoms`
                was called from will be considered, unless ``group`` is
                preceded by the ``global`` keyword. `group-name` will be
                included in the parsing just by comparison of atom indices.
                This means that it is up to the user to make sure the
                `group-name` group was defined in an appropriate
                :class:`~MDAnalysis.core.universe.Universe`.
            global *selection*
                by default, when issuing
                :meth:`~MDAnalysis.core.groups.AtomGroup.select_atoms` from an
                :class:`~MDAnalysis.core.groups.AtomGroup`, selections and
                subselections are returned intersected with the atoms of that
                instance. Prefixing a selection term with ``global`` causes its
                selection to be returned in its entirety.  As an example, the
                ``global`` keyword allows for
                ``lipids.select_atoms("around 10 global protein")`` --- where
                ``lipids`` is a group that does not contain any proteins. Were
                ``global`` absent, the result would be an empty selection since
                the ``protein`` subselection would itself be empty. When issuing
                :meth:`~MDAnalysis.core.groups.AtomGroup.select_atoms` from a
                :class:`~MDAnalysis.core.universe.Universe`, ``global`` is
                ignored.

        **Dynamic selections**
            If :meth:`~MDAnalysis.core.groups.AtomGroup.select_atoms` is
            invoked with named argument `updating` set to `True`, an
            :class:`~MDAnalysis.core.groups.UpdatingAtomGroup` instance will be
            returned, instead of a regular
            :class:`~MDAnalysis.core.groups.AtomGroup`. It behaves just like
            the latter, with the difference that the selection expressions are
            re-evaluated every time the trajectory frame changes (this happens
            lazily, only when the
            :class:`~MDAnalysis.core.groups.UpdatingAtomGroup` is accessed so
            that there is no redundant updating going on).
            Issuing an updating selection from an already updating group will
            cause later updates to also reflect the updating of the base group.
            A non-updating selection or a slicing operation made on an
            :class:`~MDAnalysis.core.groups.UpdatingAtomGroup` will return a
            static :class:`~MDAnalysis.core.groups.AtomGroup`, which will no
            longer update across frames.


        .. versionchanged:: 0.7.4 Added *resnum* selection.
        .. versionchanged:: 0.8.1 Added *group* and *fullgroup* selections.
        .. versionchanged:: 0.13.0 Added *bonded* selection.
        .. versionchanged:: 0.16.0 Resid selection now takes icodes into account
            where present.
        .. versionchanged:: 0.16.0 Updating selections now possible by setting
            the `updating` argument.
        .. versionchanged:: 0.17.0 Added *moltype* and *molnum* selections.
        .. versionchanged:: 0.19.0
           Added strict type checking for passed groups.
           Added periodic kwarg (default True)
        .. versionchanged:: 0.19.2
           Empty sel string now returns an empty Atom group.
        .. versionchanged:: 1.0.0
           The ``fullgroup`` selection has now been removed in favor of the
           equivalent ``global group`` selection.
           Removed flags affecting default behaviour for periodic selections;
           periodic are now on by default (as with default flags)
        .. versionchanged:: 2.0.0
            Added the *smarts* selection. Added `atol` and `rtol` keywords
            to select float values. Added the ``sort`` keyword. Added
            `rdkit_kwargs` to pass parameters to the RDKitConverter.
        .. versionchanged:: 2.2.0
            Added `smarts_kwargs` to pass parameters to the RDKit
            GetSubstructMatch for *smarts* selection.
        z3Empty string to select atoms, empty group returned.z@Passed groups must be AtomGroups. You provided {} for group '{}'c              3   f   K   | ]+}t           j                            |           V  ,dS ))rB  rD  rC  r   rF  rG  N)r   Parserparse)	r   r  rD  rB  rF  rC  	selgroupsrG  r   s	     r    r   z)AtomGroup.select_atoms.<locals>.<genexpr>  si           &&%!!-"/ ' 	 	     r"   c                 :    g | ]}|                               S r$   apply)r   selr^   s     r    r   z*AtomGroup.select_atoms.<locals>.<listcomp>  s#    ;;;S4;;;r"   r   Nr   )r   r   UserWarningitemsr   r2   r   rz   r~   rS   r   r(   rz  rO  )r^   rP  rB  rC  rD  rE  r   rF  rG  otherselrL  sel_strsr   thingr*   atomgrps   ` ``` ``` `     r    select_atomszAtomGroup.select_atoms?  sj   `  	ME   8O6H$%OO-- 	 	LE5eY// 55;V0%6 6             "  
 

  	'j(CCGG ;;;;JqrrN;;;1##D)) G r"   c                 P    dddd}|dk    r fd D             S 	 t           ||                   nW# t          $ r d| d}t          |          d	t          $ r+ d
| d|                                 }t	          |          d	w xY w fdt                    D             S )a/  Split :class:`AtomGroup` into a :class:`list` of
        :class:`AtomGroups<AtomGroup>` by `level`.

        Parameters
        ----------
        level : {'atom', 'residue', 'molecule', 'segment'}


        .. versionadded:: 0.9.0
        .. versionchanged:: 0.17.0 Added the 'molecule' level.
        rU  rT  rV  )rI   rH   moleculeatomc                 @    g | ]}j         j        |j        g         S r$   )r   r   r   )r   ar^   s     r    r   z#AtomGroup.split.<locals>.<listcomp>  s'    >>>ADM'/>>>r"   zThis universe does not have zE information. Maybe it is not provided in the topology format in use.Nz	level = 'z ' not supported, must be one of c                 (    g | ]}|k             S r$   r$   )r   indexlevelindicesr^   s     r    r   z#AtomGroup.split.<locals>.<listcomp>  s3     
 
 
 &'
 
 
r"   )r   rp   r   r   r   r   )r^   r   	accessorsr   r_  s   `   @r    splitzAtomGroup.split  s0    $#!
 
	 F??>>>>>>>>	/"45)9::LL 	3 	3 	3Fu F F F  !((d2 	/ 	/ 	/&E & &>>##& &  V$$$.	/
 
 
 
 
&|44
 
 
 	
s
   5 AB	皙?皙?c                    ddl m}m}m} ddlm} d } |d||| j        |          }	|	                    | j        | j        j	                  }
 || j
        d|          }|                    |
d	
           |	                    | j                  } || j
        d|          }|                    |d	
           |	                    | j                  } || j
        d|          }|                    |           dS )a1  Guess bonds, angles, and dihedrals between the atoms in this
        :class:`AtomGroup` and add them to the underlying
        :attr:`~AtomGroup.universe`.

        Parameters
        ----------
        vdwradii : dict, optional
            Dict relating atom types: vdw radii
        fudge_factor : float, optional
            The factor by which atoms must overlap each other to be considered
            a bond.  Larger values will increase the number of bonds found. [0.55]
        lower_bound : float, optional
            The minimum bond length. All bonds found shorter than this length
            will be ignored. This is useful for parsing PDB with altloc records
            where atoms with altloc A and B may be very close together and
            there should be no chemical bond between them. [0.1]

        See Also
        --------
        :func:`MDAnalysis.topology.guessers.guess_bonds`
        :func:`MDAnalysis.topology.guessers.guess_angles`
        :func:`MDAnalysis.topology.guessers.guess_dihedrals`


        .. versionadded:: 0.10.0
        .. versionchanged:: 0.20.2
           Now applies periodic boundary conditions when guessing bonds.
        .. versionchanged:: 2.5.0
           Corrected misleading docs, and now allows passing of `fudge_factor`
           and `lower_bound` arguments.
        r   )BondsAngles	Dihedralsr   )DefaultGuesserc                     	 t          | j        |          S # t          $ r%  |g           }|                     |           |cY S w xY w)z*either get *name* or create one from *cls*)r   r  rp   add_TopologyAttr)r   r  r%   r_   s       r    get_TopAttrz*AtomGroup.guess_bonds.<locals>.get_TopAttrG  s^    q{D111!   s2ww""4(((s    ,AAN)fudge_factorlower_boundr  vdwradiir  T)guessedangles	dihedrals)topologyattrsre  rf  rg  guesser.default_guesserrh  rM   guess_bondsr   rL   r   
_add_bondsguess_anglesr  guess_dihedralsrp  )r^   rn  rl  rm  re  rf  rg  rh  rk  guesserbbondattrr\  	angleattrddiheattrs                   r    rt  zAtomGroup.guess_bonds$  s@   @ 	<;;;;;;;;;<<<<<<	 	 	 !.%#
 
 
 
DJ,@AA;t}gu==At,,,  ,,Kx@@	Q---##DK00;t}k9EEAr"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )zThis :class:`AtomGroup` represented as a
        :class:`MDAnalysis.core.topologyobjects.Bond` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 2


        .. versionadded:: 0.11.0
        r   z6bond only makes sense for a group with exactly 2 atoms)r   r   r   Bondr   r   r   s    r    bondzAtomGroup.bonde  A     t99>>H   #DGT];;;r"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )zThis :class:`AtomGroup` represented as an
        :class:`MDAnalysis.core.topologyobjects.Angle` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 3


        .. versionadded:: 0.11.0
        r  z7angle only makes sense for a group with exactly 3 atoms)r   r   r   Angler   r   r   s    r    r  zAtomGroup.anglex  sA     t99>>I   $TWdm<<<r"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )zThis :class:`AtomGroup` represented as a
        :class:`~MDAnalysis.core.topologyobjects.Dihedral` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 4


        .. versionadded:: 0.11.0
           z:dihedral only makes sense for a group with exactly 4 atoms)r   r   r   Dihedralr   r   r   s    r    dihedralzAtomGroup.dihedral  sA     t99>>L   '???r"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )a  This :class:`AtomGroup` represented as an
        :class:`MDAnalysis.core.topologyobjects.ImproperDihedral` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 4


        .. versionadded:: 0.11.0
        r  z:improper only makes sense for a group with exactly 4 atoms)r   r   r   ImproperDihedralr   r   r   s    r    improperzAtomGroup.improper  sA     t99>>L   /GGGr"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )a   This :class:`AtomGroup` represented as an
        :class:`MDAnalysis.core.topologyobjects.UreyBradley` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 2


        .. versionadded:: 1.0.0
        r   z>urey bradley only makes sense for a group with exactly 2 atoms)r   r   r   UreyBradleyr   r   r   s    r    ureybradleyzAtomGroup.ureybradley  sA     t99>>P   *47DMBBBr"   c                     t          |           dk    rt          d          t          j        | j        | j                  S )zThis :class:`AtomGroup` represented as an
        :class:`MDAnalysis.core.topologyobjects.CMap` object

        Raises
        ------
        ValueError
            If the :class:`AtomGroup` is not length 5


        .. versionadded:: 1.0.0
           z6cmap only makes sense for a group with exactly 5 atoms)r   r   r   CMapr   r   r   s    r    cmapzAtomGroup.cmap  r  r"   
convert_to{trjname}_{frame}c                    t          | j                  dk    rt          d          | j        j        }||dk    r|dd         }nrt          |t          j                  rt          d          	 |j        }||ur"t          d
                    |                    |}n# t          $ r ||         }Y nw xY w|`t          j                            t          j                            |j                            \  }	}
|
                    |	|j                  }t%          j        |||ndd	
          }|                    dd          }t          |          dk    r|dk    rt          d          ||d}nt          |          dk    }	 t)          |||          } ||fd| j        i|5 }||                    | j                   nC|j        j        }	 |D ]}|                    | j                   	 ||          n# ||          w xY wddd           n# 1 swxY w Y   dS # t          t          f$ r Y nw xY w	 t1          |||nd          } ||fd| j        i|5 }|                    | j                   ddd           n# 1 swxY w Y   dS # t          t2          f$ r Y nw xY wt          d
                    |                    )a	  Write `AtomGroup` to a file.

        The output can either be a coordinate file or a selection, depending on
        the format.

        Examples
        --------

        .. code-block:: python

            >>> ag = u.atoms
            >>> ag.write('selection.ndx')  # Write a gromacs index file
            >>> ag.write('coordinates.pdb')  # Write the current frame as PDB
            >>> # Write the trajectory in XTC format
            >>> ag.write('trajectory.xtc', frames='all')
            >>> # Write every other frame of the trajectory in PBD format
            >>> ag.write('trajectory.pdb', frames=u.trajectory[::2])

        Parameters
        ----------
        filename : str, optional
            ``None``: create TRJNAME_FRAME.FORMAT from filenamefmt [``None``]
        file_format : str, optional
            The name or extension of a coordinate, trajectory, or selection
            file format such as PDB, CRD, GRO, VMD (tcl), PyMol (pml), Gromacs
            (ndx) CHARMM (str) or Jmol (spt); case-insensitive [PDB]
        filenamefmt : str, optional
            format string for default filename; use substitution tokens
            'trjname' and 'frame' ["%(trjname)s_%(frame)d"]
        bonds : str, optional
            how to handle bond information, especially relevant for PDBs.
            ``"conect"``: write only the CONECT records defined in the original
            file. ``"all"``: write out all bonds, both the original defined and
            those guessed by MDAnalysis. ``None``: do not write out bonds.
            Default is ``"conect"``.
        frames: array-like or slice or FrameIteratorBase or str, optional
            An ensemble of frames to write. The ensemble can be an list or
            array of frame indices, a mask of booleans, an instance of
            :class:`slice`, or the value returned when a trajectory is indexed.
            By default, `frames` is set to ``None`` and only the current frame
            is written. If `frames` is set to "all", then all the frame from
            trajectory are written.


        .. versionchanged:: 0.9.0 Merged with write_selection. This method can
            now write both selections out.
        .. versionchanged:: 0.19.0
            Can write multiframe trajectories with the 'frames' argument.
        r   z&Cannot write an AtomGroup with 0 atomsNr   z)The "frames" argument cannot be a number.zpThe trajectory of {} provided to the frames keyword attribute is different from the trajectory of the AtomGroup.)trjnameframePDBT)extkeep
multiframer   FznCannot explicitely set "multiframe" to False and request more than 1 frame with the "frames" keyword argument.)rz   r  r  zNo writer found for format: {})r   r   r   r   r2  r   r   r   r   r   rz   rp   ospathsplitextbasenamefilenamer  r	   r   r   r  writer3  get_selection_writer_forr#  )r^   r  file_formatfilenamefmtframesr   trj
trj_framestest_trajectoryr  r  r  writerwcurrent_frameru   s                   r    r  zAtomGroup.write  s   x tz??aEFFFm&>Vu__RRRJJ 011 	$ GHHH$"("3 ##--$%%+VF^^  
 $

 " ) ) ) [


) 7++BG,<,<S\,J,JKKLGS"))')KKH=*6E
 
 
 ZZd33
z??Q:#6#6H   ~"

 __q0
	#  F AA$,A&AA 	+Q>GGDJ''''$'FLM+!+ 0 0AGGDJ////0 M***M***	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ F I& 	 	 	D		 .)@++e F AA$,A&AA $Q
###$ $ $ $ $ $ $ $ $ $ $ $ $ $ $F ./ 	 	 	D	 9@@JJKKKsr   1B! !B65B6H+ 1*HH<	H
HHH"%H"+H?>H?J 'JJJJ/.J/r   c                    t          | j        |          }t          |          t          | j                  k    r"t          d                    |                    |j        dk    rt          j        |d          }n}|j        dk    rr|"t          d                    |                     ||          }|j        dk    r"t          d                    |                    t          j        |d          }| j        |         S )a/  
        Returns a sorted ``AtomGroup`` using a specified attribute as the key.

        Parameters
        ----------
        key: str, optional
            The name of the ``AtomGroup`` attribute to sort by (e.g. ``ids``,
            ``ix``. default= ``ix`` ).
        keyfunc: callable, optional
            A function to convert multidimensional arrays to a single
            dimension. This 1D array will be used as the sort key and
            is required when sorting with an ``AtomGroup`` attribute
            key which has multiple dimensions. Note: this argument
            is ignored when the attribute is one dimensional.

        Returns
        ----------
        :class:`AtomGroup`
            Sorted ``AtomGroup``.

        Example
        ----------

        .. doctest:: AtomGroup.sort

            >>> import MDAnalysis as mda
            >>> from MDAnalysisTests.datafiles import PDB_small
            >>> u = mda.Universe(PDB_small)
            >>> ag = u.atoms[[3, 2, 1, 0]]
            >>> ag.ix
            array([3, 2, 1, 0])
            >>> ag = ag.sort()
            >>> ag.ix
            array([0, 1, 2, 3])
            >>> ag.positions
            array([[-11.921,  26.307,  10.41 ],
                   [-11.447,  26.741,   9.595],
                   [-12.44 ,  27.042,  10.926],
                   [-12.632,  25.619,  10.046]], dtype=float32)
            >>> ag = ag.sort("positions", lambda x: x[:, 1])
            >>> ag.positions
            array([[-12.632,  25.619,  10.046],
                   [-11.921,  26.307,  10.41 ],
                   [-11.447,  26.741,   9.595],
                   [-12.44 ,  27.042,  10.926]], dtype=float32)

        Note
        ----------
        This uses a stable sort as implemented by
        `numpy.argsort(kind='stable')`.


        .. versionadded:: 2.0.0
        zpThe array returned by the attribute '{}' must have the same length as the number of atoms in the input AtomGroupr   r\  r]  NzThe {} attribute returns a multidimensional array. In order to sort it, a function returning a 1D array (to be used as the sort key) must be passed to the keyfunc argumentzMThe function assigned to the argument 'keyfunc':{} doesn't return a 1D array.)	r   r   r   r   rz   r   r   ra  	NameError)r^   keykeyfuncr  ordersortkeyss         r    sortzAtomGroup.sortn  s   n dj#&&s88s4:&&//5vc{{  
 8q==Js222EEX\\B CI&++	   ws||H}!! >>DfWoo   Jxh777Ez%  r"   r  )Nrb  rc  )NNr  N)r   N)%rS   r   r   r   r   r  rg   r   r  rJ   rd   r  rK   r'  r
   rF  rE  r;  rL   rN   rG   r3  rW  ra  rt  r  r  r  r  r  r  r   r   r  r  r  r   r   s   @r    r2   r2    
  s       V Vp8 8 8 8 85 5 5   X    X 	 	 X	 _; ; _;@ " " X" 	 	 X	 _
 
 _
 " " X" V!""    #" X 0  2 2 ! 2 * * X*X-
 -
 -
 -
^ > > X>@ * * * 0 0 X0. + + + " " X", ]' ' ]' / / X/4 y y y y yv(
 (
 (
T? ? ? ?B < < X<$ = = X=$ @ @ X@$ H H XH$ C C XC$ < < X<$ ,(899J 'SL SL SL SLjO! O! O! O! O! O! O! O!r"   r2   c                       e Zd ZdZd Zed             Zed             Zed             Zed             Z	ed             Z
e
j        d             Z
ed	             Zed
             ZddZdS )r3   a)  ResidueGroup base class.

    This class is used by a :class:`~MDAnalysis.core.universe.Universe` for
    generating its Topology-specific :class:`ResidueGroup` class. All the
    :class:`~MDAnalysis.core.topologyattrs.TopologyAttr` components are obtained
    from :class:`GroupBase`, so this class only includes ad-hoc methods
    specific to :class:`ResidueGroups<ResidueGroup>`.

    ResidueGroups can be compared and combined using group operators. See the
    list of these operators on :class:`GroupBase`.

    .. deprecated:: 0.16.2
       *Instant selectors* of Segments will be removed in the 1.0 release.
    .. versionchanged:: 1.0.0
       Removed instant selectors, use select_atoms instead
    .. versionchanged:: 2.1.0
       Indexing an ResidueGroup with ``None`` raises a ``TypeError``.
    c                 8    t           | j        | j        t          ffS r   )r&   r   r   r3   r   s    r    r  zResidueGroup.__reduce__      T]DG\BCCr"   c                     | j         }|j        |j        j                            | j                           }|                    |            |S )zAn :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
        :class:`ResidueGroup`.

        The :class:`Atoms<Atom>` are ordered locally by :class:`Residue` in the
        :class:`ResidueGroup`.  Duplicates are *not* removed.
        )r   r   r  r  residues2atoms_1dr   r  r^   r   ags      r    r   zResidueGroup.atoms  sF     MWQ[^55dh??@
 	""4(((	r"   c                 *    t          | j                  S )zNumber of :class:`Atoms<Atom>` present in this :class:`ResidueGroup`,
        including duplicate residues (and thus, duplicate atoms).

        Equivalent to ``len(self.atoms)``.
        r   r   r   s    r    r  zResidueGroup.n_atoms       4:r"   c                     | S )au  The :class:`ResidueGroup` itself.

        See Also
        --------
        copy : return a true copy of the :class:`ResidueGroup`


        .. versionchanged:: 0.19.0
           In previous versions, this returned a copy, but now
           the :class:`ResidueGroup` itself is returned. This should
           not affect any code but only speed up calculations.

        r$   r   s    r    rJ   zResidueGroup.residues  r   r"   c                      t          |           S )z_Number of residues in the :class:`ResidueGroup`.

        Equivalent to ``len(self)``.
        r  r   s    r    r  zResidueGroup.n_residues  r  r"   c                     | j         j        t          | j                           }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )znGet sorted :class:`SegmentGroup` of the unique segments present in
        the :class:`ResidueGroup`.
        Tr@  r>  r7  r<  r  r  s     r    rK   zResidueGroup.segments
  r  r"   c                    t          |t                    rt          j        |j        f          }n{t          |t
                    r|j        }n^	 d |D             }nP# t          $ rC d                    d	                    d |D                                 }t          |          d w xY wt          |t          j                  s]t          |          t          |           k    r=t          d                    t          |          t          |                               t          | |          D ]/\  }}| j        j        j                            |j        |           0d S )Nc                     g | ]	}|j         
S r$   )segindex)r   r  s     r    r   z)ResidueGroup.segments.<locals>.<listcomp>  r  r"   zECan only set ResidueGroup segments to Segment or SegmentGroup, not {}r  c              3   ^   K   | ](}t          |t                    t          |          V  )d S r   )r   r7   rR   r  s     r    r   z(ResidueGroup.segments.<locals>.<genexpr>$  r  r"   z/Incorrect size: {} for ResidueGroup of size: {})r   r7   r  r  r  r4   rU  rp   rz   r  r   r   r   r|  r   r  r  move_residuer   )r^   r  r  r   r  r  s         r    rK   zResidueGroup.segments  s{    c7## 	2?CL?33DD\** 	2>DD200C000! 	2 	2 	2..4f		 " "-0" " "  / /   ''T1	2 $	00 	SYY#d))5K5K6#c((CII..   dOO 	= 	=DAqM#&33AD!<<<<	= 	=r  c                 *    t          | j                  S )znNumber of unique segments present in the ResidueGroup.

        Equivalent to ``len(self.segments)``.
        r&  r   s    r    r'  zResidueGroup.n_segments7  r(  r"   c                 t    | j         dd         }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )a  Return a :class:`ResidueGroup` containing sorted and unique
        :class:`Residues<Residue>` only.

        Examples
        --------

        .. testsetup:: ResidueGroup.unique

            import MDAnalysis as mda
            from MDAnalysis.tests.datafiles import PSF, DCD
            u = mda.Universe(PSF, DCD)

        .. doctest:: ResidueGroup.unique

            >>> rg = u.residues[[2, 1, 2, 2, 1, 0]]
            >>> rg
            <ResidueGroup with 6 residues>
            >>> rg.ix
            array([2, 1, 2, 2, 1, 0])
            >>> rg2 = rg.unique
            >>> rg2
            <ResidueGroup with 3 residues>
            >>> rg2.ix
            array([0, 1, 2])
            >>> rg2.unique is rg2
            False


        .. versionadded:: 0.16.0
        .. versionchanged:: 0.19.0 If the :class:`ResidueGroup` is already
            unique, :attr:`ResidueGroup.unique` now returns the group itself
            instead of a copy.
        .. versionchanged:: 2.0.0
            This function now always returns a copy.
        NTr@  r>  r7  r<  r/  r  s     r    rE  zResidueGroup.unique?  L    J "111%#'Z #'Z (-_%*/&'r"   Fc                 D    |                      || j        j                  S )a}  Return a :class:`ResidueGroup` containing unique
        :class:`Residues<Residue>` only, with optional sorting.

        If the :class:`ResidueGroup` is unique, this is the group itself.

        Parameters
        ----------
        sorted: bool (optional)
            Whether or not the returned ResidueGroup should be sorted
            by resindex.

        Returns
        -------
        :class:`ResidueGroup`
            Unique ``ResidueGroup``

        Examples
        --------

        .. testsetup:: ResidueGroup.asunique

            import MDAnalysis as mda
            from MDAnalysis.tests.datafiles import PSF, DCD
            u = mda.Universe(PSF, DCD)

        .. doctest:: ResidueGroup.asunique

            >>> rg = u.residues[[2, 1, 2, 2, 1, 0]]
            >>> rg
            <ResidueGroup with 6 residues>
            >>> rg.ix
            array([2, 1, 2, 2, 1, 0])
            >>> rg2 = rg.asunique(sorted=True)
            >>> rg2
            <ResidueGroup with 3 residues>
            >>> rg2.ix
            array([0, 1, 2])
            >>> rg2.asunique() is rg2
            True


        .. versionadded:: 2.0.0
        r   r   )rP  r   rJ   r1  s     r    r;  zResidueGroup.asuniquek       X ~~V4=3I~JJJr"   Nr  )rS   r   r   r   r  rg   r   r  rJ   r  rK   rd   r'  rE  r;  r$   r"   r    r3   r3     s&        &D D D   X    X   X    X 	 	 X	 _= = _=@ " " X" ) ) X)V,K ,K ,K ,K ,K ,Kr"   r3   c                       e Zd ZdZd Zed             Zed             Zed             Zed             Z	ed             Z
ed             Zed	             ZddZdS )r4   aI  :class:`SegmentGroup` base class.

    This class is used by a :class:`~MDAnalysis.core.universe.Universe` for
    generating its Topology-specific :class:`SegmentGroup` class. All the
    :class:`~MDAnalysis.core.topologyattrs.TopologyAttr` components are obtained
    from :class:`GroupBase`, so this class only includes ad-hoc methods specific
    to :class:`SegmentGroups<SegmentGroup>`.

    :class:`SegmentGroups<SegmentGroup>` can be compared and combined using
    group operators. See the list of these operators on :class:`GroupBase`.

    .. deprecated:: 0.16.2
       *Instant selectors* of Segments will be removed in the 1.0 release.
    .. versionchanged:: 1.0.0
       Removed instant selectors, use select_atoms instead
    .. versionchanged:: 2.1.0
       Indexing an SegmentGroup with ``None`` raises a ``TypeError``.
    c                 8    t           | j        | j        t          ffS r   )r&   r   r   r4   r   s    r    r  zSegmentGroup.__reduce__  r  r"   c                     | j         }|j        |j        j                            | j                           }|                    |            |S )a*  An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
        :class:`SegmentGroup`.

        The :class:`Atoms<Atom>` are ordered locally by :class:`Residue`, which
        are further ordered by :class:`Segment` in the :class:`SegmentGroup`.
        Duplicates are *not* removed.
        )r   r   r  r  segments2atoms_1dr   r  r  s      r    r   zSegmentGroup.atoms  sF     MWQ[^55dh??@
 	""4(((	r"   c                 *    t          | j                  S )zNumber of atoms present in the :class:`SegmentGroup`, including
        duplicate segments (and thus, duplicate atoms).

        Equivalent to ``len(self.atoms)``.
        r  r   s    r    r  zSegmentGroup.n_atoms  r  r"   c                     | j         j        t          j        | j                           }|                    |            |S )a	  A :class:`ResidueGroup` of :class:`Residues<Residue>` present in this
        :class:`SegmentGroup`.

        The :class:`Residues<Residue>` are ordered locally by
        :class:`Segment` in the :class:`SegmentGroup`. Duplicates are *not*
        removed.
        )r   rJ   r   r  rT  r  r  s     r    rJ   zSegmentGroup.residues  s:     ]#BN4?$C$CD
 	""4(((	r"   c                 *    t          | j                  S )zNumber of residues present in this :class:`SegmentGroup`, including
        duplicate segments (and thus, residues).

        Equivalent to ``len(self.residues)``.
        r  r   s    r    r  zSegmentGroup.n_residues  s     4=!!!r"   c                     | S )au  The :class:`SegmentGroup` itself.

        See Also
        --------
        copy : return a true copy of the :class:`SegmentGroup`


        .. versionchanged:: 0.19.0
           In previous versions, this returned a copy, but now
           the :class:`SegmentGroup` itself is returned. This should
           not affect any code but only speed up calculations.

        r$   r   s    r    rK   zSegmentGroup.segments  r   r"   c                      t          |           S )z_Number of segments in the :class:`SegmentGroup`.

        Equivalent to ``len(self)``.
        r  r   s    r    r'  zSegmentGroup.n_segments  r  r"   c                 t    | j         dd         }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )a  Return a :class:`SegmentGroup` containing sorted and unique
        :class:`Segments<Segment>` only.

        Examples
        --------

        .. testsetup:: SegmentGroup.unique

            from MDAnalysis.tests.datafiles import CONECT
            import MDAnalysis as mda
            u = mda.Universe(CONECT)

        .. doctest:: SegmentGroup.unique

            >>> sg = u.segments[[2, 1, 2, 2, 1, 0]]
            >>> sg
            <SegmentGroup with 6 segments>
            >>> sg.ix
            array([2, 1, 2, 2, 1, 0])
            >>> sg2 = sg.unique
            >>> sg2
            <SegmentGroup with 3 segments>
            >>> sg2.ix
            array([0, 1, 2])
            >>> sg2.unique is sg2
            False


        .. versionadded:: 0.16.0
        .. versionchanged:: 0.19.0 If the :class:`SegmentGroup` is already
            unique, :attr:`SegmentGroup.unique` now returns the group itself
            instead of a copy.
        .. versionchanged:: 2.0.0
            This function now always returns a copy.
        NTr@  r>  r7  r<  r/  r  s     r    rE  zSegmentGroup.unique  r  r"   Fc                 D    |                      || j        j                  S )ay  Return a :class:`SegmentGroup` containing unique
        :class:`Segments<Segment>` only, with optional sorting.

        If the :class:`SegmentGroup` is unique, this is the group itself.

        Parameters
        ----------
        sorted: bool (optional)
            Whether or not the returned SegmentGroup should be sorted
            by segindex.

        Returns
        -------
        :class:`SegmentGroup`
            Unique ``SegmentGroup``

        Examples
        --------

        .. testsetup:: SegmentGroup.asunique

            from MDAnalysis.tests.datafiles import CONECT
            import MDAnalysis as mda
            u = mda.Universe(CONECT)

        .. doctest:: SegmentGroup.asunique

            >>> sg = u.segments[[2, 1, 2, 2, 1, 0]]
            >>> sg
            <SegmentGroup with 6 segments>
            >>> sg.ix
            array([2, 1, 2, 2, 1, 0])
            >>> sg2 = sg.asunique(sorted=True)
            >>> sg2
            <SegmentGroup with 3 segments>
            >>> sg2.ix
            array([0, 1, 2])
            >>> sg2.asunique() is sg2
            True


        .. versionadded:: 2.0.0
        r  )rP  r   rK   r1  s     r    r;  zSegmentGroup.asunique+  r  r"   Nr  )rS   r   r   r   r  rg   r   r  rJ   r  rK   r'  rE  r;  r$   r"   r    r4   r4     s        &D D D   X"   X   X  " " X"   X    X ) ) X)V,K ,K ,K ,K ,K ,Kr"   r4   c                        e Zd ZdZd Z fdZd Zd Zd Zd Z	e
d             Zd	 Zed
             Zed             Zed             Z xZS )r;   zBase class from which a :class:`~MDAnalysis.core.universe.Universe`\ 's
    Component class is built.

    Components are the individual objects that are found in Groups.
    c                 t    t          |t          j                  st          d          || _        || _        d S )Nz1Component can only be indexed by a single integer)r   r   r   r   r   r   )r^   r   r   s      r    r   zComponentBase.__init__b  s@    "g.// 	C   r"   c                    t          |           j        }|t          v ryt          |         }||j        k    r7||j        k    r,d}t          |                    |||j                            d}t          |                    |j                            t          t          |           
                    |          S )Nz:{selfcls} has no attribute {attr}. Do you mean {singular}?)r   r_   rj   r  r  )rR   rS   r   rf   rj   rp   rz   r   r{   r;   r   r  s        r    r   zComponentBase.__getattr__l  s    t**%?""!$'Cs|##(<(<.  %JJ 'dS\      N!#**cl*"C"CDDD--99$???r"   c                 `    | j         |j         k    rt          d          | j        |j        k     S Nz%Can't compare different level objectsr   r   r   r  s     r    __lt__zComponentBase.__lt__  s/    :$$CDDDw!!r"   c                 `    | j         |j         k    rt          d          | j        |j        k    S r  r  r  s     r    r   zComponentBase.__eq__  s/    :$$CDDDw%(""r"   c                     | |k     S r   r$   r  s     r    __ne__zComponentBase.__ne__  s    5=  r"   c                 *    t          | j                  S r   )r   r   r   s    r    r   zComponentBase.__hash__  s    DG}}r"   c                     |j         }| j                            t          j        | j         |g          | j                  S )a`  Concatenate the Component with another Component or Group of the
        same level.

        Parameters
        ----------
        other : Component or Group
            Component or Group with `other.level` same as `self.level`

        Returns
        -------
        Group
            Group with elements of `self` and `other` concatenated
        )r   r   r  r   r  r   r  s      r    r  zComponentBase.__add__  s=     ~z  NDM40114=
 
 	
r"   c                     |dk    r%| j                             | j        | j                  S t	          d                    t          |           j        t          |          j                            )a^  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
        r   r  )r   r  r   r   r   rz   rR   rS   r  s     r    r  zComponentBase.__radd__  sf     A:::$$T]DMBBB!!'JJ'e)=" "  r"   c                     | j         S r   r-  r   s    r    r   zComponentBase.universe  s	    wr"   c                     | j         S )a(  Unique index of this component.

        If this component is an :class:`Atom`, this is the index of the
        :class:`Atom`.
        If it is a :class:`Residue`, this is the index of the :class:`Residue`.
        If it is a :class:`Segment`, this is the index of the :class:`Segment`.
        r/  r   s    r    r   zComponentBase.ix  s     xr"   c                 N    t          j        | j        gt           j                  S )zUnique index of this component as an array.

        This method gives a consistent API between components and groups.

        See Also
        --------
        ix
        r   )r   r   r   r   r   s    r    r   zComponentBase.ix_array  s     x	1111r"   )rS   r   r   r   r   r   r  r   r  r   r   r  r  rg   r   r   r   r   r   s   @r    r;   r;   Z  s          @ @ @ @ @(" " "
# # #
! ! !   
 
 
(  0   X   X 	2 	2 X	2 	2 	2 	2 	2r"   r;   c                   <    e Zd ZdZd Zd Z fdZed             Zej	        d             Zed             Z
e
j	        d             Z
ed	             Zej	        d
             Zed             Zej	        d             Zed             Zej	        d             Z xZS )r5   ap  :class:`Atom` base class.

    This class is used by a :class:`~MDAnalysis.core.universe.Universe` for
    generating its Topology-specific :class:`Atom` class. All the
    :class:`~MDAnalysis.core.topologyattrs.TopologyAttr` components are obtained
    from :class:`ComponentBase`, so this class only includes ad-hoc methods
    specific to :class:`Atoms<Atom>`.
    c                 b   d                     | j        dz             }t          | d          r|d                     | j                  z  }t          | d          r|d                     | j                  z  }t          | d          r|d                     | j                  z  }t          | d	          r|d
                     | j                  z  }t          | d          r|d                     | j                  z  }t          | d          r|d                     | j                  z  }|dz   S )Nz	<Atom {}:r   r   {}rR   z of type {}resnamez of resname {},residz	 resid {}segidz and segid {}altLocz and altLoc {}>)	rz   r   ry   r  rR   r  r  r  r  r^   mes     r    r  zAtom.__repr__  s,   !,,4   	*%,,ty)))B4   	2-&&ty111B4## 	9#**4<888B4!! 	1+$$TZ000B4!! 	5/((444B4"" 	7"))$+666BCxr"   c                 8    t           | j        | j        t          ffS r   )r&   r   r   r5   r   s    r    r  zAtom.__reduce__  s    T]DGT:;;r"   c                     ddd}||v rt          d||         z             |dk    rt          d          t          t          |                               |          S )NrN   rG   )rQ   rO   r  rP   r  )r   r{   r5   r   )r^   r_   r3  r~   s      r    r   zAtom.__getattr__  si    &::2::54@AAAZ@AAAT4  ,,T222r"   c                 P    | j         j        | j         j        j        |                   S r   )r   rJ   r  rT  r   s    r    rH   zAtom.residue      }%dm&=&H&NOOr"   c                     t          |t                    s/t          d                    t	          |                              | j        j        j                            | j	        |j
                   d S )Nz,Can only set Atom residue to Residue, not {})r   r6   r   rz   rR   r   r  r  r  r   r  r$  s     r    rH   zAtom.residue  sh    #w'' 	6$s))$$   	",,TWclCCCCCr"   c                 P    | j         j        | j         j        j        |                   S r   r   rK   r  rU  r   s    r    rI   zAtom.segment  r  r"   c                      t          d          )Nz;Cannot set atom segment.  Segments are assigned to Residuesr"  r$  s     r    rI   zAtom.segment  s    !L
 
 	
r"   c                 h    | j         j        j        j        | j                                                 S )a/  Coordinates of the atom.

        The position can be changed by assigning an array of length (3,).

        .. note:: changing the position is not reflected in any files; reading
                  any frame from the trajectory will replace the change with
                  that from the file

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the underlying :class:`~MDAnalysis.coordinates.timestep.Timestep`
            does not contain
            :attr:`~MDAnalysis.coordinates.timestep.Timestep.positions`.
        )r   r2  r3  rL   r   r4  r   s    r    rP   zAtom.position  s(    " }'*4TW=BBDDDr"   c                 J    || j         j        j        j        | j        d d f<   d S r   r3  )r^   rc   s     r    rP   zAtom.position)  s'    <B #-dgqqqj999r"   c                 l    | j         j        j        }|j        | j                                                 S )a0  Velocity of the atom.

        The velocity can be changed by assigning an array of shape ``(3,)``.

        .. note:: changing the velocity is not reflected in any files; reading
                  any frame from the trajectory will replace the change with
                  that from the file

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the underlying :class:`~MDAnalysis.coordinates.timestep.Timestep`
            does not contain
            :attr:`~MDAnalysis.coordinates.timestep.Timestep.velocities`.
        )r   r2  r3  rN   r   r4  r7  s     r    rQ   zAtom.velocity-  s,    " ]%(}TW%**,,,r"   c                 N    | j         j        j        }||j        | j        d d f<   d S r   r9  r5  s      r    rQ   zAtom.velocityA  r:  r"   c                 l    | j         j        j        }|j        | j                                                 S )a#  Force on the atom.

        The force can be changed by assigning an array of shape ``(3,)``.

        .. note:: changing the force is not reflected in any files; reading any
                  frame from the trajectory will replace the change with that
                  from the file

        Raises
        ------
        ~MDAnalysis.exceptions.NoDataError
            If the underlying :class:`~MDAnalysis.coordinates.timestep.Timestep`
            does not contain
            :attr:`~MDAnalysis.coordinates.timestep.Timestep.forces`.
        )r   r2  r3  rG   r   r4  r7  s     r    rO   z
Atom.forceF  s,    " ]%(y!&&(((r"   c                 N    | j         j        j        }||j        | j        d d f<   d S r   r<  r5  s      r    rO   z
Atom.forceZ  r>  r"   )rS   r   r   r   r  r  r   rg   rH   rd   rI   rP   rQ   rO   r   r   s   @r    r5   r5     s           < < <3 3 3 3 3 P P XP ^D D ^D P P XP ^
 
 ^

 E E XE$ _C C _C - - X-& _+ + _+ ) ) X)& \' ' \' ' ' ' 'r"   r5   c                   j    e Zd ZdZd Zd Zed             Zed             Zej	        d             ZdS )r6   a|  :class:`Residue` base class.

    This class is used by a :class:`~MDAnalysis.core.universe.Universe` for
    generating its Topology-specific :class:`Residue` class. All the
    :class:`~MDAnalysis.core.topologyattrs.TopologyAttr` components are obtained
    from :class:`ComponentBase`, so this class only includes ad-hoc methods
    specific to :class:`Residues<Residue>`.
    c                     d}t          | d          r|d                    | j                  z  }t          | d          r|d                    | j                  z  }|dz   S )Nz<Residuer  z {},r  r  r  )ry   rz   r  r  r  s     r    r  zResidue.__repr__j  sd    4## 	.&-----B4!! 	+%,,tz***BCxr"   c                 8    t           | j        | j        t          ffS r   )r&   r   r   r6   r   s    r    r  zResidue.__reduce__s      T]DGW=>>r"   c                     | j         j        | j         j        j        |          d                  }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )z`An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
        :class:`Residue`.
        r   Tr@  r>  r7  r<  r   r   r  r   r   r^   r  s     r    r   zResidue.atomsv  [    
 ] !8!@!Fq!IJ $	* $	*%'	/"')	#$	r"   c                 P    | j         j        | j         j        j        |                   S )z6The :class:`Segment` this :class:`Residue` belongs to.r  r   s    r    rI   zResidue.segment  s!     }%dm&=&H&NOOr"   c                     t          |t                    s/t          d                    t	          |                              | j        j        j                            | j	        |j
                   d S )Nz/Can only set Residue segment to Segment, not {})r   r7   r   rz   rR   r   r  r  r  r   r  r$  s     r    rI   zResidue.segment  sh    #w'' 	6$s))$$   	"//FFFFFr"   N)
rS   r   r   r   r  r  rg   r   rI   rd   r$   r"   r    r6   r6   `  s           ? ? ? 	 	 X	 P P XP ^G G ^G G Gr"   r6   c                   J    e Zd ZdZd Zd Zed             Zed             ZdS )r7   a  :class:`Segment` base class.

    This class is used by a :class:`~MDAnalysis.core.universe.Universe` for
    generating its Topology-specific :class:`Segment` class. All the
    :class:`~MDAnalysis.core.topologyattrs.TopologyAttr` components are obtained
    from :class:`ComponentBase`, so this class only includes ad-hoc methods
    specific to :class:`Segments<Segment>`.

    .. deprecated:: 0.16.2
       *Instant selectors* of :class:`Segments<Segment>` will be removed in the
       1.0 release.
    .. versionchanged:: 1.0.0
       Removed instant selectors, use either segment.residues[...] to select
       residue by number, or segment.residues[segment.residue.resnames = ...]
       to select by resname.
    c                 j    d}t          | d          r|d                    | j                  z  }|dz   S )Nz<Segmentr  r  r  )ry   rz   r  r  s     r    r  zSegment.__repr__  s:    4!! 	+%,,tz***BCxr"   c                 8    t           | j        | j        t          ffS r   )r&   r   r   r7   r   s    r    r  zSegment.__reduce__  r   r"   c                     | j         j        | j         j        j        |          d                  }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )z`An :class:`AtomGroup` of :class:`Atoms<Atom>` present in this
        :class:`Segment`.
        r   Tr@  r>  r7  r<  r  r  s     r    r   zSegment.atoms  r  r"   c                     | j         j        | j         j        j        |          d                  }d|j        d<   d|j        d<   ||j        d<   ||j        d<   |S )zhA :class:`ResidueGroup` of :class:`Residues<Residue>` present in this
        :class:`Segment`.
        r   Tr@  r>  r7  r<  )r   rJ   r  rT  r   r  s     r    rJ   zSegment.residues  s`    
 ]#M#.t4Q7
 !%	* $	*%'	/"')	#$	r"   N)	rS   r   r   r   r  r  rg   r   rJ   r$   r"   r    r7   r7     sr         "  ? ? ? 	 	 X	   X  r"   r7   >   r   r   r   r~   _base_group_lastupdate_selectionsis_uptodaterY   _ensure_updatedupdate_selectionc                        e Zd ZdZd Z fdZed             Zej        d             Zd Z	d Z
d Z fd	Zed
             Zd Z xZS )r(   a  :class:`AtomGroup` subclass that dynamically updates its selected atoms.

    Accessing any attribute/method of an :class:`UpdatingAtomGroup` instance
    triggers a check for the last frame the group was updated. If the last
    frame matches the current trajectory frame, the attribute is returned
    normally; otherwise the group is updated (the stored selections are
    re-applied), and only then is the attribute returned.


    .. versionadded:: 0.16.0
    c                     |j         | _        || _        || _        || _        d| _        |j        | _        | j        r|                                  dS dS )a'  

        Parameters
        ----------
        base_group : :class:`AtomGroup`
            group on which *selections* are to be applied.
        selections : a tuple of :class:`~MDAnalysis.core.selection.Selection`
            instances selections ready to be applied to *base_group*.
        N)r   r   r  _selection_stringsr  r  rY   r  )r^   
base_groupr*   stringss       r    r   zUpdatingAtomGroup.__init__  sh     %%")%(7 	#   """""	# 	#r"   c                 Z   | j         | j        }|rCt          fd|dd         D             |d                                                 j        }n t          j        g t
          j                  }t          t          |           
                    || j                   d| _        dS )z
        Forces the reevaluation and application of the group's selection(s).

        This method is triggered automatically when accessing attributes, if
        the last update occurred under a different trajectory frame.
        c                 :    g | ]}|                               S r$   rN  )r   rP  bgs     r    r   z6UpdatingAtomGroup.update_selection.<locals>.<listcomp>  s#    888ciimm888r"   r   Nr   r   T)r  r  rz  rO  r   r   r   r   r{   r(   r   r   r  )r^   selsr   r  r~   s      @r    r  z"UpdatingAtomGroup.update_selection  s      	-8888tABBx888$q'--:K:KLLOBB"BG,,,B 	&&//DMBBBr"   c                 n    	 | j         j        j        | j        k    S # t          $ r | j        dk    cY S w xY w)a  
        Checks whether the selection needs updating based on frame number only.

        Modifications to the coordinate data that render selections stale are
        not caught, and in those cases :attr:`is_uptodate` may return an
        erroneous value.

        Returns
        -------
        bool
            ``True`` if the group's selection is up-to-date, ``False``
            otherwise.
        r   r   r2  r  r  rp   r   s    r    r  zUpdatingAtomGroup.is_uptodate  sL    	*=+1T5EEE 	* 	* 	*#r))))	*s    44c                 z    |r1	 | j         j        j        | _        d S # t          $ r d| _        Y d S w xY wd | _        d S )Nr   r  )r^   r}   s     r    r  zUpdatingAtomGroup.is_uptodate.  sa     	$&#'=#;#A   ! & & &#%    &  $Ds    11c                 @    | j         }|s|                                  |S )z
        Checks whether the selection needs updating and updates it if needed.

        Returns
        -------
        bool
            ``True`` if the group was already up-to-date, ``False`` otherwise.
        )r  r  )r^   statuss     r    r  z!UpdatingAtomGroup._ensure_updated9  s+     ! 	$!!###r"   c                     |                     d          s|t          v s|                                  t                              | |          S )Nru   )rx   _UAG_SHORTCUT_ATTRSr  r   __getattribute__r
  s     r    r"  z"UpdatingAtomGroup.__getattribute__G  sK     $$ 	#0C(C(C  """&&tT222r"   c                 \    t           | j                                        | j        | j        ffS r   )r/   r  r  r  r  r   s    r    r  zUpdatingAtomGroup.__reduce__P  s4      ++-- '
 	
r"   c                 j   t          t          |                                           }| j        s|S d                    d                    | j                            }| j        | j        j        u rd}nd}d                    |d d         dt          | j                  dk    d          ||          S )	Nz'{}'z' + 'zthe entire Universe.zanother AtomGroup.z{}, with selection{} {} on {}>r   r  r   )
r{   r(   r  r  rz   r  r  r   r   r   )r^   basestrr  basegrpr~   s       r    r  zUpdatingAtomGroup.__repr__^  s    )40099;;& 	N}}W\\$*ABBCC t}222,GG*G/66CRCLD+,,1334	
 
 	
r"   c                     | dd         S )a  Get a *static* :class:`AtomGroup` identical to the group of currently
        selected :class:`Atoms<Atom>` in the :class:`UpdatingAtomGroup`.


        By returning a *static* :class:`AtomGroup` it becomes possible to
        compare the contents of the group *between* trajectory frames. See the
        Example below.


        Note
        ----
        The :attr:`atoms` attribute of an :class:`UpdatingAtomGroup` behaves
        differently from :attr:`AtomGroup.atoms`: the latter returns the
        :class:`AtomGroup` itself whereas the former returns a
        :class:`AtomGroup` and not an :class:`UpdatingAtomGroup` (for this, use
        :meth:`UpdatingAtomGroup.copy`).


        Example
        -------
        The static :attr:`atoms` allows comparison of groups of atoms between
        frames. For example, track water molecules that move in and out of a
        solvation shell of a protein

        .. code-block:: python

            u = mda.Universe(TPR, XTC)
            water_shell = u.select_atoms("name OW and around 3.5 protein",
                                         updating=True)
            water_shell_prev = water_shell.atoms

            for ts in u.trajectory:
                exchanged = water_shell - water_shell_prev

            print(ts.time, "waters in shell =", water_shell.n_residues)
            print(ts.time, "waters that exchanged = ", exchanged.n_residues)
            print(ts.time, "waters that remained bound = ",
                  water_shell.n_residues - exchanged.n_residues)

            water_shell_prev = water_shell.atoms

        By remembering the atoms of the current time step in
        `water_shell_prev`, it becomes possible to use the :meth:`subtraction
        of AtomGroups<AtomGroup.subtract>` to find the water molecules that
        changed.


        See Also
        --------
        copy : return a true copy of the :class:`UpdatingAtomGroup`

        Nr$   r   s    r    r   zUpdatingAtomGroup.atomsq  s    l AAAwr"   c                 B    t          | j        | j        | j                  S )ziGet another :class:`UpdatingAtomGroup` identical to this one.


        .. versionadded:: 0.19.0
        )r(   r  r  r  r   s    r    r4  zUpdatingAtomGroup.copy  s&     !d.0G
 
 	
r"   )rS   r   r   r   r   r  rg   r  rd   r  r"  r  r  r   r4  r   r   s   @r    r(   r(     s        
 
&# # #.         & * * X*& $ $ $  3 3 3
 
 

 
 
 
 
& 5 5 X5n
 
 
 
 
 
 
r"   r(   Level)r  rj   r  rZ  rH   rI   c                        fd}|S )a\  Decorator to check if all :class:`AtomGroup` arguments have certain
    attributes

    Example
    -------
    When used to wrap a function, will check all :class:`AtomGroup` arguments
    for the listed requirements

    @requires('masses', 'charges')
    def mass_times_charge(atomgroup):
        return atomgroup.masses * atomgroup.charges
    c                 J     t          j                    fd            }|S )Nc            	          | D ]ct          t                    rLfdD             }|r<t          d                    j        d                    |                              d | i |S )Nc                 4    g | ]}t          |          |S r$   )ry   )r   r_   r\  s     r    r   zErequires.<locals>.require_dec.<locals>.check_args.<locals>.<listcomp>  s(    NNNWQ=M=MNtNNNr"   zR{funcname} failed. AtomGroup is missing the following required attributes: {attrs}r  )funcnameattrs)r   r2   r   rz   rS   r  )r   r   missingr\  r/  r   s      @r    
check_argsz1requires.<locals>.require_dec.<locals>.check_args  s      a++ NNNNNNNG )228&)-&*ii&8&8 39 3 3   4((((r"   r   )r   r1  r/  s   ` r    require_deczrequires.<locals>.require_dec  s?    				) 	) 	) 	) 	) 
		)  r"   r$   )r/  r2  s   ` r    requiresr3    s$        ( r"   )Dr   collectionsr   numpyr   r   r  r   r  rn   r   r   r   r   r   r   libr	   lib.utilr
   r   r   r   r   r   r   r   r`  r   r   r*   r   r  r   
exceptionsr   r   _get_readersr   r   r!   r&   r/   rC   r   r8   r   rX   r   r   r   r:   r2   r3   r4   total_orderingr;   r5   r6   r7   r!  r(   _Level	ATOMLEVELRESIDUELEVELSEGMENTLEVELr   r3  r$   r"   r    <module>r?     sF  0D DJ # " " " " "              				                                          ! ! ! ! ! !       1 1 1 1 1 1 1 1 ? ? ? ? ? ?       $ $ $ $ $ $       ; ; ; ; ; ; ; ;  
  = = =  DXE XE XE XE XEV XE XE XEvQ Q Q Q Q6 Q Q Qh    V     &	 	 	  4\< \< \< \< \< \< \< \<~>}! }! }! }! }!	 }! }! }!@.WK WK WK WK WK9 WK WK WKt}K }K }K }K }K9 }K }K }K@ {2 {2 {2 {2 {2L {2 {2 {2|D' D' D' D' D'= D' D' D'N.G .G .G .G .Gm .G .G .Gb3 3 3 3 3m 3 3 3r   $U
 U
 U
 U
 U
	 U
 U
 U
t 
G;;;	<	<F64++	vi,77vi,77
	! ! " " " " "r"   