
     i>                         d Z ddlZddlZddlZddlmZ ddlmZm	Z	 ddl
mZ ddlmZ  ej        d          Z G d	 d
e          Z G d de          ZdS )a  Diffusion map --- :mod:`MDAnalysis.analysis.diffusionmap`
=====================================================================

:Authors: Eugen Hruska, John Detlefs
:Year: 2016
:Copyright: Lesser GNU Public License v2.1+

This module contains the non-linear dimension reduction method diffusion map.
The eigenvectors of a diffusion matrix represent the 'collective coordinates'
of a molecule; the largest eigenvalues are the more dominant collective
coordinates. Assigning physical meaning to the 'collective coordinates' is a
fundamentally difficult problem. The time complexity of the diffusion map is
:math:`O(N^3)`, where N is the number of frames in the trajectory, and the in-memory
storage complexity is :math:`O(N^2)`. Instead of a single trajectory a sample of
protein structures can be used. The sample should be equilibrated, at least
locally. The order of the sampled structures in the trajectory is irrelevant.

The :ref:`Diffusion-Map-tutorial` shows how to use diffusion map for dimension
reduction.

More details about diffusion maps are in
:footcite:p:`deLaPorte2008,Coifman-Lafon,Ferguson2011,Clementi2011`.

.. _Diffusion-Map-tutorial:

Diffusion Map tutorial
----------------------

The example uses files provided as part of the MDAnalysis test suite
(in the variables :data:`~MDAnalysis.tests.datafiles.PSF` and
:data:`~MDAnalysis.tests.datafiles.DCD`). This tutorial shows how to use the
Diffusion Map class.

First load all modules and test data

.. code-block:: python

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

Given a universe or atom group, we can create and eigenvalue decompose
the Diffusion Matrix from that trajectory using :class:`DiffusionMap` and get
the corresponding eigenvalues and eigenvectors.

.. code-block:: python

   u = mda.Universe(PSF,DCD)

We leave determination of the appropriate scale parameter epsilon to the user,
:footcite:p:`Clementi2011` uses a complex method involving the k-nearest-neighbors
of a trajectory frame, whereas others simple use a trial-and-error approach
with a constant epsilon. Currently, the constant epsilon method is implemented
by MDAnalysis.

.. code-block:: python

   dmap = diffusionmap.DiffusionMap(u, select='backbone', epsilon=2)
   dmap.run()

From here we can perform an embedding onto the k dominant eigenvectors. The
non-linearity of the map means there is no explicit relationship between the
lower dimensional space and our original trajectory. However, this is an
isometry (distance preserving map), which means that points close in the lower
dimensional space are close in the higher-dimensional space and vice versa.
In order to embed into the most relevant low-dimensional space, there should
exist some number of dominant eigenvectors, whose corresponding eigenvalues
diminish at a constant rate until falling off, this is referred to as a
spectral gap and should be somewhat apparent for a system at equilibrium with a
high number of frames.

.. code-block:: python

   import matplotlib.pyplot as plt
   f, ax = plt.subplots()
   upper_limit = # some reasonably high number less than the n_eigenvectors
   ax.plot(dmap.eigenvalues[:upper_limit])
   ax.set(xlabel ='eigenvalue index', ylabel='eigenvalue')
   plt.tight_layout()

From here we can transform into the diffusion space

.. code-block:: python

   num_eigenvectors = # some number less than the number of frames after
   # inspecting for the spectral gap
   fit = dmap.transform(num_eigenvectors, time=1)

It can be difficult to interpret the data, and is left as a task
for the user. The `diffusion distance` between frames i and j is best
approximated by the euclidean distance  between rows i and j of
self.diffusion_space.

Classes
-------

.. autoclass:: DiffusionMap
.. autoclass:: DistanceMatrix

References
----------

If you use this Dimension Reduction method in a publication, please
cite :footcite:p:`Coifman-Lafon`.

If you choose the default metric, this module uses the fast QCP algorithm
:footcite:p:`Theobald2005` to calculate the root mean square distance (RMSD)
between two coordinate sets (as implemented in
:func:`MDAnalysis.lib.qcprot.CalcRMSDRotationalMatrix`).  When using this
module in published work please :footcite:p:`Theobald2005`.


.. footbibliography::
    N)Universe)	AtomGroupUpdatingAtomGroup   )rmsd)AnalysisBasez MDAnalysis.analysis.diffusionmapc                   T     e Zd ZdZdeddf fd	Zd Zd Zed             Z	d	 Z
 xZS )
