
     iQ                       d Z ddlZddlmZ ddlmZmZmZ ddlm	Z	 e	rddl
mZ ddlmZmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZmZ ddlmZ ddlZi Z ej        dd          ed<   	  ej        dd          ed<   n# e$ r Y nw xY wer ej        dd          ed<   [	 	 	 dJdedee          dee!         dedef
dZ"ddlm#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z8 deej9                 de dej9        fd Z: ed!d"d#d#d$%          	 	 	 dJd!eej9        d&f         d"eej9        d&f         d'eej9                 deej9                 dedej9        fd(            Z; ed!d#d$)          	 	 	 dJd!eej9        d&f         d'eej9                 deej9                 dedej9        f
d*            Z< ed!d"d#d#d#d$+          	 	 	 	 	 dKd!eej9        d&f         d"eej9        d&f         d,e=d-ee=         d'eej9                 d.ee         d/ee>         dee         fd0            Z?	 	 	 dLd!ej9        d"ej9        d,e=d-ee=         d'eej9                 d.ee         defd1Z@ ed!d"d#d#d#d$+          	 	 	 	 dMd!eej9        d&f         d"eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         dee         fd2            ZA ed!d"d#d#d#d$+          	 	 	 	 dMd!eej9        d&f         d"eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         dee         fd3            ZB ed!d"d#d#d#d$+          	 	 	 dNd!eej9        d&f         d"eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         fd4            ZC ed!d#d#d#d$+          	 	 	 	 	 dKd!eej9        d&f         d,e=d-ee=         d'eej9                 d.ee         d/ee>         dee         fd5            ZD	 	 	 dLd!ej9        d,e=d-ee=         d'eej9                 d.ee         f
d6ZE ed!d#d#d$7          	 	 	 	 dMd!eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         dee         fd8            ZF ed!d#d#d$7          	 	 	 	 dMd!eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         dee         fd9            ZG ed!d#d#d$7          	 	 	 dNd!eej9        d&f         d,e=d-ee=         d'eej9                 d/ee>         f
d:            ZH ed;          dOd<            ZI ed;          dOd=            ZJ ed>d?d$@          	 	 	 dJd>eej9        d&f         d?eej9        d&f         d'eej9                 deej9                 dedej9        fdA            ZK ed>d?dBd$@          	 	 	 dJd>eej9        d&f         d?eej9        d&f         dBeej9        d&f         d'eej9                 deej9                 dedej9        fdC            ZL ed>d?dBdDd$@          	 	 	 dJd>eej9        d&f         d?eej9        d&f         dBeej9        d&f         dDeej9        d&f         d'eej9                 deej9                 dedej9        fdE            ZM ed;d$@          	 	 dPd;eej9        d&f         d'eej9                 dedej9        fdF            ZN edGd#d#H          dGej9        d'ej9        dej9        fdI            ZOdS )Qu;  Fast distance array computation --- :mod:`MDAnalysis.lib.distances`
===================================================================

Fast C-routines to calculate arrays of distances or angles from coordinate
arrays. Distance functions can accept a NumPy :class:`np.ndarray` or an
:class:`~MDAnalysis.core.groups.AtomGroup`. Many of the functions also exist
in parallel versions, which typically provide higher performance than the
serial code. The boolean attribute `MDAnalysis.lib.distances.USED_OPENMP` can
be checked to see if OpenMP was used in the compilation of MDAnalysis.

Selection of acceleration ("backend")
-------------------------------------

All functions take the optional keyword `backend`, which determines the type of
acceleration. Currently, the following choices are implemented (`backend` is
case-insensitive):

.. Table:: Available *backends* for accelerated distance functions.

   ========== ========================= ======================================
   *backend*  module                    description
   ========== ========================= ======================================
   "serial"   :mod:`c_distances`        serial implementation in C/Cython

   "OpenMP"   :mod:`c_distances_openmp` parallel implementation in C/Cython
                                        with OpenMP

   "distopia"  `_distopia`              SIMD-accelerated implementation
                                        with the `distopia`_ library
   ========== ========================= ======================================


Use of the distopia library
---------------------------

MDAnalysis has developed a standalone library, `distopia`_ for accelerating
the distance functions in this module using explicit SIMD vectorisation.
This can provide many-fold speedups in calculating distances. Distopia is
under active development and as such only a selection of functions in this
module are covered. Consult the following table to see if the function
you wish to use is covered by distopia. For more information see the
`distopia documentation`_.

.. table:: Functions available using the `distopia`_ backend.
   :align: center

   +-------------------------------------------------------+
   | Functions                                             |
   +=======================================================+
   | :func:`MDAnalysis.lib.distances.calc_bonds`           |
   +-------------------------------------------------------+
   | :func:`MDAnalysis.lib.distances.calc_angles`          |
   +-------------------------------------------------------+
   | :func:`MDAnalysis.lib.distances.calc_dihedrals`       |
   +-------------------------------------------------------+
   | :func:`MDAnalysis.lib.distances.distance_array`       |
   +-------------------------------------------------------+
   | :func:`MDAnalysis.lib.distances.self_distance_array`  |
   +-------------------------------------------------------+

If `distopia`_ is installed, the functions in this table will accept the key
'distopia' for the `backend` keyword argument. The variable
:data:`HAS_DISTOPIA` is set to ``True`` if distopia is available.

If the distopia backend is selected the `distopia` library will be used to
calculate the distances. Note that for functions listed in this table
**distopia is not the default backend and must be explicitly selected.**


.. Note::
    Due to the use of Instruction Set Architecture (`ISA`_) specific SIMD
    intrinsics in distopia via `HWY`_, the precision of your results may
    depend on the ISA available on your machine. However, in all tested cases
    distopia satisfied the accuracy thresholds used to the functions in this
    module. Please document any issues you encounter with distopia's accuracy
    in the `relevant distopia issue`_ on the MDAnalysis GitHub repository.

.. _distopia: https://github.com/MDAnalysis/distopia
.. _distopia documentation: https://www.mdanalysis.org/distopia
.. _ISA: https://en.wikipedia.org/wiki/Instruction_set_architecture
.. _HWY: https://github.com/google/highway
.. _relevant distopia issue: https://github.com/MDAnalysis/mdanalysis/issues/3915

