
     iuO                         d Z ddlZddlZddlZddlZddlZddl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mZ ddlmZmZ  ej        d          ZddZd Zd ZddZ G d de          Zd ZddZdS )u  
Native contacts analysis --- :mod:`MDAnalysis.analysis.contacts`
================================================================

This module contains classes to analyze native contacts *Q* over a
trajectory. Native contacts of a conformation are contacts that exist
in a reference structure and in the conformation. Contacts in the
reference structure are always defined as being closer than a distance
`radius`. The fraction of native contacts for a conformation can be
calculated in different ways. This module supports 3 different metrics
listed below, as well as custom metrics.

1. *Hard Cut*: To count as a contact the atoms *i* and *j* have to be at least
   as close as in the reference structure.

2. *Soft Cut*: The atom pair *i* and *j* is assigned based on a soft potential
   that is 1 if the distance is 0, 1/2 if the distance is the same as in
   the reference and 0 for large distances. For the exact definition of the
   potential and parameters have a look at function :func:`soft_cut_q`.

3. *Radius Cut*: To count as a contact the atoms *i* and *j* cannot be further
   apart than some distance `radius`.

The "fraction of native contacts" *Q(t)* is a number between 0 and 1 and
calculated as the total number of native contacts for a given time frame
divided by the total number of contacts in the reference structure.


Examples for contact analysis
-----------------------------

One-dimensional contact analysis
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As an example we analyze the opening ("unzipping") of salt bridges
when the AdK enzyme opens up; this is one of the example trajectories
in MDAnalysis. ::

    import numpy as np
    import matplotlib.pyplot as plt
    import MDAnalysis as mda
    from MDAnalysis.analysis import contacts
    from MDAnalysis.tests.datafiles import PSF,DCD
    # example trajectory (transition of AdK from closed to open)
    u = mda.Universe(PSF,DCD)
    # crude definition of salt bridges as contacts between NH/NZ in ARG/LYS and
    # OE*/OD* in ASP/GLU. You might want to think a little bit harder about the
    # problem before using this for real work.
    sel_basic = "(resname ARG LYS) and (name NH* NZ)"
    sel_acidic = "(resname ASP GLU) and (name OE* OD*)"
    # reference groups (first frame of the trajectory, but you could also use a
    # separate PDB, eg crystal structure)
    acidic = u.select_atoms(sel_acidic)
    basic = u.select_atoms(sel_basic)
    # set up analysis of native contacts ("salt bridges"); salt bridges have a
    # distance <6 A
    ca1 = contacts.Contacts(u, select=(sel_acidic, sel_basic),
                            refgroup=(acidic, basic), radius=6.0)
    # iterate through trajectory and perform analysis of "native contacts" Q
    ca1.run()
    # print number of averave contacts
    average_contacts = np.mean(ca1.results.timeseries[:, 1])
    print('average contacts = {}'.format(average_contacts))
    # plot time series q(t)
    fig, ax = plt.subplots()
    ax.plot(ca1.results.timeseries[:, 0], ca1.results.timeseries[:, 1])
    ax.set(xlabel='frame', ylabel='fraction of native contacts',
           title='Native Contacts, average = {:.2f}'.format(average_contacts))
    fig.show()


The first graph shows that when AdK opens, about 20% of the salt
bridges that existed in the closed state disappear when the enzyme
opens. They open in a step-wise fashion (made more clear by the movie
`AdK_zipper_cartoon.avi`_).

.. _`AdK_zipper_cartoon.avi`:
   http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2803350/bin/NIHMS150766-supplement-03.avi

.. rubric:: Notes

Suggested cutoff distances for different simulations

* For all-atom simulations, cutoff = 4.5 Å
* For coarse-grained simulations, cutoff = 6.0 Å


