
     i                     H   d Z ddlZddlZddlZddlmZ ddlm	Z	 ddl
mZ ddlmZ ddlmZ dd	lmZmZ d
dlmZ  G d de          Zd Z ej         ed           ed          dd          dd            Z ej         ed          dd          dd            ZdS )a  Principal Component Analysis (PCA) --- :mod:`MDAnalysis.analysis.pca`
=====================================================================

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

.. versionadded:: 0.16.0

This module contains the linear dimensions reduction method Principal Component
Analysis (PCA). PCA sorts a simulation into 3N directions of descending
variance, with N being the number of atoms. These directions are called
the principal components. The dimensions to be analyzed are reduced by only
looking at a few projections of the first principal components. To learn how to
run a Principal Component Analysis, please refer to the :ref:`PCA-tutorial`.

The PCA problem is solved by solving the eigenvalue problem of the covariance
matrix, a :math:`3N \times 3N` matrix where the element :math:`(i, j)` is the
covariance between coordinates :math:`i` and :math:`j`. The principal
components are the eigenvectors of this matrix.

For each eigenvector, its eigenvalue is the variance that the eigenvector
explains. Stored in :attr:`PCA.results.cumulated_variance`, a ratio for each
number of eigenvectors up to index :math:`i` is provided to quickly find out
how many principal components are needed to explain the amount of variance
reflected by those :math:`i` eigenvectors. For most data,
:attr:`PCA.results.cumulated_variance`
will be approximately equal to one for some :math:`n` that is significantly
smaller than the total number of components. These are the components of
interest given by Principal Component Analysis.

From here, we can project a trajectory onto these principal components and
attempt to retrieve some structure from our high dimensional data.

For a basic introduction to the module, the :ref:`PCA-tutorial` shows how
to perform Principal Component Analysis.

.. _PCA-tutorial:

PCA 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
PCA class.

First load all modules and test data::

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


Given a universe containing trajectory data we can perform Principal Component
Analysis by using the class :class:`PCA` and retrieving the principal
components.::

    u = mda.Universe(PSF, DCD)
    PSF_pca = pca.PCA(u, select='backbone')
    PSF_pca.run()


Inspect the components to determine the principal components you would like
to retain. The choice is arbitrary, but I will stop when 95 percent of the
variance is explained by the components. This cumulated variance by the
components is conveniently stored in the one-dimensional array attribute
:attr:`PCA.results.cumulated_variance`. The value at the ith index of
:attr:`PCA.results.cumulated_variance` is the sum of the variances from 0 to
i.::

    n_pcs = np.where(PSF_pca.results.cumulated_variance > 0.95)[0][0]
    atomgroup = u.select_atoms('backbone')
    pca_space = PSF_pca.transform(atomgroup, n_components=n_pcs)


From here, inspection of the ``pca_space`` and conclusions to be drawn from the
data are left to the user.

Classes and Functions
---------------------

.. autoclass:: PCA
   :members:
   :inherited-members:

.. autofunction:: cosine_content

.. autofunction:: rmsip

.. autofunction:: cumulative_overlap

    N)tqdm)Universe)_fit_to)ProgressBar   )util)dueDoi   )AnalysisBasec                       e Zd ZdZdZ	 	 	 	 d fd	Zd Zd Zd Ze	d	             Z