.. versionadded:: 0.13.0
.. versionchanged:: 2.3.0
   Distance functions can now accept an
   :class:`~MDAnalysis.core.groups.AtomGroup` or an :class:`np.ndarray`
.. versionchanged:: 2.5.0
   Interface to the `distopia`_ package added.
.. versionchanged:: 2.9.0
   Distopia support greatly expanded (with distopia ≥ 0.4.0).

Constants
---------
.. data:: HAS_DISTOPIA

   This variable is ``True`` if the :mod:`distopia` package has been
   installed and is available as a `backend`. Otherwise it is
   ``False``.

Functions
---------
.. autofunction:: distance_array
.. autofunction:: self_distance_array
.. autofunction:: capped_distance
.. autofunction:: self_capped_distance
.. autofunction:: calc_bonds
.. autofunction:: calc_angles
.. autofunction:: calc_dihedrals
.. autofunction:: apply_PBC
.. autofunction:: transform_RtoS
.. autofunction:: transform_StoR
.. autofunction:: augment_coordinates(coordinates, box, r)
.. autofunction:: undo_augment(results, translation, nreal)
.. autofunction:: minimize_vectors(vectors, box)

    N)UnionOptionalCallable)TYPE_CHECKING   )	AtomGroup   )check_coords	check_box)triclinic_vectors)augment_coordinatesundo_augment)FastNS)_minimize_vectors_ortho_minimize_vectors_triclinic)HAS_DISTOPIAz.c_distanceszMDAnalysis.lib)packageserialz.c_distances_openmpopenmpz
._distopiadistopiafuncnameargskwargsbackendreturnc                 <   ||nt                      }||nt                      }|                                }	 t          t          |         |           }n@# t
          $ r3 d|  d| dt                                           }t          |          dw xY w ||i |S )z8Helper function to select a backend function `funcname`.Nz	Function z not available with backend z try one of: )tupledictlowergetattr
