
     i-<                         d Z ddlmZm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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mZ 	 	 	 	 	 	 	 	 ddZ	 	 ddZ	 	 	 	 	 	 	 	 	 ddZdS )a  
Distance Matrix calculation --- :mod:`MDAnalysis.analysis.ensemble.confdistmatrix`
==================================================================================


The module contains a base class to easily compute, using
parallelization and shared memory, matrices of conformational
distance between the structures stored as frames in a Universe. A
class to compute an RMSD matrix in such a way is also available.

:Author: Matteo Tiberti, Wouter Boomsma, Tone Bengtsen

.. versionadded:: 0.16.0

.. deprecated:: 2.8.0
   This module is deprecated in favour of the 
   MDAKit `mdaencore <https://mdanalysis.org/mdaencore/>`_ and will be removed
   in MDAnalysis 3.0.0.

    )ParalleldelayedN)getuser)gethostname)datetime)sleep   )Universe   )rotation_matrix   )PureRMSD)TriangularMatrixtrm_indices TmassFc
                    t          | j                            |                     |          d                    }
|rt	          j        t                      t                      t          t          j
                              | j        |
||dk    fgdt          fdt          fdt          fdt          fdt          fd	t          fd
t          fdt          fg          }| j                            |                     |          d          |r7|r|}n|}| j                            |                     |          d          ndt          t           t"          t          j        f          szdk    rt|                     |          j                            t          j                  |r8|                     |          j                            t          j                  ndnt	          j        | j                            |                     |                    d         j        d                                       t          j                  |rHt	          j        t0          d         j        d                                       t          j                  n:dn7|r3t                    dk    rt3          d          d         d         nd|
|
dz   z  dz  }t	          j        |t          j                  t7          d|
dz
  |
dz
  f          } t9          ||d|	          fd|D                        t;          |          S )a  
    Run the conformational distance matrix calculation.
    args and kwargs are passed to conf_dist_function.

    Parameters
    ----------
    ensemble : Universe object
        Universe object for which the conformational distance matrix will
        be computed.
    conf_dist_function : function object
        Function that fills the matrix with conformational distance
        values. See set_rmsd_matrix_elements for an example.
    select : str, optional
        use this selection for the calculation of conformational distance
    superimposition_select : str, optional
        use atoms from this selection for fitting instead of those of
        `select`
    pairwise_align : bool, optional
        Whether to perform pairwise alignment between conformations.
        Default is True (do the superimposition)
    weights : str/array_like, optional
       weights to be used for fit. Can be either 'mass' or an array_like
    metadata : bool, optional
        Whether to build a metadata dataset for the calculated matrix.
        Default is True.
    n_jobs : int, optional
        Number of cores to be used for parallel calculation
        Default is 1. -1 uses all available cores
    max_nbytes : str, optional
        Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder (default is None).
        See https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html for detailed documentation.
    verbose : bool, optional
        enable verbose output

    Returns
    -------
    conf_dist_matrix : encore.utils.TriangularMatrix object
        Conformational distance matrix in triangular representation.

    facorderr   hostuserdateztopology fileznumber of frameszpairwise superimpositionzsuperimposition subsetzmass-weighted)dtypeNr   r   zzused pairwise alignment with custom weights. Please provide 2 tuple with weights for 'select' and 'superimposition_select'r   )r   r   	sharedmem)n_jobsverboserequire
max_nbytesc           	   3   v   K   | ]3} t                    t          j        |                    V  4d S )N)r   npint64).0elementconf_dist_functiondistmatfitting_coordinatesrmsd_coordinatessubset_weightsweightss     s/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/encore/confdistmatrix.py	<genexpr>z1conformational_distance_matrix.<locals>.<genexpr>   sj       
 
  	$"##HW	
 	

 
 
 
 
 
    )metadata)len
trajectory
timeseriesselect_atomsr!   arrayr   r   strr   nowfilenameobjectintbool
isinstancelisttuplendarraymassesastypefloat64onesshape
fit_coordsRuntimeErroremptyr   r   r   )ensembler%   selectsuperimposition_selectr   pairwise_alignr*   r.   r   r   framesnsubset_selectmatsizeindicesr&   r'   r(   r)   s    `    `       @@@@r+   conformational_distance_matrixrN   <   s   l &&!!&)) 	' 	
 	
 G  
8  MMII''%"v%	     &)#S)+T2)62 $'	
 
 
6  *55f%%U 6    
#! 	#2MM"M&1<<!!-00 = 
 
 # wubj 9::%"v''//6==bjII 	"%22 VVBJ'' N "NN	'#..x/D/DV/L/LMM
 
 &

 	  	"Wjm&9!&<>>EE
 NN "NN 	"7||q  "/   %QZNajGG!N 1%*Ghw
++G &7Q;!"<==GH	  

 
 
 
 
 
 
 
 
 
 
 
  $ Gh7777r-   c                     | \  }}	||t          j        |          }
t          ||                             t           j                  ||	                             t           j                  ||	         j        d         ||
          ||dz   |z  dz  |	z   <   dS |e|bt          j        |          }