DistanceMatrixaJ  Calculate the pairwise distance between each frame in a trajectory
    using a given metric

    A distance matrix can be initialized on its own and used as an
    initialization argument in :class:`DiffusionMap`.

    Parameters
    ----------
    universe : `~MDAnalysis.core.universe.Universe` or `~MDAnalysis.core.groups.AtomGroup`
        The MD Trajectory for dimension reduction, remember that
        computational cost of eigenvalue decomposition
        scales at O(N^3) where N is the number of frames.
        Cost can be reduced by increasing step interval or specifying a
        start and stop value when calling :meth:`DistanceMatrix.run`.
    select : str, optional
        Any valid selection string for
        :meth:`~MDAnalysis.core.groups.AtomGroup.select_atoms`
        This selection of atoms is used to calculate the RMSD between
        different frames. Water should be excluded.
    metric : function, optional
        Maps two numpy arrays to a float, is positive definite and
        symmetric. The API for a metric requires that the arrays must have
        equal length, and that the function should have weights as an
        optional argument. Weights give each index value its own weight for
        the metric calculation over the entire arrays. Default: metric is
        set to rms.rmsd().
    cutoff : float, optional
        Specify a given cutoff for metric values to be considered equal,
        Default: 1EO-5
    weights : array, optional
        Weights to be given to coordinates for metric calculation
    verbose : bool, optional
            Show detailed progress of the calculation if set to ``True``; the
            default is ``False``.

    Attributes
    ----------
    atoms : `~MDAnalysis.core.groups.AtomGroup`
        Selected atoms in trajectory subject to dimension reduction
    results.dist_matrix : numpy.ndarray, (n_frames, n_frames)
        Array of all possible ij metric distances between frames in trajectory.
        This matrix is symmetric with zeros on the diagonal.

        .. versionadded:: 2.0.0

    dist_matrix : numpy.ndarray, (n_frames, n_frames)

        .. deprecated:: 2.0.0
                 Will be removed in MDAnalysis 3.0.0. Please use
                 :attr:`results.dist_matrix` instead.

    Example
    -------
    Often, a custom distance matrix could be useful for local
    epsilon determination or other manipulations on the diffusion
    map method. The :class:`DistanceMatrix` exists in
    :mod:`~MDAnalysis.analysis.diffusionmap` and can be passed
    as an initialization argument for :class:`DiffusionMap`.

    .. code-block:: python

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

    Now create the distance matrix and pass it as an argument to
    :class:`DiffusionMap`.

        u = mda.Universe(PSF,DCD)
        dist_matrix = diffusionmap.DistanceMatrix(u, select='all')
        dist_matrix.run()
        dmap = diffusionmap.DiffusionMap(dist_matrix)
        dmap.run()

    .. versionchanged:: 1.0.0
       ``save()`` method has been removed. You can use ``np.save()`` on
       :attr:`DistanceMatrix.results.dist_matrix` instead.
    .. versionchanged:: 2.0.0
         :attr:`dist_matrix` is now stored in a
         :class:`MDAnalysis.analysis.base.Results` instance.
    .. versionchanged:: 2.2.0
         :class:`DistanceMatrix` now also accepts `AtomGroup`.
    .. versionchanged:: 2.8.0
         :class:`DistanceMatrix` is now correctly works with `frames=...`
         parameter (#4432) by iterating over `self._sliced_trajectory`
    allg      Nc                      t          t          |           j        |j        j        fi | t          |t                    rd}t          j        |           |	                    |          | _
        || _        || _        || _        d| _        d S )NzU must be a static AtomGroup. Parsing an updating AtomGroup will result in a static AtomGroup with the current frame atom selection.F)superr
   __init__universe
trajectory
isinstancer   warningswarnselect_atomsatoms_metric_cutoff_weights_calculated)	selfr   selectmetriccutoffweightskwargswmsg	__class__s	           j/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/diffusionmap.pyr   zDistanceMatrix.__init__   s     	-nd##,(	
 	
,2	
 	
 	
 h 122 	 " 
 M$**622
     c                 Z    t          j        | j        | j        f          | j        _        d S )N)npzerosn_framesresultsdist_matrixr   s    r"   _preparezDistanceMatrix._prepare  s%    #%8T]DM,J#K#K   r#   c                    | j         }| j        j        }t          | j        |d                    D ]\  }}|| _        | j        j        }|                     ||| j                  }|| j        k    r|nd| j	        j
        | j         || j         z   f<   | j	        j
        | j         || j         z   f         | j	        j
        || j         z   | j         f<   | j        |         | _        d S )N)r   r   )_frame_indexr   	positions	enumerate_sliced_trajectory_tsr   r   r   r(   r)   )r   iframei_refjtsj_refdists          r"   _single_framezDistanceMatrix._single_frame  s    "