_distancesKeyErrorkeys
ValueError)r   r   r   r   funcerrmsgs         b/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/lib/distances.py_runr(      s     #44D)VVtvvFmmooG+z'*H55 + + +/ / /g / /%??,,/ / 	   d*+ 4    s   A =B)_UINT64_MAXcalc_distance_arraycalc_distance_array_orthocalc_distance_array_tricliniccalc_self_distance_arraycalc_self_distance_array_ortho"calc_self_distance_array_tricliniccoord_transformcalc_bond_distancecalc_bond_distance_orthocalc_bond_distance_triclinic
calc_anglecalc_angle_orthocalc_angle_tricliniccalc_dihedralcalc_dihedral_orthocalc_dihedral_triclinic	ortho_pbctriclinic_pbc)OPENMP_ENABLEDresultshapec                 (   |  t          j        |t           j                  S | j        |k    r(t	          d                    || j                            | j        t           j        k    r't          d                    | j                            | S )a'  Check if the result array is ok to use.

    The `result` array must meet the following requirements:
      * Must have a shape equal to `shape`.
      * Its dtype must be ``numpy.float64``.

    Paramaters
    ----------
    result : numpy.ndarray or None
        The result array to check. If `result` is `None``, a newly created
        array of correct shape and dtype ``numpy.float64`` will be returned.
    shape : tuple
        The shape expected for the `result` array.

    Returns
    -------
    result : numpy.ndarray (``dtype=numpy.float64``, ``shape=shape``)
        The input array or a newly created array if the input was ``None``.

    Raises
    ------
    ValueError
        If `result` is of incorrect shape.
    TypeError
        If the dtype of `result` is not ``numpy.float64``.
    Ndtypez9Result array has incorrect shape, should be {0}, got {1}.z3Result array must be of type numpy.float64, got {}.)npzerosfloat64r>   r$   formatrA   	TypeError)r=   r>   s     r'   _check_result_arrayrG      s    : ~xRZ0000|u6%..
 
 	
 |rz!!vfl##
 
 	
 M    	referenceconfigurationFT)reduce_result_if_singlecheck_lengths_matchallow_atomgroupr   boxc                    |j         d         }| j         d         }||z  t          k    rt          d||z   d          t          |||f          }t	          |          dk    r|S |dk    rT|                    t          j                  }|1t          j        |                              t          j                  nd}|Ft          |          \  }}|dk    rt          d| |||f|           n,t          d	| |||f|           nt          d
| ||f|           |dk    r(|                    t          j                  }|||dd<   |S )a
  Calculate all possible distances between a reference set and another
    configuration.

    If there are ``n`` positions in `reference` and ``m`` positions in
    `configuration`, a distance array of shape ``(n, m)`` will be computed.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    If a 2D numpy array of dtype ``numpy.float64`` with the shape ``(n, m)``
    is provided in `result`, then this preallocated array is filled. This can
    speed up calculations.

    Parameters
    ----------
    reference :numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array of shape ``(3,)`` or ``(n, 3)`` (dtype is
        arbitrary, will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    configuration : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Configuration coordinate array of shape ``(3,)`` or ``(m, 3)`` (dtype is
        arbitrary, will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    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]``.
    result : numpy.ndarray, optional
        Preallocated result array which must have the shape ``(n, m)`` and dtype
        ``numpy.float64``.
        Avoids creating the array which saves time when the function
        is called repeatedly.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    d : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n, m)``)
        Array containing the distances ``d[i,j]`` between reference coordinates
        ``i`` and configuration coordinates ``j``.


    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts single coordinates as input.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.9.0
       Added support for the `distopia` backend.
    r   Size of resulting array - elements larger than size of maximum integerr   Northor+   r   r   r,   r*   r>   r)   r$   rG   lenastyperB   float32asarrayr   r(   rD   )	rI   rJ   rN   r=   r   confnumrefnum	distancesboxtypes	            r'   distance_arrayr]     s   J !!$G_QF +%%3v'7 3 3 3
 
 	

 $FVW,=>>I
9~~* $$RZ00	47Objoo$$RZ000
 ~~g+Y?     /Y?     	!]I6	
 	
 	
 	
 * $$RZ00	!F111IrH   )rK   rM   c                    | j         d         }||dz
  z  dz  }|t          k    rt          d| d          t          ||f          }t	          |          dk    r|S |dk    rT|                    t          j                  }|1t          j        |                              t          j                  nd}|Dt          |          \  }}|dk    rt          d	| ||f|
           n*t          d| ||f|
           nt          d| |f|
           |dk    r(|                    t          j                  }|||dd<   |S )a  Calculate all possible distances within a configuration `reference`.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    If a 1D numpy array of dtype ``numpy.float64`` with the shape
    ``(n*(n-1)/2,)`` is provided in `result`, then this preallocated array is
    filled. This can speed up calculations.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array of shape ``(3,)`` or ``(n, 3)`` (dtype is
        arbitrary, will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    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]``.
    result : numpy.ndarray, optional
        Preallocated result array which must have the shape ``(n*(n-1)/2,)`` and
        dtype ``numpy.float64``. Avoids creating the array which saves time when
        the function is called repeatedly.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    d : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n*(n-1)/2,)``)
        Array containing the distances ``dist[i,j]`` between reference
        coordinates ``i`` and ``j`` at position ``d[k]``. Loop through ``d``:

        .. code-block:: python

            for i in range(n):
                for j in range(i + 1, n):
                    dist[i, j] = dist[j, i] = d[k]
                    k += 1

    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.9.0
       Added support for the `distopia` backend.
    r   r	   r   rP   rQ   r   NrR   r.   rS   r/   r-   rT   )rI   rN   r=   r   rZ   distnumr[   r\   s           r'   self_distance_arrayr`     s   t _QF
#q(G,w , , ,
 
 	

 $FWJ77I
9~~* $$RZ00	47Objoo$$RZ000
 ~~g0i0     4i0     	&Y'	
 	
 	
 	
 * $$RZ00	!F111IrH   )enforce_copyrK   rL   rM   
max_cutoff
min_cutoffmethodreturn_distancesc           	         |@t          j        |t           j                  }|j        d         dk    rt	          d          | }|}	t          ||	||||          }
|
j        dk    r |
| |||||          S  |
| ||||||	          S )
a  Calculates pairs of indices corresponding to entries in the `reference`
    and `configuration` arrays which are separated by a distance lying within
    the specified cutoff(s). Optionally, these distances can be returned as
    well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    An automatic guessing of the optimal method to calculate the distances is
    included in the function. An optional keyword for the method is also
    provided. Users can enforce a particular method with this functionality.
    Currently brute force, grid search, and periodic KDtree methods are
    implemented.

    Parameters
    -----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)``. Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    configuration : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Configuration coordinate array with shape ``(3,)`` or ``(m, 3)``. Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between the reference and configuration.
    min_cutoff : float, optional
        Minimum cutoff distance between reference and configuration.
    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]``.
    method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional
        Keyword to override the automatic guessing of the employed search
        method.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` and
        `configuration` arrays such that the distance between them lies within
        the interval (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th coordinate in `reference` and the ``j``-th coordinate in
        `configuration`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

        .. code-block:: python

            pairs, distances = capped_distances(reference, configuration,
                                                max_cutoff, return_distances=True)
            for k, [i, j] in enumerate(pairs):
                coord1 = reference[i]
                coord2 = configuration[j]
                distance = distances[k]

    See Also
    --------
    distance_array
    MDAnalysis.lib.pkdtree.PeriodicKDTree.search
    MDAnalysis.lib.nsgrid.FastNS.search


    .. versionchanged:: 1.0.1
       nsgrid was temporarily removed and replaced with pkdtree due to issues
       relating to its reliability and accuracy (Issues #2919, #2229, #2345,
       #2670, #2930)
    .. versionchanged:: 1.0.2
       nsgrid enabled again
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    Nr@   r      yBox Argument is of incompatible type. The dimension should be either None or of the form [lx, ly, lz, alpha, beta, gamma]rc   rN   rd   _nsgrid_cappedrc   rN   re   rc   rN   re   r   )rB   rX   rW   r>   r$   _determine_method__name__)rI   rJ   rb   rc   rN   rd   re   r   reference_positionsconfiguration_positionsfunctions              r'   capped_distancerr     s    N jBJ///9Q<13   (1+8   H ,,,x!-
 
 
 	
 x!-
 
 
 	
rH   c                    t           t          t          d}|||                                         S t	          |           dk     st	          |          dk     r|d         S t	          |           t	          |          z  dk    r|d         S |t          j        |                     d          |                    d          g          }t          j        |                     d          |                    d          g          }|                    d          |                    d          z
  }	ngt          j	        |d	d         d
k              r|dd	         }	n<t          |          }
|
                    d          |
                    d          z
  }	t          j        |d|	z  k              r|d         S |d         S )a  Guesses the fastest method for capped distance calculations based on the
    size of the coordinate sets and the relative size of the target volume.

    Parameters
    ----------
    reference : numpy.ndarray
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)``.
    configuration : numpy.ndarray
        Configuration coordinate array with shape ``(3,)`` or ``(m, 3)``.
    max_cutoff : float
        Maximum cutoff distance between `reference` and `configuration`
        coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` and `configuration`
        coordinates.
    box : numpy.ndarray
        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]``.
    method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional
        Keyword to override the automatic guessing of the employed search
        method.

    Returns
    -------
    function : callable
        The function implementing the guessed (or deliberatly chosen) method.


    .. versionchanged:: 1.0.1
       nsgrid was temporarily removed and replaced with pkdtree due to issues
       relating to its reliability and accuracy (Issues #2919, #2229, #2345,
       #2670, #2930)
    .. versionchanged:: 1.1.0
       enabled nsgrid again
    
bruteforcepkdtreensgridN
   ru   g    חArw   r   axis        V@g333333?)_bruteforce_capped_pkdtree_cappedrj   r   rU   rB   arrayminmaxallr   any)rI   rJ   rb   rc   rN   rd   methodsmin_dimmax_dimsizetriboxs              r'   rm   rm     s   \ )"  G v||~~&&