Two-dimensional contact analysis (q1-q2)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Analyze a single DIMS transition of AdK between its closed and open
conformation and plot the trajectory projected on q1-q2
:footcite:p:`Franklin2007` ::


    import MDAnalysis as mda
    from MDAnalysis.analysis import contacts
    from MDAnalysisTests.datafiles import PSF, DCD
    u = mda.Universe(PSF, DCD)
    q1q2 = contacts.q1q2(u, 'name CA', radius=8)
    q1q2.run()

    f, ax = plt.subplots(1, 2, figsize=plt.figaspect(0.5))
    ax[0].plot(q1q2.results.timeseries[:, 0], q1q2.results.timeseries[:, 1],
               label='q1')
    ax[0].plot(q1q2.results.timeseries[:, 0], q1q2.results.timeseries[:, 2],
               label='q2')
    ax[0].legend(loc='best')
    ax[1].plot(q1q2.results.timeseries[:, 1],
               q1q2.results.timeseries[:, 2], '.-')
    f.show()

Compare the resulting pathway to the `MinActionPath result for AdK`_
:footcite:p:`Franklin2007`.

.. _MinActionPath result for AdK:
   http://lorentz.dynstr.pasteur.fr/joel/adenylate.php


Writing your own contact analysis
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The :class:`Contacts` class has been designed to be extensible for your own
analysis. As an example we will analyze when the acidic and basic groups of AdK
are in contact which each other; this means that at least one of the contacts
formed in the reference is closer than 2.5 Å.

For this we define a new function to determine if any contact is closer than
2.5 Å; this function must implement the API prescribed by :class:`Contacts`::

    def is_any_closer(r, r0, dist=2.5):
        return np.any(r < dist)

The first two parameters `r` and `r0` are provided by :class:`Contacts` when it
calls :func:`is_any_closer` while the others can be passed as keyword args
using the `kwargs` parameter in :class:`Contacts`.

Next we are creating an instance of the :class:`Contacts` class and use the
:func:`is_any_closer` function as an argument to `method` and run the analysis::

    # crude definition of salt bridges as contacts between NH/NZ in ARG/LYS and
    # OE*/OD* in ASP/GLU. You might want to think a little bit harder about the
    # problem before using this for real work.
    sel_basic = "(resname ARG LYS) and (name NH* NZ)"
    sel_acidic = "(resname ASP GLU) and (name OE* OD*)"

    # reference groups (first frame of the trajectory, but you could also use a
    # separate PDB, eg crystal structure)
    acidic = u.select_atoms(sel_acidic)
    basic = u.select_atoms(sel_basic)

    nc = contacts.Contacts(u, select=(sel_acidic, sel_basic),
                           method=is_any_closer,
                           refgroup=(acidic, basic), kwargs={'dist': 2.5})
    nc.run()

    bound = nc.results.timeseries[:, 1]
    frames = nc.results.timeseries[:, 0]

    f, ax = plt.subplots()

    ax.plot(frames, bound, '.')
    ax.set(xlabel='frame', ylabel='is Bound',
           ylim=(-0.1, 1.1))

    f.show()


Functions
---------

.. autofunction:: hard_cut_q
.. autofunction:: soft_cut_q
.. autofunction:: radius_cut_q
.. autofunction:: contact_matrix
.. autofunction:: q1q2

Classes
-------

.. autoclass:: Contacts
   :members:

.. rubric:: References
.. footbibliography::

    N)openany)distance_array)	AtomGroupUpdatingAtomGroup   )AnalysisBaseResultsGroupzMDAnalysis.analysis.contacts      @?c                     t          j        |           } t          j        |          }ddt          j        || ||z  z
  z            z   z  }|                                t	          |          z  S )a  Calculate fraction of native contacts *Q* for a soft cut off

    The native contact function is defined as :footcite:p:`Best2013`

    .. math::

        Q(r, r_0) = \frac{1}{1 + e^{\beta (r - \lambda r_0)}}

    Reasonable values for different simulation types are

    - *All Atom*: `lambda_constant = 1.8` (unitless)
    - *Coarse Grained*: `lambda_constant = 1.5` (unitless)

    Parameters
    ----------
    r: array
      Contact distances at time t
    r0: array
      Contact distances at time t=0, reference distances
    beta: float (default 5.0 Angstrom)
      Softness of the switching function
    lambda_constant: float (default 1.8, unitless)
      Reference distance tolerance

    Returns
    -------
    Q : float
      fraction of native contacts
    r   )npasarrayexpsumlen)rr0betalambda_constantresults        f/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/contacts.py
