
     i0                         d dl Z d dlmZ d dlmZmZ d dlmZ d dlZ	d dl
Z
d dlZddlmZ  G d de          Z G d	 d
e          Zd Zd Zd Zd ZdS )    N)SynchronizedArray)ProcessManager)	cpu_count   )MemoryReaderc                   Z    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd ZeZd ZdS )TriangularMatrixa  Triangular matrix class. This class is designed to provide a
    memory-efficient representation of a triangular matrix that still behaves
    as a square symmetric one. The class wraps a numpy.array object,
    in which data are memorized in row-major order. It also has few additional
    facilities to conveniently load/write a matrix from/to file. It can be
    accessed using the [] and () operators, similarly to a normal numpy array.

    Nc           	      n   t          |t                    r3t          j        |                                t
                    | _        n|| _        || _        |r|                     |           dS t          |t          j
                  r7|| _        t          j        |dz   |z  dz  t          j                  | _        dS t          |t                    rxt          j        |                                t          j                  | _        t!          t          j        ddt%          |          z  z             dz
  dz            | _        dS t          |t          j                  rH|| _        t!          t          j        ddt%          |          z  z             dz
  dz            | _        dS t(          )a  Class constructor.

        Parameters
        ----------

        size : int / array_like
            Size of the matrix (number of rows or columns). If an
            array is provided instead, the size of the triangular matrix
            will be calculated and the array copied as the matrix
            elements. Otherwise, the matrix is just initialized to zero.
        metadata : dict or None
            Metadata dictionary. Used to generate the metadata attribute.
        loadfile : str or None
            Load the matrix from this file. All the attributes and data will
            be determined by the matrix file itself (i.e. metadata will be
            ignored); size has to be provided though.

        )dtype         N)
isinstancedictnparrayitemsobjectmetadatasizeloadznumbersIntegralzerosfloat64	_elementsr   get_objintsqrtlenndarray	TypeError)selfr   r   loadfiles       j/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/encore/utils.py__init__zTriangularMatrix.__init__,   sk   & h%% 	%HX^^%5%5VDDDDMM$DM	 	JJx     g.// 
	DIXtax4&71&<BJOOODNNN/00 	XdllnnBJGGGDNRWQSYY%677!;q@AADIIIbj)) 	!DNRWQSYY%677!;q@AADIIIO    c                 R    |\  }}||k     r||}}| j         ||dz   z  dz  |z            S Nr   r   r   )r$   argsxys       r&   __getitem__zTriangularMatrix.__getitem__S   s<    1q55aqA~a1q5kQ.233r(   c                 P    |\  }}||k     r||}}|| j         ||dz   z  dz  |z   <   d S r*   r+   )r$   r,   valr-   r.   s        r&   __setitem__zTriangularMatrix.__setitem__Y   sA    1q55aqA/2qAE{a'!+,,,r(   c                    t          j        | j        | j        f          }| j        |t          j        | j                  <   |j        t          j        | j                           |t          j        | j                  <   |S )z&Return standard numpy array equivalent)r   r   r   r   tril_indicesTtriu_indices)r$   as     r&   as_arrayzTriangularMatrix.as_array_   sb     Hdi+,,(,"/$)
$
$%()BODI,F,F(G"/$)
$
$%r(   c                 H    t          j        || j        | j                   dS )zSave matrix in the npz compressed numpy format. Save metadata and
        data as well.

        Parameters
        ----------

        fname : str
            Name of the file to be saved.
        )elementsr   N)r   savezr   r   )r$   fnames     r&   r;   zTriangularMatrix.savezg   s%     	$-HHHHHHr(   c                 <   t          j        |d          }|d         j        dk    r,|d         d         | j        k    rt          |d         | _        n;| j        | j        dz
  z  dz  | j        z   t          |d                   k    rt          |d         | _        d	S )
zLoad matrix from the npz compressed numpy format.

        Parameters
        ----------

        fname : str
            Name of the file to be loaded.
        T)allow_pickler    znumber of framesr   r   r:   N)r   loadshaper   r#   r   r!   r   )r$   r<   loadeds      r&   r   zTriangularMatrix.loadzs   s     T222*#r))j!"45BB":.DMMyDIM*Q.:cz"? ?    