9~~c-00255|$$	Y#m,,	,	3	3 x  ;hA&&(9(9q(9(A(AB G hA&&(9(9q(9(A(AB G ;;A;&&!)<)<<DDVCGtO$$ 	;rr7DD&s++F::1:%%


(:(::D6*sTz)** 	%<((8$$rH   c                    t          j        dt           j                  }t          j        dt           j                  }t	          |           dk    rt	          |          dk    rt          | |||          }	| t          j        |	|k    |	|k    z            }
nt          j        |	|k              }
|
d         j        dk    r*t           j        |
d         |
d         f         }|r|	|
         }|r||fS |S )a;  Capped distance evaluations using a brute force method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` and `configuration` arrays which are separated by
    a distance lying within the specified cutoff(s). Employs naive distance
    computations (brute force) to find relevant distances.

    Optionally, these distances can be returned as well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    configuration : array or :class:`~MDAnalysis.core.groups.AtomGroup`
        Configuration coordinate array with shape ``(3,)`` or ``(m, 3)`` (dtype
        will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` and `configuration`
        coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` and `configuration`
        coordinates.
    box : numpy.ndarray, 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]``.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` and
        `configuration` arrays such that the distance between them lies within
        the interval (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th coordinate in `reference` and the ``j``-th coordinate in
        `configuration`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    r   r   r@   r   r   rN   r   Nr	   )	rB   emptyintprD   rU   r]   wherer   c_)rI   rJ   rb   rc   rN   re   r   pairsr[   r!   masks              r'   r}   r}     s   ` HV27+++ERZ000I
9~~c-00144#}#w
 
 

 !8z)j:.EF DD 8Z:577D7<!E$q'47*+E -&t,	 irH   c                 L   ddl m} t          j        dt          j                  }t          j        dt          j                  }	t          |           dk    rt          |          dk    r ||          }
||nd}|
                    ||	           |
                    | |          }|j	        dk    rg|}|s|a|dddf         |dddf         }}t          | |         ||         ||
          }	|(t          j        |	|k              }||         |	|         }	}|r||	fS |S )a2  Capped distance evaluations using a KDtree method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` and `configuration` arrays which are separated by
    a distance lying within the specified cutoff(s). Employs a (periodic) KDtree
    algorithm to find relevant distances.

    Optionally, these distances can be returned as well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    configuration : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Configuration coordinate array with shape ``(3,)`` or ``(m, 3)`` (dtype
        will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` and `configuration`
        coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` and `configuration`
        coordinates.
    box : numpy.ndarray, 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]``.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` and
        `configuration` arrays such that the distance between them lies within
        the interval (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th coordinate in `reference` and the ``j``-th coordinate in
        `configuration`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    r	   PeriodicKDTreer   r@   r   r   rN   Ncutoffr   )rv   r   rB   r   r   rD   rU   
set_coordssearch_treer   
calc_bondsr   )rI   rJ   rb   rc   rN   re   r   r   r   r[   kdtreecut_pairsrefArefBr   s                   r'   r~   r~   E  sl   ^     
 HV27+++ERZ000I
9~~c-00144C(((Ojj-444##Iz::;??E 
DJ$:"111a4[%1+d&dO!$'#	  	 )8I
$:;;D',T{IdO9E irH   c                    t          j        dt           j                  }t          j        dt           j                  }t	          |           dk    rt	          |          dk    rz|t          j        dt           j                  }t          j        | |g          }	|	                    d          }
|		                    d          }|
|z
                                  }t          j
        |d|z            }|d	|z  z   |dd
<   d|d
d<   |                                 |                                }}||d|z  z
  z  }||d|z  z
  z  }t          |||d          }|                    |          }n't          |||          }|                    |           }|                                }|s|,|                                }|||k    }||         ||         }}|r||fS |S )aE  Capped distance evaluations using a grid-based search method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` and `configuration` arrays which are separated by
    a distance lying within the specified cutoff(s). Employs a grid-based search
    algorithm to find relevant distances.

    Optionally, these distances can be returned as well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    configuration : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Configuration coordinate array with shape ``(3,)`` or ``(m, 3)`` (dtype
        will be converted to ``numpy.float32`` internally). Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` and `configuration`
        coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` and `configuration`
        coordinates.
    box : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), 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]``.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` and
        `configuration` arrays such that the distance between them lies within
        the interval (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th coordinate in `reference` and the ``j``-th coordinate in
        `configuration`.
    distances : numpy.ndarray, optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    r   r@   r   r   Nrg   ry   r   皙@r{   r|   皙?FrN   pbcr   )rB   r   r   rD   rU   rC   rW   concatenater   r   maximumcopyr   search	get_pairsget_pair_distances)rI   rJ   rb   rc   rN   re   r   r[   	pseudobox
all_coordslmaxlminboxsizeshiftref	shiftconf
gridsearchresultsidxs                     r'   rj   rj     s   T HV27+++ERZ000I
9~~c-00144;
 "*555IM(BCCJ>>q>))D>>q>))Dd{''))G j!j.99G#cJ&66IbqbM IabbM"+.."2"2M4F4F4H4HiHsZ///Hj 000II9%  J !''11GG
MsCCCJ ''	22G!!## 	>
 62244I%*,#(:y~y irH   c                 
   |@t          j        |t           j                  }|j        d         dk    rt	          d          | }t          |||||          }|j        dk    r || ||||          S  || |||||	          S )
a  Calculates pairs of indices corresponding to entries in the `reference`
    array which are separated by a distance lying within the specified
    cutoff(s). Optionally, these distances can be returned as well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    An automatic guessing of the optimal method to calculate the distances is
    included in the function. An optional keyword for the method is also
    provided. Users can enforce a particular method with this functionality.
    Currently brute force, grid search, and periodic KDtree methods are
    implemented.

    Parameters
    -----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)``. Also
        accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` coordinates.
    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]``.
    method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional
        Keyword to override the automatic guessing of the employed search
        method.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` array
        such that the distance between them lies within the interval
        (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th and the ``j``-th coordinate in `reference`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``)
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and ``reference[pairs[k, 1]]``.

        .. code-block:: python

            pairs, distances = self_capped_distances(reference, max_cutoff,
                                                     return_distances=True)
            for k, [i, j] in enumerate(pairs):
                coord1 = reference[i]
                coord2 = reference[j]
                distance = distances[k]


    Note
    -----
    Currently supports brute force, grid-based, and periodic KDtree search
    methods.

    See Also
    --------
    self_distance_array
    MDAnalysis.lib.pkdtree.PeriodicKDTree.search
    MDAnalysis.lib.nsgrid.FastNS.self_search


    .. versionchanged:: 0.20.0
       Added `return_distances` keyword.
    .. versionchanged:: 1.0.1
       nsgrid was temporarily removed and replaced with pkdtree due to issues
       relating to its reliability and accuracy (Issues #2919, #2229, #2345,
       #2670, #2930)
    .. versionchanged:: 1.0.2
       enabled nsgrid again
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    Nr@   r   rg   rh   ri   _nsgrid_capped_selfrk   rl   )rB   rX   rW   r>   r$   _determine_method_selfrn   )	rI   rb   rc   rN   rd   re   r   ro   rq   s	            r'   self_capped_distancer   ,  s    N jBJ///9Q<13   (1%  H 111x!-
 
 
 	
 x!-
 
 
 	
rH   c                    t           t          t          d}|||                                         S t	          |           dk     r|d         S |t          j        |                     d          g          }t          j        |                     d          g          }|                    d          |                    d          z
  }ngt          j	        |dd         dk              r|dd         }n<t          |          }	|	                    d          |	                    d          z
  }|d	|                                z  k     r|d
         S |d         S )a!  Guesses the fastest method for capped distance calculations based on the
    size of the `reference` coordinate set and the relative size of the target
    volume.

    Parameters
    ----------
    reference : numpy.ndarray
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)``.
    max_cutoff : float
        Maximum cutoff distance between `reference` coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` coordinates.
    box : numpy.ndarray
        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]``.
    method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional
        Keyword to override the automatic guessing of the employed search
        method.

    Returns
    -------
    function : callable
        The function implementing the guessed (or deliberatly chosen) method.


    .. versionchanged:: 1.0.1
       nsgrid was temporarily removed and replaced with pkdtree due to issues
       relating to its reliability and accuracy (Issues #2919, #2229, #2345,
       #2670, #2930)
    .. versionchanged:: 1.0.2
       enabled nsgrid again
    rt   Nd   ru   r   ry   r{   r|   gQ?rv   rw   )_bruteforce_capped_self_pkdtree_capped_selfr   r   rU   rB   r   r   r   r   r   )