e	d
             Ze	d             Ze	d             Zej        d             Z	 	 	 	 	 ddZddZ ej         ed           ed          dd          dd            Z ej         ed          dd          dd            Z xZS )PCAa  Principal component analysis on an MD trajectory.

    After initializing and calling method with a universe or an atom group,
    principal components ordering the atom coordinate data by decreasing
    variance will be available for analysis. As an example:::

        pca = PCA(universe, select='backbone').run()
        pca_space = pca.transform(universe.select_atoms('backbone'), 3)


    generates the principal components of the backbone of the atomgroup and
    then transforms those atomgroup coordinates by the direction of those
    variances. Please refer to the :ref:`PCA-tutorial` for more detailed
    instructions. When using mean selections, the first frame of the selected
    trajectory slice is used as a reference.

    Parameters
    ----------
    universe : Universe
        Universe
    select : string, optional
        A valid selection statement for choosing a subset of atoms from
        the atomgroup.
    align : boolean, optional
        If True, the trajectory will be aligned to a reference
        structure.
    mean : array_like, optional
        Optional reference positions to be be used as the mean of the
        covariance matrix.
    n_components : int, optional
        The number of principal components to be saved, default saves
        all principal components
    verbose : bool (optional)
            Show detailed progress of the calculation if set to ``True``.

    Attributes
    ----------
    results.p_components: array, (n_atoms * 3, n_components)
        Principal components of the feature space,
        representing the directions of maximum variance in the data.
        The column vector p_components[:, i] is the eigenvector
        corresponding to the variance[i].

        .. versionadded:: 2.0.0

    p_components: array, (n_atoms * 3, n_components)
        Alias to the :attr:`results.p_components`.

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

    results.variance : array (n_components, )
        Raw variance explained by each eigenvector of the covariance
        matrix.

        .. versionadded:: 2.0.0

    variance : array (n_components, )
        Alias to the :attr:`results.variance`.

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

    results.cumulated_variance : array, (n_components, )
        Percentage of variance explained by the selected components and the sum
        of the components preceding it. If a subset of components is not chosen
        then all components are stored and the cumulated variance will converge
        to 1.

        .. versionadded:: 2.0.0

    cumulated_variance : array, (n_components, )
        Alias to the :attr:`results.cumulated_variance`.

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

    Notes
    -----
    Computation can be sped up by supplying precalculated mean positions.


    .. versionchanged:: 0.19.0
       The start frame is used when performing selections and calculating
       mean positions.  Previously the 0th frame was always used.
    .. versionchanged:: 1.0.0
       ``n_components`` now limits the correct axis of ``p_components``.
       ``cumulated_variance`` now accurately represents the contribution of
       each principal component and does not change when ``n_components`` is
       given. If ``n_components`` is not None or is less than the number of
       ``p_components``, ``cumulated_variance`` will not sum to 1.
       ``align=True`` now correctly aligns the trajectory and computes the
       correct means and covariance matrix.
    .. versionchanged:: 2.0.0
       ``mean_atoms`` removed, as this did not reliably contain the mean
       positions.
       ``mean`` input now accepts coordinate arrays instead of atomgroup.
       :attr:`p_components`, :attr:`variance` and :attr:`cumulated_variance`
       are now stored in a :class:`MDAnalysis.analysis.base.Results` instance.
    .. versionchanged:: 2.8.0
       ``self.run()`` can now appropriately use ``frames`` parameter (bug
       described by #4425 and fixed by #4423). Previously, behaviour was to
       manually iterate through ``self._trajectory``, which would
       incorrectly handle cases where the ``frame`` argument
       was passed.
    FallNc                      t          t          |           j        |j        fi | || _        || _        d| _        || _        || _        || _	        d S )NF)
superr   __init__
trajectory_ualign_calculated_n_components_select_mean)selfuniverseselectr   meann_componentskwargs	__class__s          a/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/pca.pyr   zPCA.__init__   s_     	"c4!("5@@@@@ 
 )


    c                    | j         d          | j                            | j                  | _        | j                            | j                  | _        | j        j        | _        | j        (t          j
        | j        df          | _        d| _        nxt          j        | j                  | _        | j        j        d         | j        k    r8t          d                    | j        | j        j        d                             d| _        | j        dk    rt          d          | j        dz  }t          j
        ||f          | _        | j        j        | _        | j                                        | _        | xj        | j        z  c_        | j        rt/          | j         | j        d	          D ]o}| j        rL| j                                        }t5          | j        j        |z
  | j        | j        || j        
          \  }}| xj        | j        j        z  c_        p| xj        | j        z  c_        t          j        | j                  | _        d S )Nr      TzVNumber of atoms in reference ({}) does not match number of atoms in the selection ({})Fr   zINo covariance information can be gathered from asingle trajectory frame.
zMean Calculation)verbosedesc
mobile_comref_com)_sliced_trajectoryr   select_atomsr   
_reference_atomsn_atoms_n_atomsr   npzerosr   
_calc_meanasarrayshape
ValueErrorformatn_framescov	positions_ref_atom_positionscenter_of_geometry_ref_cogr   _verboser   r   ravel_xmean)r   n_dimts
mobile_cogmobile_atomsold_rmsds         r!   _preparezPCA._prepare	  s)   ""'..t|<<g**4<88+:$-!344DI"DOO
4:..DIyq!T]22 %%+VDM49?1;M%N%N  
 $DO=A-   !8UEN++#'?#< ::<<  DM1  ? 	'!''   3 3
 : !%!?!?!A!AJ-4-
