
     i=                         d Z ddlZddlZddlZddlZddlmZmZ ddl	m
Z
  ej        d          Zd Zd Zd	 Zd
 Z G d de          Z G d de          ZdS )aA  
Elastic network analysis of MD trajectories --- :mod:`MDAnalysis.analysis.gnm`
==============================================================================

:Author: Benjamin Hall <benjamin.a.hall@ucl.ac.uk>
:Year: 2011
:Copyright: Lesser GNU Public License v2.1 or later


Analyse a trajectory using elastic network models, following the approach of
:footcite:p:`Hall2007`.

An example is provided in the MDAnalysis Cookbook_, listed as GNMExample_.

.. _GNMExample: https://github.com/MDAnalysis/MDAnalysisCookbook/blob/master/examples/GNMExample.py
.. _Cookbook: https://github.com/MDAnalysis/MDAnalysisCookbook

The basic approach is to pass a trajectory to :class:`GNMAnalysis` and then run
the analysis:

.. code-block:: python

    u = MDAnalysis.Universe(PSF, DCD)
    C = MDAnalysis.analysis.gnm.GNMAnalysis(u, ReportVector="output.txt")

    C.run()
    output = zip(*C.results)

    with open("eigenvalues.dat", "w") as outputfile:
        for item in output[1]:
            outputfile.write(item + "\n")


The results are found in :attr:`GNMAnalysis.results`, which can be
used for further processing (see :footcite:p:`Hall2007`).

.. rubric:: References

.. footbibliography::


Analysis tasks
--------------

.. autoclass:: GNMAnalysis
   :members:
.. autoclass:: closeContactGNMAnalysis
   :members:

Utility functions
-----------------

The following functions are used internally and are typically not
directly needed to perform the analysis.

.. autofunction:: generate_grid
.. autofunction:: order_list

.. versionchanged:: 0.16.0
   removed unused function :func:`backup_file`

    N   )AnalysisBaseResultsGroup)ResultszMDAnalysis.analysis.GNMc                 6    | |z
  }t          j        ||          S N)npdot)abdiffs      a/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/gnm.py_dsqr   g   s    q5D6$    c                    t          j        |           } | j        \  }}}|                                }|                                |                                |                                }|                                |                                fdt          t          ||z
  z            dz             D             }t          |           D ]}\  }}	t          |	d         |z
  z            }
t          |	d         z
  z            }t          |	d         z
  z            }||
         |         |                             |           ~|S )a|  Simple grid search.

    An alternative to searching the entire list of each atom; divide the
    structure into `cutoff` sized boxes This way, for each particle you only need
    to search the neighbouring boxes to find the particles within the `cutoff`.

    Observed a 6x speed up for a smallish protein with ~300 residues; this
    should get better with bigger systems.

    Parameters
    ----------
    positions : array
        coordinates of the atoms
    cutoff : float
        find particles with distance less than `cutoff` from each other; the
        grid will consist of boxes with sides of at least length `cutoff`

    c           	      v    g | ]5}fd t          t          z
  z            dz             D             6S )c           	      n    g | ]1}d  t          t          z
  z            dz             D             2S )c                     g | ]}g S  r   ).0is     r   
<listcomp>z7generate_grid.<locals>.<listcomp>.<listcomp>.<listcomp>   s    CCCARCCCr   r   rangeint)r   jcutoffhigh_zlow_zs     r   r   z,generate_grid.<locals>.<listcomp>.<listcomp>   sV     	
 	
 	
 DCsFUNf#<==ABBCCC	
 	
 	
r   r   r   )r   kr   high_yr   low_yr   s     r   r   z!generate_grid.<locals>.<listcomp>   st       
 		
 	
 	
 	
 	
 	
3&899A=>>	
 	
 	
  r   r   r      )	r	   asarrayTmaxminr   r   	enumerateappend)	positionsr   xyzhigh_xlow_xgridr   posx_posy_posz_posr!   r   r"   r   s    `           @@@@r   generate_gridr5   l   sd   & 