rI   rb   rc   rN   rd   r   r   r   r   r   s
             r'   r   r     sL   T .'% G v||~~&&
9~~|$$
{(IMMqM11233(IMMqM11233{{{""W[[a[%8%88	ABB4	 	  72A2w"3''zzqz!!FJJAJ$6$66D488::%%%y!!x  rH   )ra   rK   rM   c                 ~   t          j        dt           j                  }t          j        dt           j                  }t	          |           }|dk    rt          | ||          }	t          j        ||ft          j        t           j                  j        t           j                  }
|	|
t          j	        |d          <   | t          j
        |
|k    |
|k    z            }nt          j
        |
|k              }|d         j        dk    r(t           j        |d         |d         f         }|
|         }|r||fS |S )a
  Capped distance evaluations using a brute force method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` array which are separated by a distance lying
    within the specified cutoff(s). Employs naive distance computations (brute
    force) to find relevant distances. Optionally, these distances can be
    returned as well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` coordinates.
    box : numpy.ndarray, 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]``.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` array
        such that the distance between them lies within the interval
        (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th and the ``j``-th coordinate in `reference`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

    .. versionchanged:: 0.20.0
       Added `return_distances` keyword.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    r   r@   r   r	   r   Nr   )rB   r   r   rD   rU   r`   fullfinfor   triu_indicesr   r   r   )rI   rb   rc   rN   re   r   r   r[   Ndistvecdistr   s               r'   r   r     s!   N HV27+++ERZ000IIA 	1uu%iS'JJJw1vrx
337rzJJJ&-R_Q""#!8TZ/D:4EFGGDD8TZ/11D7<!E$q'47*+ET
I  iLrH   c                     ddl m} t          j        dt          j                  }t          j        dt          j                  }t          |           dk    r ||          }	||nd}
|	                    | |
           |	                    |          }|j	        d	k    rU|}|s|O|ddd	f         |dddf         }}t          | |         | |         ||
          }|||k    }||         ||         }}|r||fS |S )a
  Capped distance evaluations using a KDtree method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` array which are separated by a distance lying
    within the specified cutoff(s). Employs a (periodic) KDtree algorithm to
    find relevant distances. Optionally, these distances can be returned as
    well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` coordinates.
    box : numpy.ndarray, 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]``.
    return_distances : bool, optional
        If set to ``True``, distances will also be returned.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` array
        such that the distance between them lies within the interval
        (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th and the ``j``-th coordinate in `reference`.
    distances : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``)
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between
        the coordinates ``reference[pairs[k, 0]]`` and
        ``reference[pairs[k, 1]]``.

    .. versionchanged:: 0.20.0
       Added `return_distances` keyword.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.10.0
       Added the "backend" argument to select the type of acceleration of
       the distance calculations.
    r	   r   r   r@   r   r   Nr   r   r   )rv   r   rB   r   r   rD   rU   r   search_pairsr   r   )rI   rb   rc   rN   re   r   r   r   r[   r   r   r   r   r   r   s                  r'   r   r   ^  sL   L     
 HV27+++ERZ000I 9~~C(((Ojj)C000$$Z00;??E BJ$:"111a4[%1+d&dOYt_#w  	 )#j0C',Sz9S>9E  iLrH   c                 0   t          j        dt           j                  }t          j        dt           j                  }t	          |           dk    r;|t          j        dt           j                  }|                     d          }|                     d          }	||	z
                                  }
|
d	|z  k     r	d
|z  |
z  }nd}||
z  |dd<   d|dd<   | 	                                }||	d|
z  z
  z  }t          |||d          }|                                }n&t          || |          }|                                }|                                }|s|,|                                }|||k    }||         ||         }}|r||fS |S )aR	  Capped distance evaluations using a grid-based search method.

    Computes and returns an array containing pairs of indices corresponding to
    entries in the `reference` array which are separated by a distance lying
    within the specified cutoff(s). Employs a grid-based search algorithm to
    find relevant distances. Optionally, these distances can be returned as
    well.

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    Parameters
    ----------
    reference : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Reference coordinate array with shape ``(3,)`` or ``(n, 3)`` (dtype will
        be converted to ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    max_cutoff : float
        Maximum cutoff distance between `reference` coordinates.
    min_cutoff : float, optional
        Minimum cutoff distance between `reference` coordinates.
    box : numpy.ndarray, 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]``.

    Returns
    -------
    pairs : numpy.ndarray (``dtype=numpy.int64``, ``shape=(n_pairs, 2)``)
        Pairs of indices, corresponding to coordinates in the `reference` array
        such that the distance between them lies within the interval
        (`min_cutoff`, `max_cutoff`].
        Each row in `pairs` is an index pair ``[i, j]`` corresponding to the
        ``i``-th and the ``j``-th coordinate in `reference`.
    distances : numpy.ndarray, optional
        Distances corresponding to each pair of indices. Only returned if
        `return_distances` is ``True``. ``distances[k]`` corresponds to the
        ``k``-th pair returned in `pairs` and gives the distance between the
        coordinates ``reference[pairs[k, 0]]`` and
        ``configuration[pairs[k, 1]]``.

    .. versionchanged:: 0.20.0
       Added `return_distances` keyword.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    r   r@   r   r	   Nrg   r   ry   r   r   g333333?r{   r|   r   Fr   r   )rB   r   r   rD   rU   rC   rW   r   r   r   r   self_searchr   r   )rI   rb   rc   rN   re   r   r[   r   r   r   r   
sizefactorr   r   r   r   s                   r'   r   r     s   ~ HV27+++ERZ000I 9~~;
 "*555I==a=((D==a=((Dd{''))G Z'' :-7

 
&0IbqbM IabbM ~~''HsW},,H
H)OOOJ ,,..GG
I3???J ,,..G!!## 	>
 62244I%*,#(:y~y  iLrH   coordsc                 T   t          |           dk    r| S t          |          \  }}|dk    rt          j        |          }|                    t          j                  }t          j        t          j                            |          d          }t          d| |f|           | S )a  Transform an array of coordinates from real space to S space (a.k.a.
    lambda space)

    S space represents fractional space within the unit cell for this system.

    Reciprocal operation to :meth:`transform_StoR`.

    Parameters
    ----------
    coords : numpy.ndarray
        A ``(3,)`` or ``(n, 3)`` array of coordinates (dtype is arbitrary, will
        be converted to ``numpy.float32`` internally).
    box : numpy.ndarray
        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]``.
    backend : {'serial', 'OpenMP'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    newcoords : numpy.ndarray (``dtype=numpy.float32``, ``shape=coords.shape``)
        An array containing fractional coordiantes.


    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts (and, likewise, returns) a single coordinate.
    r   rR   C)orderr0   rS   )
rU   r   rB   diagrV   rD   r   linalginvr(   )r   rN   r   r\   r   s        r'   transform_RtoSr   /  s    D 6{{aS>>LGS'gcll
**RZ
 
 C (29==%%S
1
1
1C	&#@@@@MrH   c                     t          |           dk    r| S t          |          \  }}|dk    rt          j        |          }|                    t          j                  }t          d| |f|           | S )a  Transform an array of coordinates from S space into real space.

    S space represents fractional space within the unit cell for this system.

    Reciprocal operation to :meth:`transform_RtoS`

    Parameters
    ----------
    coords : numpy.ndarray
        A ``(3,)`` or ``(n, 3)`` array of coordinates (dtype is arbitrary, will
        be converted to ``numpy.float32`` internally).
    box : numpy.ndarray
        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]``.
    backend : {'serial', 'OpenMP'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    newcoords : numpy.ndarray (``dtype=numpy.float32``, ``shape=coords.shape``)
        An array containing real space coordiantes.


    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts (and, likewise, returns) a single coordinate.
    r   rR   r0   rS   )rU   r   rB   r   rV   rD   r(   )r   rN   r   r\   s       r'   transform_StoRr   a  st    B 6{{aS>>LGS'gcll
**RZ
 
 C	&#@@@@MrH   coords1coords2)rM   c                    | j         d         }t          ||f          }|dk    rT|                    t          j                  }|1t          j        |                              t          j                  nd}|dk    r]|Ft          |          \  }}|dk    rt          d| |||f|           n,t          d| |||f|           nt          d| ||f|           |dk    r(|                    t          j                  }|||dd<   |S )	a  Calculates the bond lengths between pairs of atom positions from the two
    coordinate arrays `coords1` and `coords2`, which must contain the same
    number of coordinates. ``coords1[i]`` and ``coords2[i]`` represent the
    positions of atoms connected by the ``i``-th bond. If single coordinates are
    supplied, a single distance will be returned.

    In comparison to :meth:`distance_array` and :meth:`self_distance_array`,
    which calculate distances between all possible combinations of coordinates,
    :meth:`calc_bonds` only calculates distances between pairs of coordinates,
    similar to::

       numpy.linalg.norm(a - b) for a, b in zip(coords1, coords2)

    If the optional argument `box` is supplied, the minimum image convention is
    applied when calculating distances. Either orthogonal or triclinic boxes are
    supported.

    If a numpy array of dtype ``numpy.float64`` with shape ``(n,)`` (for ``n``
    coordinate pairs) is provided in `result`, then this preallocated array is
    filled. This can speed up calculations.

    Parameters
    ----------
    coords1 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` for one half of a
        single or ``n`` bonds, respectively (dtype is arbitrary, will be
        converted to ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords2 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` for the other half of
        a single or ``n`` bonds, respectively (dtype is arbitrary, will be
        converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    box : numpy.ndarray, 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]``.
    result : numpy.ndarray, optional
        Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)``
        (for ``n`` coordinate pairs). Avoids recreating the array in repeated
        function calls.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration. Defaults to 'serial'.

    Returns
    -------
    bondlengths : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n,)``) or
        numpy.float64 Array containing the bond lengths between each pair of
        coordinates. If two single coordinates were supplied, their distance is
        returned as a single number instead of an array.


    .. versionadded:: 0.8
    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts single coordinates as input.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    .. versionchanged:: 2.5.0
       Can now optionally use the fast distance functions from distopia
    r   r   NrR   r2   rS   r3   r1   	r>   rG   rV   rB   rW   rX   r   r(   rD   )r   r   rN   r=   r   numatombondlengthsr\   s           r'   r   r     sV   R mAG%fwj99K* "((4447Objoo$$RZ000{{?$S>>LGS'!!.!7C=#     2!7C=#     $w4   
 * "((44#F111IrH   coords3c                    | j         d         }t          ||f          }|dk    rT|                    t          j                  }|1t          j        |                              t          j                  nd}|dk    r`|Ht          |          \  }}|dk    rt          d| ||||f|           n.t          d| ||||f|           nt          d| |||f|           |dk    r(|                    t          j                  }|||dd<   |S )	a9  Calculates the angles formed between triplets of atom positions from the
    three coordinate arrays `coords1`, `coords2`, and `coords3`. All coordinate
    arrays must contain the same number of coordinates.

    The coordinates in `coords2` represent the apices of the angles::

            2---3
           /
          1

    Configurations where the angle is undefined (e.g., when coordinates 1 or 3
    of a triplet coincide with coordinate 2) result in a value of **zero** for
    that angle.

    If the optional argument `box` is supplied, periodic boundaries are taken
    into account when constructing the connecting vectors between coordinates,
    i.e., the minimum image convention is applied for the vectors forming the
    angles. Either orthogonal or triclinic boxes are supported.

    If a numpy array of dtype ``numpy.float64`` with shape ``(n,)`` (for ``n``
    coordinate triplets) is provided in `result`, then this preallocated array
    is filled. This can speed up calculations.

    Parameters
    ----------
    coords1 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Array of shape ``(3,)`` or ``(n, 3)`` containing the coordinates of one
        side of a single or ``n`` angles, respectively (dtype is arbitrary, will
        be converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords2 :  numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Array of shape ``(3,)`` or ``(n, 3)`` containing the coordinates of the
        apices of a single or ``n`` angles, respectively (dtype is arbitrary,
        will be converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords3 :  numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Array of shape ``(3,)`` or ``(n, 3)`` containing the coordinates of the
        other side of a single or ``n`` angles, respectively (dtype is
        arbitrary, will be converted to ``numpy.float32`` internally).
        Also accepts an :class:`~MDAnalysis.core.groups.AtomGroup`.
    box : numpy.ndarray, 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]``.
    result : numpy.ndarray, optional
        Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)``
        (for ``n`` coordinate triplets). Avoids recreating the array in repeated
        function calls.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    angles : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n,)``) or numpy.float64
        Array containing the angles between each triplet of coordinates. Values
        are returned in radians (rad). If three single coordinates were
        supplied, the angle is returned as a single number instead of an array.


    .. versionadded:: 0.8
    .. versionchanged:: 0.9.0
       Added optional box argument to account for periodic boundaries in
       calculation
    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts single coordinates as input.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    r   r   NrR   r5   rS   r6   r4   r   )	r   r   r   rN   r=   r   r   anglesr\   s	            r'   calc_anglesr     sW   d mAG '44F* rz**47Objoo$$RZ000{{?$S>>LGS'!!&!7GS&A#     *!7GS&A#     w8    * rz**F111IMrH   coords4c           	      $   | j         d         }t          ||f          }|dk    rT|                    t          j                  }|1t          j        |                              t          j                  nd}|dk    rc|Jt          |          \  }	}|	dk    rt          d| |||||f|           n0t          d| |||||f|           nt          d| ||||f|           |dk    r(|                    t          j                  }|||dd<   |S )	ad  Calculates the dihedral angles formed between quadruplets of positions
    from the four coordinate arrays `coords1`, `coords2`, `coords3`, and
    `coords4`, which must contain the same number of coordinates.

    The dihedral angle formed by a quadruplet of positions (1,2,3,4) is
    calculated around the axis connecting positions 2 and 3 (i.e., the angle
    between the planes spanned by positions (1,2,3) and (2,3,4))::

                  4
                  |
            2-----3
           /
          1

    If all coordinates lie in the same plane, the cis configuration corresponds
    to a dihedral angle of zero, and the trans configuration to :math:`\pi`
    radians (180 degrees). Configurations where the dihedral angle is undefined
    (e.g., when all coordinates lie on the same straight line) result in a value
    of ``nan`` (not a number) for that dihedral.

    If the optional argument `box` is supplied, periodic boundaries are taken
    into account when constructing the connecting vectors between coordinates,
    i.e., the minimum image convention is applied for the vectors forming the
    dihedral angles. Either orthogonal or triclinic boxes are supported.

    If a numpy array of dtype ``numpy.float64`` with shape ``(n,)`` (for ``n``
    coordinate quadruplets) is provided in `result` then this preallocated array
    is filled. This can speed up calculations.

    Parameters
    ----------
    coords1 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` containing the 1st
        positions in dihedrals (dtype is arbitrary, will be converted to
        ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords2 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` containing the 2nd
        positions in dihedrals (dtype is arbitrary, will be converted to
        ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords3 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` containing the 3rd
        positions in dihedrals (dtype is arbitrary, will be converted to
        ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    coords4 : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` containing the 4th
        positions in dihedrals (dtype is arbitrary, will be converted to
        ``numpy.float32`` internally).  Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    box : numpy.ndarray, 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]``.
    result : numpy.ndarray, optional
        Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)``
        (for ``n`` coordinate quadruplets). Avoids recreating the array in
        repeated function calls.
    backend : {'serial', 'OpenMP', 'distopia'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    dihedrals : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n,)``) or numpy.float64
        Array containing the dihedral angles formed by each quadruplet of
        coordinates. Values are returned in radians (rad). If four single
        coordinates were supplied, the dihedral angle is returned as a single
        number instead of an array. The range of dihedral angle is
        :math:`(-\pi, \pi)`.


    .. versionadded:: 0.8
    .. versionchanged:: 0.9.0
       Added optional box argument to account for periodic boundaries in
       calculation
    .. versionchanged:: 0.11.0
       Renamed from calc_torsions to calc_dihedrals
    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts single coordinates as input.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    r   r   NrR   r8   rS   r9   r7   r   )