:0#- $. . .*L( 		T[22			II&IIhty))r"   c                    | j         rf| j                                        }t          | j        j        |z
  | j        | j        || j                  \  }}|j                                        }n| j        j                                        }|| j        z  }| xj	        t          j        |d d t          j        f         |d d t          j        f         j                  z  c_	        d S )Nr'   )r   r-   r;   r   r9   r:   r<   r>   r?   r8   r0   dotnewaxisT)r   rB   rC   rD   xs        r!   _single_framezPCA._single_frame=  s    : 	.7799J%,%
2(%& & &"L( &,,..AA%++--A	T[BF1QQQ
]+Qqqq"*}-=-?@@@r"   c                     | xj         | j        dz
  z  c_         t          j                            | j                   \  }}t          j        |          d d d         }||         | _        |d d |f         | _        d| _        | j	        | _
        d S )Nr   T)r8   r7   r0   linalgeigargsort	_variance_p_componentsr   r   r   )r   e_valse_vectssort_idxs       r!   	_concludezPCA._concludeN  s    DMA%%)--11:f%%ddd+)$QQQ[1 .r"   c                 R    d}t          j        |t                     | j        j        S )NzThe `p_components` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.p_components` instead.)warningswarnDeprecationWarningresultsp_componentsr   wmsgs     r!   r\   zPCA.p_componentsW  s,    9 	
 	d.///|((r"   c                 R    d}t          j        |t                     | j        j        S )NzThe `variance` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.variance` instead.)rX   rY   rZ   r[   variancer]   s     r!   r`   zPCA.variancea  s,    5 	
 	d.///|$$r"   c                 R    d}t          j        |t                     | j        j        S )NzThe `cumulated_variance` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.cumulated_variance` instead.)rX   rY   rZ   r[   cumulated_variancer]   s     r!   rb   zPCA.cumulated_variancek  s,    ? 	
 	d.///|..r"   c                     | j         S N)r   )r   s    r!   r   zPCA.n_componentsu  s    !!r"   c                 D   | j         r|t          | j                  }| j        d |         | j        _        t          j        | j                  t          j        | j                  z  d |         | j        _        | j	        d d d |f         | j        _
        || _        d S rd   )r   lenrQ   r[   r`   r0   cumsumsumrb   rR   r\   r   )r   ns     r!   r   zPCA.n_componentsy  s     	By''$(N2A2$6DL!	$.))BF4>,B,BBqb/DL+ )-(:111bqb5(ADL%r"   c           
      d   | j         st          d          t          |t                    r|j        }| j        |j        k    r-t          d                    | j        |j                            | j        j	        |j	        k    
                                st          j        d           |j        j        }|                    |||          \  }}}t!          t#          |||                    }||n| j        j        j        d         }	t+          j        ||	f          }
t/          t1          ||||                   | t!          ||||                             D ]O\  }}|j                                        | j        z
  }t+          j        || j        ddd|	f                   |
|<   P|
S )a  Apply the dimensionality reduction on a trajectory

        Parameters
        ----------
        atomgroup : AtomGroup or Universe
            The AtomGroup or Universe containing atoms to be PCA transformed.
        n_components : int, optional
            The number of components to be projected onto. The default
            ``None`` maps onto all components.
        start : int, optional
            The frame to start on for the PCA transform. The default
            ``None`` becomes 0, the first frame index.
        stop : int, optional
            Frame index to stop PCA transform. The default ``None`` becomes
            the total number of frames in the trajectory.
            Iteration stops *before* this frame number, which means that the
            trajectory would be read until the end.
        step : int, optional
            Include every `step` frames in the PCA transform. If set to
            ``None`` (the default) then every frame is analyzed (i.e., same as
            ``step=1``).
        verbose : bool, optional
            ``verbose = True`` option displays a progress bar for the
            iterations of transform. ``verbose = False`` disables the
            progress bar, just returns the pca_space array when the
            calculations are finished.

        Returns
        -------
        pca_space : array, shape (n_frames, n_components)


        .. versionchanged:: 0.19.0
           Transform now requires that :meth:`run` has been called before,
           otherwise a :exc:`ValueError` is raised.
        .. versionchanged:: 2.8.0
           Transform now has shows a tqdm progressbar, which can be toggled
           on with ``verbose = True``, or off with ``verbose = False``
        z,Call run() on the PCA before using transformz8PCA has been fit for{} atoms. Your atomgrouphas {} atomsz2Atom types do not match with types used to fit PCANr   )disabletotal)r   r5   
isinstancer   atomsr/   r.   r6   r-   typesr   rX   rY   r   r   check_slice_indicesrf   ranger[   r\   r4   r0   r1   r   	enumerater9   r>   r?   rG   rR   )r   	atomgroupr   startstopstepr%   trajr7   dimrG   irA   xyzs                 r!   	transformzPCA.transform  s   `  	MKLLLi** 	(!I=I---%vdmY5FGG  
 !Y_499;; 	PMNOOO!, 44UD$GGtTuUD$//00 ' L*03 	 h#''d5d?+,,Kd5d?+,,
 
 
 	> 	>EAr %++--;CVC!3AAAttG!<==CFF
r"   c                      j         st          d          |t          d                              |          j        }t	          j        |          j        |j        k    rt          d          t	          j        j        |                                          st          d          	                     j
                  st          d          j        j         j
        z
  t	          j         j
        j        d          \  }}t	          j        g t          	          }j        D ]M}|t	          j        ||j        k                       d
         }	t	          j        ||j        j        |	z
            }Nt	          j        t	          j        j        j                  |          )t	          j         j        j        j        d                    fd}