soft_cut_qr      s_    < 	
1A	BB!bfTQ2)=%=>???@F::<<#b''!!    c                     t          j        |           } t          j        |          }| |k    }|                                | j        z  S )a  Calculate fraction of native contacts *Q* for a hard cut off.

    The cutoff can either be a float or a :class:`~numpy.ndarray` of the same
    shape as `r`.

    Parameters
    ----------
    r : ndarray
        distance matrix
    cutoff : ndarray | float
        cut off value to count distances. Can either be a float of a ndarray of
        the same size as distances

    Returns
    -------
    Q : float
        fraction of contacts

    )r   r   r   size)r   cutoffys      r   
hard_cut_qr     s>    ( 	
1AZF	VA5577QVr   c                 "    t          | |          S )aq  calculate native contacts *Q* based on the single distance radius.

    Parameters
    ----------
    r : ndarray
        distance array between atoms
    r0 : ndarray
        unused to fullfill :class:`Contacts` API
    radius : float
        Distance between atoms at which a contact is formed

    Returns
    -------
    Q : float
        fraction of contacts

    )r   )r   r   radiuss      r   radius_cut_qr!   &  s    $ a   r   c                 .    || |k    |dd<   n| |k    }|S )a  calculate contacts from distance matrix

    Parameters
    ----------
    d : array-like
        distance matrix
    radius : float
        distance below which a contact is formed.
    out : array (optional)
        If `out` is supplied as a pre-allocated array of the correct
        shape then it is filled instead of allocating a new one in
        order to increase performance.

    Returns
    -------
    contacts : ndarray
        boolean array of formed contacts
    N )dr    outs      r   contact_matrixr&   ;  s*    & fAAA6kJr   c                        e Zd ZdZdZed             Z	 	 	 	 d fd	Zed             Z	ed	             Z
d
 Zd Zed             Zd Z xZS )Contactsa  Calculate contacts based observables.

    The standard methods used in this class calculate the fraction of native
    contacts *Q* from a trajectory.


    .. rubric:: Contact API

    By defining your own method it is possible to calculate other observables
    that only depend on the distances and a possible reference distance. The
    **Contact API** prescribes that this method must be a function with call
    signature ``func(r, r0, **kwargs)`` and must be provided in the keyword
    argument `method`.

    Attributes
    ----------
    results.timeseries : numpy.ndarray
        2D array containing *Q* for all refgroup pairs and analyzed frames

    timeseries : numpy.ndarray
        Alias to the :attr:`results.timeseries` attribute.

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


    .. versionchanged:: 1.0.0
       ``save()`` method has been removed. Use ``np.savetxt()`` on
       :attr:`Contacts.results.timeseries` instead.
    .. versionchanged:: 1.0.0
        added ``pbc`` attribute to calculate distances using PBC.
    .. versionchanged:: 2.0.0
       :attr:`timeseries` results are now stored in a
       :class:`MDAnalysis.analysis.base.Results` instance.
    .. versionchanged:: 2.2.0
       :class:`Contacts` accepts both AtomGroup and string for `select`
    .. versionchanged:: 2.9.0
       Introduced :meth:`get_supported_backends` allowing
       for parallel execution on :mod:`multiprocessing`
       and :mod:`dask` backends.
    Tc                     dS )N)serialmultiprocessingdaskr#   )clss    r   get_supported_backendszContacts.get_supported_backends  s    
 