r   r   r   r   rN   r=   r   r   	dihedralsr\   s
             r'   calc_dihedralsr   y  sb   D mAG#FWJ77I* $$RZ00	47Objoo$$RZ000{{?$S>>LGS'!!)!7GWc9M#     -!7GWc9M#     w)D   
 * $$RZ00	!F111IrH   c                     | }t          |          dk    r|S t          |          \  }}|dk    rt          d||f|           nt          d||f|           |S )av  Moves coordinates into the primary unit cell.

    Parameters
    ----------
    coords : numpy.ndarray or :class:`~MDAnalysis.core.groups.AtomGroup`
        Coordinate array of shape ``(3,)`` or ``(n, 3)`` (dtype is arbitrary,
        will be converted to ``numpy.float32`` internally). Also accepts an
        :class:`~MDAnalysis.core.groups.AtomGroup`.
    box : numpy.ndarray
        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]``.
    backend : {'serial', 'OpenMP'}, optional
        Keyword selecting the type of acceleration.

    Returns
    -------
    newcoords : numpy.ndarray  (``dtype=numpy.float32``, ``shape=coords.shape``)
        Array containing coordinates that all lie within the primary unit cell
        as defined by `box`.


    .. versionadded:: 0.8
    .. versionchanged:: 0.13.0
       Added *backend* keyword.
    .. versionchanged:: 0.19.0
       Internal dtype conversion of input coordinates to ``numpy.float32``.
       Now also accepts (and, likewise, returns) single coordinates.
    .. versionchanged:: 2.3.0
       Can now accept an :class:`~MDAnalysis.core.groups.AtomGroup` as an
       argument in any position and checks inputs using type hinting.
    r   rR   r:   rS   r;   )rU   r   r(   )r   rN   r   coords_arrayr\   s        r'   	apply_PBCr     sz    R !'L