+r(   c                 X    |                      | j                  }| j        |z   |_        |S zAdd scalar to matrix elements.

        Parameters
        ----------

        scalar : float
            Scalar to be added.
        	__class__r   r   r$   scalar	newMatrixs      r&   __add__zTriangularMatrix.__add__   ,     NN49--	"nv5	r(   c                 &    | xj         |z  c_         | S rD   r+   r$   rH   s     r&   __iadd__zTriangularMatrix.__iadd__        	& r(   c                 X    |                      | j                  }| j        |z  |_        |S zMultiply with scalar.

        Parameters
        ----------

        scalar : float
            Scalar to multiply with.
        rE   rG   s      r&   __mul__zTriangularMatrix.__mul__   rK   r(   c                 &    | xj         |z  c_         | S rQ   r+   rM   s     r&   __imul__zTriangularMatrix.__imul__   rO   r(   c                 D    t          |                                           S )N)strr8   )r$   s    r&   __str__zTriangularMatrix.__str__   s    4==??###r(   NN)__name__
__module____qualname____doc__r'   r/   r2   r8   r;   r   rJ   rN   rR   rT   __rmul__rW   r?   r(   r&   r
   r
   "   s         % % % %N4 4 43 3 3  
I 
I 
I, , ,,  
 
 
  
 
 
 H$ $ $ $ $r(   r
   c                   &    e Zd ZdZddZd Zd ZdS )ParallelCalculationa  
    Generic parallel calculation class. Can use arbitrary functions,
    arguments to functions and kwargs to functions.

    Attributes
    ----------
    n_jobs : int
        Number of cores to be used for parallel calculation. If -1 use all
        available cores.
    function : callable object
        Function to be run in parallel.
    args : list of tuples
        Each tuple contains the arguments that will be passed to
        function(). This means that a call to function() is performed for
        each tuple. function is called as function(\*args, \*\*kwargs). Runs
        are distributed on the requested numbers of cores.
    kwargs : list of dicts
        Each tuple contains the named arguments that will be passed to
        function, similarly as described for the args attribute.
    nruns : int
        Number of runs to be performed. Must be equal to len(args) and
        len(kwargs).
    Nc                    || _         | j         dk    rt                      | _         || _        t          | j        d          s| j        gt	          |          z  | _        t	          | j                  t	          |          k    r9| j        dd         t	          |          t	          | j                  z  z  | _        |g }|| _        |r|| _        nd | j        D             | _        t	          |          | _        dS )a  
        Parameters
        ----------
        n_jobs : int
            Number of cores to be used for parallel calculation. If -1 use all
            available cores.
        function : object that supports __call__, as functions
            function to be run in parallel.
        args : list of tuples
            Arguments for function; see the ParallelCalculation class
            description.
        kwargs : list of dicts or None
            kwargs for function; see the ParallelCalculation
            class description.
        __iter__Nc                     g | ]}i S r?   r?   ).0is     r&   
<listcomp>z0ParallelCalculation.__init__.<locals>.<listcomp>  s    111!2111r(   )n_jobsr   	functionshasattrr!   r,   kwargsnruns)r$   rg   functionr,   rj   s        r&   r'   zParallelCalculation.__init__   s    $ ;"#++DK!t~z22 	:"n-D		9DNt~#d))++!^AAA.D		S000DN
 <D	  	2 DKK11ty111DKYY