|
S )a  Computes a function to project structures onto selected PCs

        Applies Inverse-PCA transform to the PCA atomgroup.
        Optionally, calculates one displacement vector per residue
        to extrapolate the transform to atoms not in the PCA atomgroup.

        Parameters
        ----------
        components : int, array, optional
            Components to be projected onto.
            The default ``None`` maps onto all components.

        group : AtomGroup, optional
            The AtomGroup containing atoms to be projected.
            The projection applies to whole residues in ``group``.
            The atoms in the PCA class are not affected by this argument.
            The default ``None`` does not extrapolate the projection
            to non-PCA atoms.

        anchor : string, optional
            The string to select the PCA atom whose displacement vector
            is applied to non-PCA atoms in a residue. The ``anchor`` selection
            is applied to ``group``.The resulting atomselection must have
            exactly one PCA atom in each residue of ``group``.
            The default ``None`` does not extrapolate the projection
            to non-PCA atoms.

        Returns
        -------
        function
            The resulting function f(ts) takes as input a
            :class:`~MDAnalysis.coordinates.timestep.Timestep` ts,
            and returns ts with the projected structure

            .. warning::
               The transformation function takes a :class:`Timestep` as input
               because this is required for :ref:`transformations`.
               However, the inverse-PCA transformation is applied on the atoms
               of the Universe that was used for the PCA. It is *expected*
               that the `ts` is from the same Universe but this is
               currently not checked.

        Notes
        -----
        When the PCA class is run for an atomgroup, the principal components
        are cached. The trajectory can then be projected onto one or more of
        these principal components. Since the principal components are sorted
        in the order of decreasing explained variance, the first few components
        capture the essential molecular motion.

        If N is the number of atoms in the PCA group, each component has the
        length 3N. A PCA score :math:`w\_i`, along component :math:`u\_i`, is
        calculated for a set of coordinates :math:`(r(t))` of the same atoms.
        The PCA scores are then used to transform the structure, :math:`(r(t))`
        at a timestep, back to the original space.

        .. math::

            w_{i}(t) =  ({\textbf r}(t) - \bar{{\textbf r}}) \cdot
                        {\textbf u}_i \\
            {\textbf r'}(t) = (w_{i}(t) \cdot {\textbf u}_i^T) +
                              \bar{{\textbf r}}

        For each residue, the projection can be extended to atoms that were
        not part of PCA by applying the displacement vector of a PCA atom to
        all the atoms in the residue. This could be useful to preserve the bond
        distance between a PCA atom and other non-PCA atoms in a residue.

        If there are r residues and n non-PCA atoms in total, the displacement
        vector has the size 3r. This needs to be broadcasted to a size 3n. An
        extrapolation trick is used to shape the array, since going over each
        residue for each frame can be expensive. Non-PCA atoms' displacement
        vector is calculated with fancy indexing on the anchors' displacement
        vector. `index_extrapolate` saves which atoms belong to which anchors.
        If there are two non-PCA atoms in the first anchor's residue and three
        in the second anchor's residue, `index_extrapolate` is [0, 0, 1, 1, 1]

        Examples
        --------
        Run PCA class before using this function. For backbone PCA, run::

            pca = PCA(universe, select='backbone').run()

        Obtain a transformation function to project the
        backbone trajectory onto the first principal component::

            project = pca.project_single_frame(components=0)

        To project onto the first two components, run::

            project = pca.project_single_frame(components=[0,1])

        Alternatively, the transformation can be applied to PCA atoms and
        extrapolated to other atoms according to the CA atom's translation
        in each residue::

            all = u.select_atoms('all')
            project = pca.project_single_frame(components=0,
                                               group=all, anchor='name CA')

        Finally, apply the transformation function to a timestep::

            project(u.trajectory.ts)

        or apply the projection to the universe::

            u.trajectory.add_transformations(project)


        .. versionadded:: 2.2.0
        z'Call run() on the PCA before projectingNz2'anchor' cannot be 'None' if 'group' is not 'None'z(More than one 'anchor' found in residuesz0Some residues in 'group' do not have an 'anchor'z(Some 'anchors' are not part of PCA classT)return_counts)dtyper   r   c           
         j         }j        j                                         j        z
  }t	          j        t	          j        t	          j        |j        ddf                   j        ddf         j                  j        z   d          j        _         xj         j         |z
           z  c_         | S )zProjects a timestepN)rM   r$   )	r9   r-   r>   r?   r0   reshaperG   rR   rI   )	rA   anchors_coords_oldrz   anchors