r   hard_cut      @Nc           
           _          t          t                     j         j         j        fi | ||ni  _        |dk    rt           _        n_|dk    rt           _        nL|dk    r!t          j
        t          |           _        n%t          |          st          d          | _        | _         fd|D             \   _         _        | _        g  _        g  _        t          j
         j         j                   _        t-          |d	         t.                    r|\  }	}
 j                            t3          |	j        |
j                             |	j                  
                      j                            t9           j        d         |                     n|D ]\  }	}
 j                            t3          |	j        |
j                             |	j                  
                      j                            t9           j        d         |                      j        d	                                          _        dS )a  
        Parameters
        ----------
        u : Universe
            trajectory
        select : tuple(AtomGroup, AtomGroup) | tuple(string, string)
            two contacting groups that change over time
        refgroup : tuple(AtomGroup, AtomGroup)
            two contacting atomgroups in their reference conformation. This
            can also be a list of tuples containing different atom groups
        radius : float, optional (4.5 Angstroms)
            radius within which contacts exist in refgroup
        method : string | callable (optional)
            Can either be one of ``['hard_cut' , 'soft_cut', 'radius_cut']`` or a callable
            with call signature ``func(r, r0, **kwargs)`` (the "Contacts API").
        pbc : bool (optional)
            Uses periodic boundary conditions to calculate distances if set to ``True``; the
            default is ``True``.
        kwargs : dict, optional
            dictionary of additional kwargs passed to `method`. Check
            respective functions for reasonable values.
        verbose : bool (optional)
             Show detailed progress of the calculation if set to ``True``; the
             default is ``False``.

        Attributes
        ----------
        n_initial_contacts : int
             Total number of initial contacts.
        r0 : list[numpy.ndarray]
             List of distance arrays between reference groups.

        Notes
        -----

        .. versionchanged:: 1.0.0
           Changed `selection` keyword to `select`
        Nr/   soft_cut
radius_cut)r    zmethod has to be callablec              3   D   K   | ]}                     |          V  d S N)_get_atomgroup).0selselfus     r   	<genexpr>z$Contacts.__init__.<locals>.<genexpr>  s3      LLcd11!S99LLLLLLr   )pbcr   box)r:   superr(   __init__
trajectoryfraction_kwargsr   fraction_contactsr   	functoolspartialr!   callable
ValueErrorselectgrAgrBr<   r   initial_contacts_get_box_func_get_box
isinstancer   appendr   	positionsuniverser&   r   n_initial_contacts)r9   r:   rI   refgroupmethodr    r<   kwargs
basekwargsrefArefB	__class__s   ``         r   rA   zContacts.__init__  sq   b &h&tv'8GGJGGG)/);vvZ%/D""z!!%/D""|##%.%6V& & &D"" F## > !<===%+D"LLLLLVLLL$(  " ")$*<$(KKKhqk9-- 	!JD$GNNNNdm44     !((V)L)LMMMM ' 
 

d" MM$-88     %,,"472;77    #'"7":">">"@"@r   c                     d}t          |t                    r|                     |          S t          |t                    r&t          |t                    rt          |          |S t          |          )Nz]selection must be either string or a static AtomGroup. Updating AtomGroups are not supported.)rO   strselect_atomsr   r   	TypeError)r:   r8   select_error_messages      r   r6   zContacts._get_atomgroup  sz    ! 	
 c3 	2>>#&&&Y'' 	2#011  4555
0111r   c                     |r| j         ndS )ac  Retrieve the dimensions of the simulation box based on PBC.

        Parameters
        ----------
        ts : Timestep
            The current timestep of the simulation, which contains the
            box dimensions.
        pbc : bool
            A flag indicating whether periodic boundary conditions (PBC)
            are enabled. If `True`, the box dimensions are returned,
            else returns `None`.

        Returns
        -------
        box_dimensions : ndarray or None
            The dimensions of the simulation box as a NumPy array if PBC
            is True, else returns `None`.
        N)