9%%IkGAq!UUWWFUUWWFUUWWFEEGGEEEGGEEEGGE       
 sFUNf4559::  D I&& , ,3SVe^v-..SVe^v-..SVe^v-..UE5!((++++Kr   c              #   f  K   t          | |          }t          |          }t          |d                   }t          |d         d                   }t          j        t	          |          t	          |          t	          |                    D ]\  }}}||         |         |         }	g }
d}t          j        |||          D ]\\  }}}||z   }||z   }||z   }d|cxk    r|k     r:n %d|cxk    r|k     r*n 5d|cxk    r|k     rn E|
||         |         |         z  }
]|	D ]}|
D ]}||fV  	dS )a  
    return atom pairs that are in neighboring regions of space from a verlet-grid

    Parameters
    ----------
    positions : ndarray
        atom positions
    cutoff : float
        size of grid box

    Yields
    ------
    i_atom, j_atom
        indices of close atom pairs
    r   )r   r   N)r5   len	itertoolsproductr   )r*   r   r0   n_xn_yn_zcell_xcell_ycell_zatoms	all_atoms	nei_cellsr+   r,   r-   gxgygzi_atomj_atoms                       r   neighbour_generatorrI      s       F++D
d))C
d1g,,C
d1gaj//C"+"3c

E#JJc

# # % % VV$V,		 (IyII 	. 	.GAq!!B!B!BB}}}}}}}}}b31====S=====T"Xb\"--	 	% 	%F# % %fn$$$$%	%% %r   c                     t          |           }t          |           }|                                 i }t          t          |                     D ] }|                    ||                   ||<   !|S )z]Returns a dictionary showing the order of eigenvalues (which are reported scrambled normally))listsortr   r8   index)wordered	unorderedlist_mapr   s        r   
order_listrR      se    1ggGQILLNNNH3q66]] 2 2oogaj11Or   c                   h     e Zd ZdZdZed             Z	 	 	 	 d fd	Z	 dd	Zd
 Z	d Z
d Zd Z xZS )GNMAnalysisa?  Basic tool for GNM analysis.

    Each frame is treated as a novel structure and the GNM
    calculated.  By default, this stores the dominant eigenvector
    and its associated eigenvalue; either can be used to monitor
    conformational change in a simulation.

    Parameters
    ----------
    universe : Universe
          Analyze the full trajectory in the universe.
    select : str (optional)
          MDAnalysis selection string
    cutoff : float (optional)
          Consider selected atoms within the cutoff as neighbors for the
          Gaussian network model.
    ReportVector : str (optional)
          filename to write eigenvectors to, by default no output is written
    Bonus_groups : tuple
          This is a tuple of selection strings that identify additional groups
          (such as ligands). The center of mass of each group will be added as
          a single point in the ENM (it is a popular way of treating small
          ligands such as drugs). You need to ensure that none of the atoms in
          `Bonus_groups` is contained in `selection` as this could lead to
          double counting. No checks are applied.

    Attributes
    ----------
    results.times : numpy.ndarray
            simulation times used in analysis
    results.eigenvalues : numpy.ndarray
            calculated eigenvalues
    results.eigenvectors : numpy.ndarray
            calculated eigenvectors

    See Also
    --------
    :class:`closeContactGNMAnalysis`


    .. versionchanged:: 0.16.0
       Made :meth:`generate_output` a private method :meth:`_generate_output`.

    .. versionchanged:: 1.0.0
       Changed `selection` keyword to `select`

    .. versionchanged:: 2.0.0
       Use :class:`~MDAnalysis.analysis.AnalysisBase` as parent class and
       store results as attributes ``times``, ``eigenvalues`` and
       ``eigenvectors`` of the ``results`` attribute.

    .. versionchanged:: 2.8.0
       Enabled **parallel execution** with the ``multiprocessing`` and ``dask``
       backends; use the new method :meth:`get_supported_backends` to see all
       supported backends.
    Tc                     dS )N)serialmultiprocessingdaskr   )clss    r   get_supported_backendsz"GNMAnalysis.get_supported_backends  s    44r   protein and name CA      @Nc                 v    t          t                                         |j                   | _        | _        | _        t                       _        g  j        _	        g  j        _
        d  _        | _        |r fd|D             ng  _         j                             j                   _        d S )Nc                 D    g | ]}j                             |          S r   )uselect_atoms)r   itemselfs     r   r   z(GNMAnalysis.__init__.<locals>.<listcomp>  s)    @@@4TV  &&@@@r   )superrT   __init__