r(   c           	          	 |                                 }|dk    rdS |                    | | j        |         | j        |         i | j        |         f           [)a  
        Generic worker. Will run function with the prescribed args and kwargs.

        Parameters
        ----------

        q : multiprocessing.Manager.Queue object
                work queue, from which the worker fetches arguments and
                messages

        results : multiprocessing.Manager.Queue object
                results queue, where results are put after each calculation is
                finished

        TSTOPN)getputrh   r,   rj   )r$   qresultsre   s       r&   workerzParallelCalculation.worker  sh     	AF{{KK%DN1%ty|Ft{1~FFG  	r(   c           
      2    g } j         dk    rWt           j                  D ]@}|                    |  j        |          j        |         i  j        |         f           Ant                      }|                                |                                 fdt           j                   D             }t           j                  D ]}	                    |           |D ]}	                    d           |D ]}|
                                 |D ]}|                                 	                    d           t          j        d          D ]}|                    |           t          t          |d                     S )a  
        Run parallel calculation.

        Returns
        -------

        results : tuple of ordered tuples (int, object)
                int is the number of the calculation corresponding to a
                certain argument in the args list, and object is the result of
                corresponding calculation. For instance, in (3, output), output
                is the return of function(\*args[3], \*\*kwargs[3]).
        r   c                 @    g | ]}t          j        f           S ))targetr,   )r   rs   )rd   re   rq   rr   r$   s     r&   rf   z+ParallelCalculation.run.<locals>.<listcomp>6  s<        t{!W>>>  r(   rn   c                     | d         S )Nr   r?   )r-   s    r&   <lambda>z)ParallelCalculation.run.<locals>.<lambda>J  s
    ! r(   )key)rg   rangerk   appendrh   r,   rj   r   Queuerp   startjoiniterro   tuplesorted)r$   results_listre   managerworkerswrq   rr   s   `     @@r&   runzParallelCalculation.run  s    ;!4:&&  ##)q)49Q<J4;q>JJK   
 iiGAmmooG     t{++  G
 4:&&  a  f  				  KK'+v.. ' '##A&&&&VLnn===>>>r(   rX   )rY   rZ   r[   r\   r'   rs   r   r?   r(   r&   r_   r_      sQ         0) ) ) )V  2,? ,? ,? ,? ,?r(   r_   c              #      K   | \  }}||d         k     r+||k    r||fV  d}|dz  }n||fV  |dz  }||d         k     +||d         k    r||fV  |dz  }||d         k    dS dS )a  
    Generate (i,j) indeces of a triangular matrix, between elements a and b.
    The matrix size is automatically determined from the number of elements.
    For instance: trm_indices((0,0),(2,1)) yields (0,0) (1,0) (1,1) (2,0)
    (2,1).

    Parameters
    ----------

    a : (int i, int j) tuple
        starting matrix element.

    b : (int i, int j) tuple
        final matrix element.
    r   r   Nr?   )r7   bre   js       r&   trm_indicesr   M  s        DAq
ad((66a&LLLAFAAa&LLLFA ad(( qt))!f	Q qt))))))r(   c              #   `   K   t          d|           D ]}t          |          D ]}||fV  	dS )zgenerate (i,j) indeces of a triangular matrix of n rows (or columns),
    without diagonal (e.g. no elements (0,0),(1,1),...,(n,n))

    Parameters
    ----------

    n : int
        Matrix size
    r   Nrz   nre   r   s      r&   trm_indices_nodiagr   k  sR       1a[[  q 	 	Aa&LLLL	 r(   c              #   f   K   t          d|           D ]}t          |dz             D ]}||fV  	dS )zgenerate (i,j) indeces of a triangular matrix of n rows (or columns),
    with diagonal

    Parameters
    ----------

    n : int
        Matrix size
    r   r   Nr   r   s      r&   trm_indices_diagr   {  sV       1a[[  q1u 	 	Aa&LLLL	 r(   c           	          | D ]}|                                  t          j        | d         j        t	          j        t          d | D                       d          t                    S )z
    Merge list of universes into one

    Parameters
    ----------
    universes : list of Universe objects


    Returns
    ----------
    Universe object
    r   c                 D    g | ]}|j                             d           S )fac)order)
trajectory
timeseries)rd   es     r&   rf   z#merge_universes.<locals>.<listcomp>  s+    KKKA1<***77KKKr(   )axis)format)transfer_to_memorymdaUniversefilenamer   concatenater   r   )	universesuniverses     r&   merge_universesr     s      & &##%%%%<!
KKKKKLL	
 	
 	
    r(   )r   multiprocessing.sharedctypesr   multiprocessingr   r   joblibr   numpyr   sys
MDAnalysisr   coordinates.memoryr   r   r
   r_   r   r   r   r   r?   r(   r&   <module>r      s+  .  : : : : : : , , , , , , , ,           



     . . . . . .\$ \$ \$ \$ \$v \$ \$ \$~I? I? I? I? I?& I? I? I?X  <          r(   