<AS>>LGS'[c2GDDDDD_L##6HHHHrH   vectors)ra   enforce_dtypec                     t          |          \  }}t          j        |           }|                    | j                  }|dk    rt          | ||           n#t          | |                                |           |S )a  Apply minimum image convention to an array of vectors

    This function is required for calculating the correct vectors between two
    points.  A naive approach of ``ag1.positions - ag2.positions`` will not
    provide the minimum vectors between particles, even if all particles are
    within the primary unit cell (box).

    Parameters
    ----------
    vectors : numpy.ndarray
        Vector array of shape ``(n, 3)``, either float32 or float64.  These
        represent many vectors (such as between two particles).
    box : numpy.ndarray
        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]``.

    Returns
    -------
    minimized_vectors : numpy.ndarray
        Same shape and dtype as input.  The vectors from the input, but
        minimized according to the size of the box.


    .. versionadded:: 2.1.0
    rR   )r   rB   
empty_likerV   rA   r   r   ravel)r   rN   r\   outputs       r'   minimize_vectorsr   9  sv    : S>>LGS]7##F **W]
#
#C'f5555#GSYY[[&AAAMrH   )NNr   )NNNTr   )NNN)NNTr   )NNT)r   )Nr   )P__doc__numpyrB   numpy.typingtypingnptr   r   r   r   core.groupsr   utilr
   r   mdamathr   _augmentr   r   rw   r   c_distancesr   r   	_distopiar   	importlibr!   import_moduleImportErrorstrr   r   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   c_distances_openmpr<   USED_OPENMPNDArrayrG   r]   r`   floatboolrr   rm   r}   r~   rj   r   r   r   r   r   r   r   r   r   r   r   r    rH   r'   <module>r     s  2t tj           , , , , , , , , , ,             ('''''' ) ) ) ) ) ) ) ) & & & & & & 7 7 7 7 7 7 7 7       M M M M M M M M # # # # # #    
.y.,  
8 	292'7  Jx  	 	 	D	  4Y4.  Jz 
 !!	! !!
5/! TN! 	!
 ! ! ! !.                                         , > = = = = =,S[!,*/,[, , , ,^ !   "&$(o oS[+-.ok12o 
#+	o S[!	o
 o 	[o o o od k5$OOO "&$(	i iS[+-.i	#+	i S[!i 	i
 	[i i i POiX !   #'!% '+%H
 H
S[+-.H
k12H
 H
 	H

 
#+	H
 SMH
 tnH
 c]H
 H
 H
 H
^ #'!% M% M%{M%;M% M% 	M%
 
#+	M% SMM% M% M% M% M%` !   #'!%'+%] ]S[+-.]k12] ] 	]
 