trajectoryr_   selectr   r   resultseigenvalueseigenvectors
_timestepsReportVectorBonus_groupsr`   ca)rb   universerf   r   rk   rl   	__class__s   `     r   rd   zGNMAnalysis.__init__
  s     	k4  ))(*=>>>yy#% $&!( @@@@<@@@@ 	
 &%%dk22r   r   c           
         t          |          }|rwt          |d          5 }t          ||d                            D ]2}t          d||d         dz   ||d                  |d         |           3	 ddd           n# 1 swxY w Y   |j                            ||d                             |j                            ||d                             dS )aO  Appends time, eigenvalues and eigenvectors to results.

        This generates the output by adding eigenvalue and
        eigenvector data to an appendable object and optionally
        printing some of the results to file. This is the function
        to replace if you want to generate a more complex set of
        outputs
        r   r    r   )fileN)rR   openr(   printrh   r)   ri   )	rb   rN   voutputobjectrk   counterrQ   oupra   s	            r   _generate_outputzGNMAnalysis._generate_output"  s%    a== 
	lC(( 	C%an55  DQ!(1+Q     	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ''(1+777!((8A;88888s   AA>>BBc                    | j         j        }| j        D ]*}t          j        ||                                f          }+t          |          }t          j        ||ft          j                  }| j	        dz  }t          || j	                  D ]u\  }}||k    rjt          ||         ||                   |k     rJd||         |<   d||         |<   ||         |         dz   ||         |<   ||         |         dz   ||         |<   v|S )a,  Generate the Kirchhoff matrix of contacts.

        This generates the neighbour matrix by generating a grid of
        near-neighbours and then calculating which are are within
        the cutoff.

        Returns
        -------
        array
                the resulting Kirchhoff matrix
        r#   g      r   )rm   r*   rl   r	   vstackcenter_of_massr8   zerosfloat64r   rI   r   )rb   r*   ra   natomsmatrixcutoffsqrG   rH   s           r   generate_kirchoffzGNMAnalysis.generate_kirchoff=  s    G%	 % 	F 	FD	9d.A.A.C.C"DEEIIY66*BJ77;>1)T[II 	D 	DNFF6*If,=>>II)-vv&)-vv&)/)?!)Cvv&)/)?!)Cvv&r   c                    |                                  }	 t          j                            |          \  }}}ng# t          j        j        $ rP d| j         d}|d| j        j         dz  }t          j	        |           t                              |           Y d S w xY w|                     ||| j        | j        | j        j                   d S )NzSVD with cutoff z failed to converge. zSkip frame at .)rk   rw   )r   r	   linalgsvdLinAlgErrorr   _tstimewarningswarnloggerwarningry   rg   rk   frame)rb   r   _rN   ru   msgs         r   _single_framezGNMAnalysis._single_framea  s    ''))	immF++GAq!!y$ 	 	 	GT[GGGC4DHM4444CM#NN3FF	 	L*HN 	 	
 	
 	
 	
 	
s   #: A BBc                     | j         | j        _         t          j        | j        j                  | j        _        t          j        | j        j                  | j        _        d S r   )timesrg   r	   r$   rh   ri   rb   s    r   	_concludezGNMAnalysis._concludet  sF    !Z#%:dl.F#G#G $&Jt|/H$I$I!!!r   c                 f    t          t           j        t           j        t           j        d          S )N)ri   rh   r   )lookup)r   ndarray_hstackr   s    r   _get_aggregatorzGNMAnalysis._get_aggregatory  s5     , ;+:%4 
 
 
 	