componentsgroupindex_extrapolatenon_pcar   s	      r!   wrappedz)PCA.project_single_frame.<locals>.wrappedw  s     %,%6"+'--//$+=C$&JFsD$6qqq*}$EFF*111j=9;  k	" 	% 	%DK!  !!g&7:L&L%& !! Ir"   )r   r5   r+   
resindicesr0   uniquesizeisinr   issubsetr-   residuesrn   arrayintwhereresindexappendr.   repeataranger[   r\   r4   )r   r   r   anchoranchors_res_idspca_res_indicespca_res_countsnon_pca_atomsresn_commonr   r   r   r   s   ```        @@@r!   project_single_framezPCA.project_single_frame  s   `  	HFGGG~ M   ((00G%0Oy))./2FFF !KLLL75+_==AACC  K   ##DK00 M !KLLL n*T[8G.0i&d/ / /+O^ HRs333M~  )H_<== !#	!39#4x#?! ! !#		'-/00-! ! 4<#<#B1#EFFJ	 	 	 	 	 	 	 	 	 	. r"   ?10.1002/(SICI)1097-0134(19990901)36:4<419::AID-PROT5>3.0.CO;2-U10.1529/biophysj.104.052449RMSIPMDAnalysis.analysis.pcadescriptionpathc                 >   	 | j         j        }n# t          $ r t          d          w xY w	 |j         j        }nI# t          $ r< t	          |t          |                     rt          d          t          d          w xY wt          |j        |j        |          S )a  Compute the root mean square inner product between subspaces.

        This is only symmetric if the number of components is the same for
        both instances. The RMSIP effectively measures how
        correlated the vectors of this instance are to those of ``other``.

        Please cite [Amadei1999]_ and [Leo-Macias2004]_ if you use this function.

        Parameters
        ----------
        other : :class:`~MDAnalysis.analysis.pca.PCA`
            Another PCA class. This must have already been run.
        n_components : int or tuple of ints, optional
            number of components to compute for the inner products.
            ``None`` computes all of them.

        Returns
        -------
        float:
            Root mean square inner product of the selected subspaces.
            0 indicates that they are mutually orthogonal, whereas 1 indicates
            that they are identical.

        Examples
        --------

        .. testsetup::

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


        You can compare the RMSIP between different intervals of the same trajectory.
        For example, to compare similarity within the top three principal components:

        .. doctest::

            >>> first_interval = pca.PCA(u, select="backbone").run(start=0, stop=25)
            >>> second_interval = pca.PCA(u, select="backbone").run(start=25, stop=50)
            >>> last_interval = pca.PCA(u, select="backbone").run(start=75)
            >>> round(first_interval.rmsip(second_interval, n_components=3), 6)
            0.381476
            >>> round(first_interval.rmsip(last_interval, n_components=3), 6)
            0.174782


        See also
        --------
        :func:`~MDAnalysis.analysis.pca.rmsip`


        .. versionadded:: 1.0.0
        z(Call run() on the PCA before using rmsipz.Call run() on the other PCA before using rmsipother must be another PCA class)r   )r[   r\   AttributeErrorr5   rm   typermsiprI   )r   otherr   abs        r!   r   z	PCA.rmsip  s    |	I)AA 	I 	I 	IGHHH	I	D*AA 	D 	D 	D%d,, D D   !!BCCC	D QS!#L9999    ): AB 10.1016/j.str.2007.12.011Cumulative overlapr   c                 @   	 | j         j        }n# t          $ r t          d          w xY w	 |j         j        }nI# t          $ r< t	          |t          |                     rt          d          t          d          w xY wt          |j        |j        ||          S )a)  Compute the cumulative overlap of a vector in a subspace.

        This is not symmetric. The cumulative overlap measures the overlap of
        the chosen vector in this instance, in the ``other`` subspace.

        Please cite [Yang2008]_ if you use this function.

        Parameters
        ----------
        other : :class:`~MDAnalysis.analysis.pca.PCA`
            Another PCA class. This must have already been run.
        i : int, optional
            The index of eigenvector to be analysed.
        n_components : int, optional
            number of components in ``other`` to compute for the cumulative overlap.
            ``None`` computes all of them.

        Returns
        -------
        float:
            Cumulative overlap of the chosen vector in this instance to
            the ``other`` subspace. 0 indicates that they are mutually
            orthogonal, whereas 1 indicates that they are identical.

        See also
        --------
        :func:`~MDAnalysis.analysis.pca.cumulative_overlap`


        .. versionadded:: 1.0.0
        z5Call run() on the PCA before using cumulative_overlapz;Call run() on the other PCA before using cumulative_overlapr   )ry   r   )r[   r\   r   r5   rm   r   cumulative_overlaprI   )r   r   ry   r   r   r   s         r!   r   zPCA.cumulative_overlap  s    L	)AA 	 	 	G  	
	D*AA 	D 	D 	D%d,, D Q   !!BCCC	D "!#qsalKKKKr   )r   FNN)NNNNF)NNNrd   r   N)__name__