#+	] tn] c]] ] ] ]@ !   #'!%'+%e eS[+-.ek12e e 	e
 
#+	e tne c]e e e eP !   #'!%'+l lS[+-.lk12l l 	l
 
#+	l tnl l l l^ !   #'!% '+%D
 D
S[+-.D
D
 D
 
#+		D

 SMD
 tnD
 c]D
 D
 D
 D
T #'!% B! B!{B!B! B! 
#+		B!
 SMB! B! B! B!J !	   #'!%'+%V VS[+-.VV V 
#+		V
 tnV c]V V V Vr !	   #'!%'+%[ [S[+-.[[ [ 
#+		[
 tn[ c][ [ [ [| !	   #'!%'+d dS[+-.dd d 
#+		d
 tnd d d dN h. . . .b h( ( ( (V iD999 "&$(m m3;+,m3;+,m 
#+	m S[!	m
 m 	[m m m :9m` iItDDD
 "&$(w w3;+,w3;+,w 3;+,w 
#+		w
 S[!w w 	[w w w EDwt iIy$OOO "&$(F F3;+,F3;+,F 3;+,F 3;+,	F
 
#+	F S[!F F 	[F F F POFR h--- "&2 2#+{*+2	#+	2 2 	[	2 2 2 .-2j ie5AAA'ck ' ' ' ' ' BA' ' 's   +B B	B	