r   )r[   r\   NN)Nr   )__name__
__module____qualname____doc__%_analysis_algorithm_is_parallelizableclassmethodrZ   rd   ry   r   r   r   r   __classcell__ro   s   @r   rT   rT      s        7 7r -1)5 5 [5 %3 3 3 3 3 32 >?9 9 9 96" " "H
 
 
&J J J

 
 
 
 
 
 
r   rT   c                   2     e Zd ZdZ	 	 	 	 d fd	Zd Z xZS )	closeContactGNMAnalysisaP  GNMAnalysis only using close contacts.

    This is a version of the GNM where the Kirchoff matrix is
    constructed from the close contacts between individual atoms
    in different residues.

    Parameters
    ----------
    universe : Universe
          Analyze the full trajectory in the universe.
    select : str (optional)
          MDAnalysis selection string
    cutoff : float (optional)
          Consider selected atoms within the cutoff as neighbors for the
          Gaussian network model.
    ReportVector : str (optional)
          filename to write eigenvectors to, by default no output is written
    weights : {"size", None} (optional)
          If set to "size" (the default) then weight the contact by
          :math:`1/\sqrt{N_i N_j}` where :math:`N_i` and :math:`N_j` are the
          number of atoms in the residues :math:`i` and :math:`j` that contain
          the atoms that form a contact.

    Attributes
    ----------
    results.times : numpy.ndarray
            simulation times used in analysis
    results.eigenvalues : numpy.ndarray
            calculated eigenvalues
    results.eigenvectors : numpy.ndarray
            calculated eigenvectors

    Notes
    -----
    The `MassWeight` option has now been removed.

    See Also
    --------
    :class:`GNMAnalysis`


    .. versionchanged:: 0.16.0
       Made :meth:`generate_output` a private method :meth:`_generate_output`.

    .. deprecated:: 0.16.0
       Instead of ``MassWeight=True`` use ``weights="size"``.

    .. versionchanged:: 1.0.0
       MassWeight option (see above deprecation entry).
       Changed `selection` keyword to `select`

    .. versionchanged:: 2.0.0
       Use :class:`~MDAnalysis.analysis.AnalysisBase` as parent class and
       store results as attributes ``times``, ``eigenvalues`` and
       ``eigenvectors`` of the `results` attribute.
    protein      @Nsizec                 l    t          t          |                               ||||           || _        d S r   )rc   r   rd   weights)rb   rn   rf   r   rk   r   ro   s         r   rd   z closeContactGNMAnalysis.__init__  s>     	%t,,55ffl	
 	
 	
 r   c                     | j         j        }| j         j        }| j         j                                        }t          j        ||ft
          j                  }| j        dz  }t          j	        t          | j         j                            }| j        dk    r+dt          j        d | j         j        D                       z  }t          || j                  D ]\  }}||k    rt          ||         ||                   |k     ry||         }	||         }
||	         ||
         z  }||	         |
xx         |z  cc<   ||
         |	xx         |z  cc<   ||	         |	xx         |z  cc<   ||
         |
xx         |z  cc<   |S )N)dtyper#   r   r   c                 &    g | ]}|j         j        S r   )rA   n_atoms)r   rs     r   r   z=closeContactGNMAnalysis.generate_kirchoff.<locals>.<listcomp>  s    ;;;Q;;;r   )rm   
n_residuesr*   
resindicescopyr	   r}   r~   r   onesr8   residuesr   sqrtrI   r   )rb   	nresiduesr*   residue_index_mapr   r   inv_sqrt_res_sizesrG   rH   iresiduejresiduecontacts               r   r   z)closeContactGNMAnalysis.generate_kirchoff  s   G&	G%	 G.33559i0
CCC;>  WS)9%:%:;;<6!!!"RW;;$'*:;;;& & " 2)T[II 	6 	6NFF6*If,=>>II,V4,V4&x03Eh3OO  x ***g5***x ***g5***x ***g5***x ***g5***r   )r   r   Nr   )r   r   r   r   rd   r   r   r   s   @r   r   r     se        7 7x            r   r   )r   r9   loggingr   numpyr	   baser   r   MDAnalysis.analysis.baser   	getLoggerr   r   r5   rI   rR   rT   r   r   r   r   <module>r      s*  6= =|           , , , , , , , , - , , , , ,		4	5	5  
) ) )X$% $% $%N  v
 v
 v
 v
 v
, v
 v
 v
rd d d d dk d d d d dr   