t          j        |          t          j        |          z  }t          j        ||         d|          }||         |z
  }||         |z
  }t          j        ||	         d|          }||	         |z
  }||	         |z
  }t          |||          d         }t          j
        t          j        |t          j
        |                              }t          |                    t           j                  |                    t           j                  ||	         j        d         ||
          ||dz   |z  dz  |	z   <   dS t          d          )a  
    RMSD Matrix calculator

    Parameters
    ----------
    tasks : iterator of int of length 2
        Given a triangular matrix, this function will calculate RMSD
        values from element tasks[0] to tasks[1]. Since the matrix
        is triangular, the trm_indices matrix automatically
        calculates the corrisponding i,j matrix indices.
        The matrix is written as an array in a row-major
        order (see the TriangularMatrix class for details).

        If fit_coords and fit_weights are specified, the structures
        will be superimposed before calculating RMSD, and fit_coords and fit_weights
        will be used to place both structures at their center of mass and
        compute the rotation matrix. In this case, both fit_coords and fit_weights
        must be specified.
    coords : numpy.array
        Array of the ensemble coordinates
    weights : numpy.array
        Array of atomic weights, having the same order as the
        coordinates array
    rmsdmat : encore.utils.TriangularMatrix
        Memory-shared triangular matrix object
    fit_coords : numpy.array or None, optional
        Array of the coordinates used for fitting
    fit_weights : numpy.array. optional
        Array of atomic weights, having the same order as the
        fit_coords array
    Nr   r   r   )axisr*   zIBoth fit_coords and fit_weights must be specified if one of them is given)r!   sumr   r?   r@   rB   asarraymeanaverager   	transposedot	TypeError)taskscoordsrmsdmatr*   rC   fit_weightsargskwargsij
sumweightsr)   com_itranslated_isubset1_coordscom_jtranslated_jsubset2_coordsrotamat	rotated_is                       r+   set_rmsd_matrix_elementsri      s   R DAqk1VG__
(01IRZ((1IRZ((1IOA)
 )
Q!q 1$%%% 
	K$;VG__
K0027;3G3GG
:a=q+FFFay5(#A.
:a=q+FFFay5(#A.!NN
 

 Ll1K1K!L!LMM	(0RZ((
++1IOA)
 )
Q!q 1$%%% &
 
 	
r-   name CAc
           
         |r9t          j        d                    |                     t          | j                            |                     |          d          j        d         |          }t          j        d           |j        j	        j
        D ]H}t          j        d                    |t          |j        |         d                                        I|j        | j                            |                     |          d          j        d         k    st          j        d           d	S n*|                                  t          |t           t"          t$          j        f          s	|d
k    rd}n|d}nd}t          j        d                    t          |                               t          j        d                    |                     |r't          j        d                    |                     t          j        d           t)          | t*          ||||||	          }t          j        d           |r|                    |           |S )aq  
    Retrieves or calculates the conformational distance (RMSD)
    matrix. The distance matrix is calculated between all the frames of all
    the :class:`~MDAnalysis.core.universe.Universe` objects given as input.
    The order of the matrix elements depends on the order of the coordinates
    of the ensembles and on the order of the input ensembles themselves,
    therefore the order of the input list is significant.

    The distance matrix can either be calculated from input ensembles or
    loaded from an input numpy binary file.

    Please notice that the .npz file does not contain a bi-dimensional array,
    but a flattened representation that is meant to represent the elements of
    an encore.utils.TriangularMatrix object.


    Parameters
    ----------
    ensemble : Universe
    select : str
        Atom selection string in the MDAnalysis format. Default is "name CA"
    load_matrix : str, optional
        Load similarity/dissimilarity matrix from numpy binary file instead
        of calculating it (default is None). A filename is required.
    save_matrix : bool, optional
        Save calculated matrix as numpy binary file (default is None). A
        filename is required.
    superimpose : bool, optional
        Whether to superimpose structures before calculating distance
        (default is True).
    superimposition_subset : str, optional
        Group for superimposition using MDAnalysis selection syntax
        (default is CA atoms: "name CA")
    weights : str/array_like, optional
        weights to be used for fit. Can be either 'mass' or an array_like
    n_jobs : int, optional
        Maximum number of cores to be used (default is 1). If -1 use all cores.
    max_nbytes : str, optional
        Threshold on the size of arrays passed to the workers that triggers automated memory mapping in temp_folder (default is None).
        See https://joblib.readthedocs.io/en/latest/generated/joblib.Parallel.html for detailed documentation.
    verbose : bool, optional
        print progress

    Returns
    -------

    confdistmatrix : encore.utils.TriangularMatrix
        Conformational distance matrix. .
    z+        Loading similarity matrix from: {0}r   r   r   )sizeloadfilez        Done!z        {0} : {1}zEERROR: The size of the loaded matrix and of the ensemble do not matchNr   MassNoneCustomz'        Perform pairwise alignment: {0}z(        weighted alignment and RMSD: {0}z'        Atoms subset for alignment: {0}z'    Calculating similarity matrix . . .)r%   rG   rI   r*   r   r   r   z	    Done!)logginginfoformatr   r0   r1   r2   rB   r.   r   namesr4   rl   errortransfer_to_memoryr:   r;   r<   r!   r=   rN   ri   savez)rF   rG   load_matrixsave_matrixsuperimposesuperimposition_subsetr*   r   r   r   conf_dist_argsconf_dist_kwargsconfdistmatrixkeyweight_types                  r+   get_distance_matrixr   8  s   B  L.9@@MM	
 	
 	
 *$//%%f--U 0  A !	
 
 
 	_%%%!*06 	 	CL#**^4S9!<==     #"--%%f--U .  A 
 M    4 	##%%% 7T5"*$=>>	#6!! KK_ KK"K5<<S=M=MNN	
 	
 	
 	6==kJJ	
 	
 	
  	L9@@*   
 	>??? 87&!	
 	
 	
 	[!!! 	.  ---r-   )r   r   r   Tr   TFN)NN)	rj   NNTrj   r   r   NF)__doc__joblibr   r   numpyr!   getpassr   socketr   r   timer   rq   warningscore.universer
   alignr   cutilsr   utilsr   r   rN   ri   r    r-   r+   <module>r      sr  . ( % $ $ $ $ $ $ $                               % % % % % % # # # # # #       0 0 0 0 0 0 0 0 i8 i8 i8 i8b M
 M
 M
 M
d $O O O O O Or-   