dimensions)tsr<   s     r   rM   zContacts._get_box_func  s    ( !$-r}}-r   c                 z    t          j        | j        t          | j                  dz   f          | j        _        d S )Nr   )r   emptyn_framesr   r   results
timeseriesr9   s    r   _preparezContacts._prepare  s0    "$(DM3tw<<!;K+L"M"Mr   c                    | j         j        | j        j        | j                 d<   t          | j        j        | j        j        | 	                    | j                             }t          t          | j        | j                  d          D ]F\  }\  }}||         }||         } | j        ||fi | j        }|| j        j        | j                 |<   Gd S )Nr   r=   r   )_tsframerf   rg   _frame_indexr   rJ   rQ   rK   rN   	enumerateziprL   r   rD   rC   )r9   r$   irL   r   r   qs          r   _single_framezContacts._single_frame  s    8< 1215 H 2dh8O8O
 
 
 *3%tw//*
 *
 	> 	>%A% " "#A$%B&&q"EE0DEEA<=DL#D$56q99	> 	>r   c                 R    d}t          j        |t                     | j        j        S )NzThe `timeseries` attribute was deprecated in MDAnalysis 2.0.0 and will be removed in MDAnalysis 3.0.0. Please use `results.timeseries` instead)warningswarnDeprecationWarningrf   rg   )r9   wmsgs     r   rg   zContacts.timeseries0  s,    + 	
 	d.///|&&r   c                 :    t          dt           j        i          S )Nrg   )lookup)r	   ndarray_vstackrh   s    r   _get_aggregatorzContacts._get_aggregator:  s    L,2M#NOOOOr   )r/   r0   TN)__name__
__module____qualname____doc__%_analysis_algorithm_is_parallelizableclassmethodr.   rA   staticmethodr6   rM   ri   rr   propertyrg   r{   __classcell__)rZ   s   @r   r(   r(   U  s       ) )V -1)
 
 [
 hA hA hA hA hA hAT 2 2 \2  . . \.*N N N> > >" ' ' X'P P P P P P Pr   r(   c                     t          j        | j        | j        j                  j        |          fd|D             S )z/create stand alone AGs from selections at framec                 :    g | ]}                     |          S r#   )r]   )r7   sr:   s     r   
<listcomp>z#_new_selections.<locals>.<listcomp>B  s%    222!ANN1222r   )
MDAnalysisUniversefilenamerB   )u_orig
selectionsrl   r:   s      @r   _new_selectionsr   >  sD    FOV->-GHHAL2222z2222r   allr0   c                 z    ||f}t          | |d          }t          | |d          }t          | |||f|d          S )a  Perform a q1-q2 analysis.

    Compares native contacts between the starting structure and final structure
    of a trajectory :footcite:p:`Franklin2007`.

    Parameters
    ----------
    u : Universe
        Universe with a trajectory
    select : string, optional
        atoms to do analysis on
    radius : float, optional
        distance at which contact is formed

    Returns
    -------
    contacts : :class:`Contacts`
        Contact Analysis that is set up for a q1-q2 analysis


    .. versionchanged:: 1.0.0
       Changed `selection` keyword to `select`
       Support for setting ``start``, ``stop``, and ``step`` has been removed.
       These should now be directly passed to :meth:`Contacts.run`.
    r   r?   r3   )r    rU   )r   r(   )r:   rI   r    	selectionfirst_frame_refslast_frame_refss         r   q1q2r   E  s\    4  I&q)Q77%aB77O		?+   r   )r
   r   r5   )r   r0   )r   oserrnort   bz2rE   numpyr   loggingr   MDAnalysis.lib.distancesMDAnalysis.lib.utilr   MDAnalysis.analysis.distancesr   MDAnalysis.core.groupsr   r   baser   r	   	getLoggerloggerr   r   r!   r&   r(   r   r   r#   r   r   <module>r      s  0z zv 
			   



                  ' ' ' ' ' ' 8 8 8 8 8 8 ? ? ? ? ? ? ? ? , , , , , , , ,		9	:	:"" "" "" ""J  4! ! !*   4fP fP fP fP fP| fP fP fPR3 3 3# # # # # #r   