__module____qualname____doc__%_analysis_algorithm_is_parallelizabler   rE   rK   rV   propertyr\   r`   rb   r   setterr{   r   r	   dciter
   r   r   __classcell__)r    s   @r!   r   r      s       l l\ -2)
      (2* 2* 2*hA A A"/ / / ) ) X) % % X% / / X/ " " X" 	 	 	 T T T Tls s s sj SYMNN)**&	  G: G: G: G:R SY'(((&  
2L 2L 2L 
2L 2L 2L 2L 2Lr"   r   c                 z   t          j        t          |                     }t          |           }t          j        t           j        |z  |dz   z  |z            }d|z  t
          j                            || dd|f         z            dz  z  t
          j                            | dd|f         dz            z  S )a[  Measure the cosine content of the PCA projection.

    The cosine content of pca projections can be used as an indicator if a
    simulation is converged. Values close to 1 are an indicator that the
    simulation isn't converged. For values below 0.7 no statement can be made.
    If you use this function please cite :footcite:p:`BerkHess2002`.


    Parameters
    ----------
    pca_space : array, shape (number of frames, number of components)
        The PCA space to be analyzed.
    i : int
        The index of the pca_component projection to be analyzed.

    Returns
    -------
    A float reflecting the cosine content of the ith projection in the PCA
    space. The output is bounded by 0 and 1, with 1 reflecting an agreement
    with cosine while 0 reflects complete disagreement.

    References
    ----------
    .. footbibliography::

    r   g       @Nr   )r0   r   rf   cospiscipy	integratesimpson)	pca_spacery   trI   r   s        r!   cosine_contentr     s    8 		#i..!!AIA
&a!e$q(
)
)C	q?""3111a4#899a
?	@
/
!
!)AAAqD/Q"6
7
7	8r"   r   r   r   r   r   c                    t          j        |          }t          |          dk    r|d         x}}n(t          |          dk    r|\  }}nt          d          |t          |           }|t          |          }t	          j        | d|         |d|         j                  dz  }|                                |z  }|dz  S )a+	  Compute the root mean square inner product between subspaces.

    This is only symmetric if the number of components is the same for
    ``a`` and ``b``. The RMSIP effectively measures how
    correlated the vectors of ``a`` are to those of ``b``.

    Please cite [Amadei1999]_ and [Leo-Macias2004]_ if you use this function.

    Parameters
    ----------
    a : array, shape (n_components, n_features)
        The first subspace. Must have the same number of features as ``b``.
        If you are using the results of :class:`~MDAnalysis.analysis.pca.PCA`,
        this is the TRANSPOSE of ``p_components`` (i.e. ``p_components.T``).
    b : array, shape (n_components, n_features)
        The second subspace. Must have the same number of features as ``a``.
        If you are using the results of :class:`~MDAnalysis.analysis.pca.PCA`,
        this is the TRANSPOSE of ``p_components`` (i.e. ``p_components.T``).
    n_components : int or tuple of ints, optional
        number of components to compute for the inner products.
        ``None`` computes all of them.

    Returns
    -------
    float:
        Root mean square inner product of the selected subspaces.
        0 indicates that they are mutually orthogonal, whereas 1 indicates
        that they are identical.


    Examples
    --------

    .. testsetup::

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


    You can compare the RMSIP between different intervals of the same trajectory.
    For example, to compare similarity within the top three principal components:

    .. doctest::

        >>> first_interval = pca.PCA(u, select="backbone").run(start=0, stop=25)
        >>> second_interval = pca.PCA(u, select="backbone").run(start=25, stop=50)
        >>> last_interval = pca.PCA(u, select="backbone").run(start=75)
        >>> round(pca.rmsip(first_interval.results.p_components.T,
        ...           second_interval.results.p_components.T,
        ...           n_components=3), 6)
        0.381476
        >>> round(pca.rmsip(first_interval.results.p_components.T,
        ...           last_interval.results.p_components.T,
        ...           n_components=3), 6)
        0.174782


    .. versionadded:: 1.0.0
    r   r   r   z)Too many values provided for n_componentsN      ?)r   
asiterablerf   r5   r0   matmulrI   rh   )r   r   r   n_an_bsipmsips          r!   r   r   ?  s    H ?<00L
<A O#cc	\		a		SSDEEE
{!ff
{!ff
)AdsdGQttWY
'
'1
,C7799s?D9r"   r   r   c                    t          | j                  t          |j                  k     r| t          j        ddf         } | |         t          j        ddf         }|dz                                  dz  }|t          |          }|d|         }|dz                      d          dz  }t          j        t          j        ||j                            ||z  z  }|dz                                  dz  S )aR  Compute the cumulative overlap of a vector in a subspace.

    This is not symmetric. The cumulative overlap measures the overlap of
    the chosen vector in ``a``, in the ``b`` subspace.

    Please cite [Yang2008]_ if you use this function.

    Parameters
    ----------
    a : array, shape (n_components, n_features) or vector, length n_features
        The first subspace containing the vector of interest. Alternatively,
        the actual vector. Must have the same number of features as ``b``.
    b : array, shape (n_components, n_features)
        The second subspace. Must have the same number of features as ``a``.
    i : int, optional
        The index of eigenvector to be analysed.
    n_components : int, optional
        number of components in ``b`` to compute for the cumulative overlap.
        ``None`` computes all of them.

    Returns
    -------
    float:
        Cumulative overlap of the chosen vector in ``a`` to the ``b`` subspace.
        0 indicates that they are mutually orthogonal, whereas 1 indicates
        that they are identical.


    .. versionadded:: 1.0.0
    Nr   r   r   )axis)rf   r4   r0   rH   rh   absr   rI   )r   r   ry   r   vecvec_normb_normsos           r!   r   r     s    J 17||c!'ll""bj!!!m
A$rz111}
CQ||~~$H1vv	-<-A!tjjaj  C'G
ryac""##w'9:AqD::<<3r"   rd   r   )r   rX   numpyr0   scipy.integrater   	tqdm.autor   
MDAnalysisr   MDAnalysis.analysis.alignr   MDAnalysis.lib.logr   libr   r	   r
   baser   r   r   r   r   r    r"   r!   <module>r      s  0\ \z                      - - - - - - * * * * * *                    R
L R
L R
L R
L R
L, R
L R
L R
Lj# # #L CIJJC%&&	"	  M M M M` C#$$$	"  
- - - 
- - -r"   