$ t6vww?@@ 	 	EArDHJ(E<<udm<DDD ,,! L$!1t'8#88
 (!1t'8#88 L$D%%t'88 
 *62r#   c                 R    d}t          j        |t                     | j        j        S )NzThe `dist_matrix` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.dist_matrix` instead.)r   r   DeprecationWarningr(   r)   )r   r    s     r"   r)   zDistanceMatrix.dist_matrix"  s,    8 	
 	d.///|''r#   c                     d| _         d S )NT)r   r*   s    r"   	_concludezDistanceMatrix._conclude,  s    r#   )__name__
__module____qualname____doc__r   r   r+   r8   propertyr)   r<   __classcell__)r!   s   @r"   r
   r
      s        U Ut ! ! ! ! ! !8L L L3 3 3( ( ( X(             r#   r
   c                   (    e Zd ZdZddZddZd ZdS )	DiffusionMapal  Non-linear dimension reduction method

    Dimension reduction with diffusion mapping of selected structures in a
    trajectory.

    Attributes
    ----------
    eigenvalues: array (n_frames,)
        Eigenvalues of the diffusion map

    Methods
    -------
    run()
        Constructs an anisotropic diffusion kernel and performs eigenvalue
        decomposition on it.
    transform(n_eigenvectors, time)
        Perform an embedding of a frame into the eigenvectors representing
        the collective coordinates.


    .. versionchanged:: 2.2.0
         :class:`DiffusionMap` now also accepts `AtomGroup`.
    r   c                     t          |t                    st          |t                    rt          |fi || _        n,t          |t                    r|| _        nt          d          || _        dS )a  
        Parameters
        -------------
        u : MDAnalysis Universe or AtomGroup or DistanceMatrix object.
            Can be a Universe or AtomGroup, in which case one must supply kwargs for the
            initialization of a DistanceMatrix. Otherwise, this can be a
            DistanceMatrix already initialized. Either way, this will be made
            into a diffusion kernel.
        epsilon : Float
            Specifies the method used for the choice of scale parameter in the
            diffusion map. More information in
            :footcite:p:`Coifman-Lafon,Ferguson2011,Clementi2011`, Default: 1.
        **kwargs
            Parameters to be passed for the initialization of a
            :class:`DistanceMatrix`.
        zdU is not a Universe or AtomGroup or DistanceMatrix and so the DiffusionMap has no data to work with.N)r   r   r   r
   _dist_matrix
ValueError_epsilon)r   uepsilonr   s       r"   r   zDiffusionMap.__init__I  s    " a## 	z!X'>'> 	 .q ; ;F ; ;D>** 	 !DA    r#   Nc                    | j         j        s| j                             |||           | j         j        | _        | j        dk    rt          j        d           | j         j        j        dz  | j	        z  | _
        t          j        | j
                   | _        t          j        d| j                            d          z            }t          j        || j                  | _        t          j                            | j                  \  | _        | _        t          j        | j                  ddd         }| j        |         | _        | j        |         | _        d| _        | S )	a  Create and decompose the diffusion matrix in preparation
        for a diffusion map.

        Parameters
        ----------
        start : int, optional
            start frame of analysis
        stop : int, optional
            stop frame of analysis
        step : int, optional
            number of frames to skip between each analysed frame

        .. versionchanged:: 0.19.0
           Added start/stop/step kwargs
        )startstopstepi  zThe distance matrix is very large, and can be very slow to compute. Consider picking a larger step size in distance matrix initialization.   r   NT)rF   r   runr'   	_n_framesr   r   r(   r)   rH   _scaled_matrixr%   exp_kerneldiagsumdot_difflinalgeig
_eigenvals_eigenvectorsargsorteigenvalues)r   rL   rM   rN   D_invsort_idxs         r"   rQ   zDiffusionMap.rune  s?   "  , 	E!!Dt!DDD*3>D  M?   %114t}D 	 vt2233DL,,Q///00VE4<00
.0immDJ.G.G++:do..ttt4?84!/9r#   c                 ^    | j         d|dz   f         j        | j        d|dz            |z  z  S )a,  Embeds a trajectory via the diffusion map

        Parameters
        ---------
        n_eigenvectors : int
            The number of dominant eigenvectors to be used for
            diffusion mapping
        time : float
            Exponent that eigenvalues are raised to for embedding, for large
            values, more dominant eigenvectors determine diffusion distance.
        Return
        ------
        diffusion_space : array (n_frames, n_eigenvectors)
            The diffusion map embedding as defined by :footcite:p:`Ferguson2011`.
        r   )r]   Tr_   )r   n_eigenvectorstimes      r"   	transformzDiffusionMap.transform  sC      !!nq&8"8"9:<Q!!334<
 	
r#   )r   )NNN)r=   r>   r?   r@   r   rQ   rf    r#   r"   rD   rD   0  sV         0       8' ' ' 'R
 
 
 
 
r#   rD   )r@   loggingr   numpyr%   MDAnalysis.core.universer   MDAnalysis.core.groupsr   r   rmsr   baser   	getLoggerloggerr
   objectrD   rg   r#   r"   <module>rq      s  0q qd       - - - - - - ? ? ? ? ? ? ? ?            		=	>	>V  V  V  V  V \ V  V  V rp
 p
 p
 p
 p
6 p
 p
 p
 p
 p
r#   