
     iAO                     n    d 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
 d Zd Zdd
Z G d de
          ZdS )u  
HELANAL --- analysis of protein helices
=======================================

:Author: Lily Wang
:Year: 2020
:Copyright: Lesser GNU Public License v2.1+

.. versionadded:: 2.0.0

This module contains code to analyse protein helices using the
HELANAL_ algorithm
([Bansal2000]_ , [Sugeta1967]_ ).

HELANAL_ quantifies the geometry of helices in proteins on the basis of their
Cα atoms. It can determine local structural features such as the local
helical twist and rise, virtual torsion angle, local helix origins and
bending angles between successive local helix axes.

.. _HELANAL: https://pubmed.ncbi.nlm.nih.gov/10798526/

.. [Sugeta1967] Sugeta, H. and Miyazawa, T. 1967. General method for
   calculating helical parameters of polymer chains from bond lengths, bond
   angles and internal rotation angles. *Biopolymers* 5 673 - 679

.. [Bansal2000] Bansal M, Kumar S, Velavan R. 2000.
   HELANAL - A program to characterise helix geometry in proteins.
   *J Biomol Struct Dyn.*  17(5):811-819.


Example use
-----------

You can pass in a single selection::

    import MDAnalysis as mda
    from MDAnalysis.tests.datafiles import PSF, DCD
    from MDAnalysis.analysis import helix_analysis as hel
    u = mda.Universe(PSF, DCD)
    helanal = hel.HELANAL(u, select='name CA and resnum 161-187')
    helanal.run()

All computed properties are available in ``.results``::

    print(helanal.results.summary)

Alternatively, you can analyse several helices at once by passing
in multiple selection strings::

    helanal2 = hel.HELANAL(u, select=('name CA and resnum 100-160',
                                      'name CA and resnum 200-230'))

The :func:`helix_analysis` function will carry out helix analysis on
atom positions, treating each row of coordinates as an alpha-carbon
equivalent::

    hel_xyz = hel.helix_analysis(u.atoms.positions, ref_axis=[0, 0, 1])

    
Classes
-------

.. autoclass:: HELANAL


Functions
---------

.. autofunction:: helix_analysis

.. autofunction:: vector_of_best_fit

.. autofunction:: local_screw_angles


    N   )utilmdamath   )AnalysisBasec                 (   | |                      d          z
  }t          j        |j        |          }t          j                            |          \  }}}|d         }t          j        |d         |          }|t          j        dz  k    r|dz  }|S )a   Fit vector through the centered coordinates,
    pointing to the first coordinate (i.e. upside-down).

    Parameters
    ----------
    coordinates : :class:`numpy.ndarray` of shape (N, 3)

    Returns
    -------
    :class:`numpy.ndarray` of shape (3,)
        Vector of best fit.
    r   axisr   )	meannpmatmulTlinalgsvdr   anglepi)coordinatescenteredMt_Musvhvectorr   s           l/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/helix_analysis.pyvector_of_best_fitr   m   s     [--1-555H9XZ**Dy}}T""HAq"UF M(1+v..Eruqy"M    c                    t          j        |           } t          j        ||           }t          j        |          s[g dg dg}t          j        |          s?|r=t          j        |                                |           }t          j        |          s|=t          j        | |           }t          j        | |           }t          j        | |j                  |z  }|                    dd          |                     dd          z  }||z
  }	t          j	        ||g          }
t          j
        t          j        |
          t          j        |	                    x}\  }}t          j        |
|	j                  |z  x}\  }}t          j        t          j        |dd                    \  }}d||dk    <   ||dk     xx         dz  cc<   t           j        ||t           j         k    <   t          j        |          S )a  
    Cylindrical azimuth angles between the local direction vectors,
    as projected onto the cross-section of the helix, from (-pi, pi].
    The origin (angle=0) is set to the plane of global_axis and ref_axis.

    Parameters
    ----------
    global_axis : :class:`numpy.ndarray` of shape (3,)
        Vector of best fit. Screw angles are calculated perpendicular to
        this axis.
    ref_axis : :class:`numpy.ndarray` of shape (3,)
        Reference length-wise axis. One of the reference vectors is
        orthogonal to this axis.
    helix_directions : :class:`numpy.ndarray` of shape (N, 3)
        array of vectors representing the local direction of each
        helix window.

    Returns
    -------
    :class:`numpy.ndarray` of shape (N,)
        Array of screw angles.
    )r   r   r   r   r   r   r   r   r   )r   asarraycrossanypopdotr   r   reshapearrayouterr   pnormarccosclipr   rad2deg)global_axisref_axishelix_directionsperpnew_reforthonorm_global_sqmag_gproj_g
proj_planerefsnorms_
ortho_normcoscos_perp	cos_orthoto_perpto_orthos                      r   local_screw_anglesr?      s   . *[))K8Hk**D6$<< 899iii(&,, 	87 	88GKKMM;77D &,, 	87 	8 HdUK((E VK55NIk#3#566GE]]2q!!K$7$72$>$>>F!F*J 8T5M""DHdW]:66  EMAz !#	$
 = = EEC
(I	"'#r1"5"566GX !HZ1_X\b #%5HX"% :hr   r   c                    | dd         | dd         z
  }|dd         |dd         z
  }t          j        |          }|dd         |dd         z  }t          j        |dd         |dd                   |z  }t          j        |dd          }t          j        |          }t          j        |          }dt          j        z  |z  }	t          j        |dd         |dd                   }
|
j	        t          j        |
          z  j	        }t          j
        |          }t          j        t          j        |d          t          |          df          j	        }t          j        ||j	                  }t          j        ||j	        z   |d          }t          j        t          j        t          j        |dd                              }t          j        |d          }|dz  dd	|z
  z  z  }t          j        |dk    ||dz  dz            }t          j        t          j        |dd         |                    }|j	        |z  j	        }| dd                                         }|ddxx         ||dd         j	        z  j	        z  cc<   |dxx         |d         |d         z  z  cc<   t'          |          }t)          |t          j        |          |          }||	||||||||d

}|S )aL  
    Calculate helix properties from atomic coordinates.

    Each property is calculated from a sliding window of 4 atoms,
    from i to i+3. Any property whose name begins with 'local' is a
    property of a sliding window.

    Parameters
    ----------
    positions : :class:`numpy.ndarray` of shape (N, 3)
        Atomic coordinates.
    ref_axis : array-like of length 3, optional
        The reference axis used to calculate the tilt of the vector
        of best fit, and the local screw angles.

    Returns
    -------
    dict with the following keys:
        local_twists : array, shape (N-3,)
            local twist angle from atom i+1 to i+2
        local_nres_per_turn : array, shape (N-3,)
            number of residues per turn, based on local_twist
        local_axes :  array, shape (N-3, 3)
            the length-wise helix axis of the local window
        local_bends : array, shape (N-6,)
            the angles between local helix angles, 3 windows apart
        local_heights : array, shape (N-3,)
            the rise of each local helix
        local_helix_directions : array, shape (N-2, 3)
            the unit vector from each local origin to atom i+1
        local_origins : array, shape (N-2, 3)
            the projected origin for each helix
        all_bends : array, shape (N-3, N-3)
            angles between each local axis
        global_axis : array, shape (3,)
            vector of best fit through origins, pointing at the first origin.
        local_screw_angles : array, shape (N-2,)
            cylindrical azimuth angle to plane of global_axis and ref_axis
    r   Nr   r   r	      )offset      ?      ?)
local_twistslocal_nres_per_turn
local_axeslocal_bendslocal_heightslocal_helix_directionslocal_origins	all_bendsr,   r?   )r   r(   pdotr   r*   r)   r+   r   r!   r   
nan_to_numtiler"   lenr   wherediagonalabscopyr   r?   r    )	positionsr-   vectors	bisectorsbimagsadjacent_mag	cos_thetatwistsrE   rF   cross_birG   zero_vectors
bend_thetabend_matrixrH   radiiheightsrJ   origins
helix_axesscrewresultss                          r   helix_analysisrf      s   v min,Gwqrr{*I]9%%F#2#;+L Yss^Yqrr];;lJI	2q))IYy!!F:f%%Lbe)f, x	#2#	!""66H*w}X6669Jz**J726*1555J7KLLNL:z|44J|~%z1 J *RYrwz2q'A'ABBCCK+k!444K 31i#89E HY!^U\3->!,CDDEfW\'!B$-<<==G'kF25 "o""$$GCRCLLLU3CRC8::==LLLBKKK595b999KKK#G,,JBJx((*@ E
 %2 " "8  !# G Nr   c            	       d     e Zd ZdZdddddddddZ	 	 	 	 	 d fd	ZddZd Zd Zd Z	d Z
 xZS )HELANALa   
    Perform HELANAL helix analysis on your trajectory.

    Parameters
    ----------
    universe : Universe or AtomGroup
        The Universe or AtomGroup to apply the analysis to.
    select : str or iterable of str, optional
        The selection string to create an atom selection that the HELANAL
        analysis is applied to. Note that HELANAL is designed to work on the
        alpha-carbon atoms of protein residues. If you pass in multiple
        selections, the selections will be analysed separately.
    ref_axis : array-like of length 3, optional
        The reference axis used to calculate the tilt of the vector
        of best fit, and the local screw angles.
    flatten_single_helix : bool, optional
        Whether to flatten results if only one selection is passed.
    split_residue_sequences : bool, optional
        Whether to split the residue sequence into individual helices.
        This keyword only applies if a residue gap is present in the
        AtomGroup generated by a ``select`` string.
        If ``False``, the residues will be analysed as a single helix.
        If ``True``, each group of consecutive residues will be treated
        as a separate helix.
    verbose : bool, optional
        Turn on more logging and debugging.

    Attributes
    ----------
    results.local_twists : array or list of arrays
        The local twist angle from atom i+1 to i+2.
        Each array has shape (n_frames, n_residues-3)
    results.local_nres_per_turn : array or list of arrays
        Number of residues per turn, based on local_twist.
        Each array has shape (n_frames, n_residues-3)
    results.local_axes : array or list of arrays
        The length-wise helix axis of the local window.
        Each array has shape (n_frames, n_residues-3, 3)
    results.local_heights : array or list of arrays
        The rise of each local helix.
        Each array has shape (n_frames, n_residues-3)
    results.local_helix_directions : array or list of arrays
        The unit vector from each local origin to atom i+1.
        Each array has shape (n_frames, n_residues-2, 3)
    results.local_origins :array or list of arrays
        The projected origin for each helix.
        Each array has shape (n_frames, n_residues-2, 3)
    results.local_screw_angles : array or list of arrays
        The local screw angle for each helix.
        Each array has shape (n_frames, n_residues-2)
    results.local_bends : array or list of arrays
        The angles between local helix axes, 3 windows apart.
        Each array has shape (n_frames, n_residues-6)
    results.all_bends : array or list of arrays
        The angles between local helix axes.
        Each array has shape (n_frames, n_residues-3, n_residues-3)
    results.global_axis : array or list of arrays
        The length-wise axis for the overall helix. This points at
        the first helix window in the helix, so it runs opposite to
        the direction of the residue numbers.
        Each array has shape (n_frames, 3)
    results.global_tilts : array or list of arrays
        The angle between the global axis and the reference axis.
        Each array has shape (n_frames,)
    results.summary : dict or list of dicts
        Summary of stats for each property: the mean, the sample
        standard deviation, and the mean absolute deviation.
    ))i)rA   )ri   rA   )rj   )rE   rH   rI   rF   rK   rG   rJ   r?   name CAr   FTc           
      ,   t          t          |                               j        j        |           t          j        |          }fd|D             }g }	t          ||          D ]\  }
}t          j        |j	                  }d}t          |          dk    rYd                    |
          }|r&|d                    t          |                    z  }n|j	        g}t          j        |           |D ]}t          |          }||z  }|dk     r)t          j        d                    |
|                     Et          j        |d	
          \  }}t          j        |dk              rZd                    t%          t&          ||dk                                 }t          j        d                    |
|                     |	                    |||z
  |                    |	| _        t          j        |          | _        || _        d S )N)verbosec                 :    g | ]}                     |          S  )select_atoms).0r   universes     r   
<listcomp>z$HELANAL.__init__.<locals>.<listcomp>  s'    CCC1h++A..CCCr   r   r   z+Your selection {} has gaps in the residues.z Splitting into {} helices.	   u   Fewer than 9 atoms found for helix in selection {} with these resindices: {}. This sequence will be skipped. HELANAL is designed to work on at sequences of ≥9 residues.T)return_countsz, zYour selection {} includes multiple atoms for residues with these resindices: {}.HELANAL is designed to work on one alpha-carbon per residue.)superrh   __init__rr   
trajectoryr   
asiterablezip"group_same_or_consecutive_integers
resindicesrP   formatwarningswarnr   uniquer"   joinmapstrappend
atomgroupsr    r-   _flatten)selfrr   selectr-   rm   flatten_single_helixsplit_residue_sequences
selectionsr   consecutiver   aggroupscountermsggngidscountsdup	__class__s    `                  r   rw   zHELANAL.__init__  s"    	gt%%(' 	& 	
 	
 	
 _V,,
CCCC
CCC
Z00 "	? "	?EAr<R]KKFG6{{QCJJ1MM* -8??FLLLCC m_Fc""" ? ?VV266M) *01    i>>>V6&1*%% ))CS!_$=$=>>CM. /5fQnn	   ""2glW&<#=>>>>/?2 &
8,,,r   r   c                     |d         |z   }| j         |f|dd         z   }t          j        |t          j                  S )z<Create zero arrays where first 2 dims are n_frames, n_valuesr   r   N)dtype)n_framesr   zerosfloat64)r   dimsn_positionsfirstnpdimss        r   _zeros_per_framezHELANAL._zeros_per_frame  sN    Q+%M
 BB

 xbj1111r   c                      d  j         D             } j                                        D ]\  } fd|D             }| j        |<    fd|D              j        _         fd|D              j        _        d S )Nc                 ,    g | ]}t          |          S ro   )rP   )rq   r   s     r   rs   z$HELANAL._prepare.<locals>.<listcomp>  s    333RR333r   c                 >    g | ]}                     |           S ))r   r   )rq   nr   r   s     r   rs   z$HELANAL._prepare.<locals>.<listcomp>  s,    OOOAT**4Q*??OOOr   c                 :    g | ]}                     d           S )rA   r   rq   r   r   s     r   rs   z$HELANAL._prepare.<locals>.<listcomp>  s'    #O#O#OAD$9$9$$?$?#O#O#Or   c                 J    g | ]}                     |d z
  |d z
  f           S r   r   r   s     r   rs   z$HELANAL._prepare.<locals>.<listcomp>  s@     "
 "
 "
67D!!1q5!a%.11"
 "
 "
r   )r   attr_shapesitemsre   r,   rL   )r   n_reskeyemptyr   s   `   @r   _preparezHELANAL._prepare  s    334?333)//11 	& 	&ICOOOOOOOOE %DL#O#O#O#O#O#O#O "
 "
 "
 "
;@"
 "
 "
r   c                     | j         }t          | j                  D ]R\  }}t          |j        | j                  }|                                D ]\  }}| j        |         }|||         |<   Sd S )N)r-   )_frame_index	enumerater   rf   rU   r-   r   re   )r   _fir   re   r   valueattrs           r   _single_framezHELANAL._single_frame  s    t// 	$ 	$EAr$R\DMJJJG%mmoo $ $
U|C(#Q$	$ 	$r   c                    g x| j         _        }| j        dz                                  dz  }| j         j        D ]}t          j        | j        |j                  t          j	        |          |z  z  }t          j
        |dd          }|                    t          j        t          j        |                               g d}t          | j                                                  |z   }g | j         _        t%          t'          | j                            D ]}i }|D ]}	| j         |	         }
|
|                             d          }t          j        |
|         |z
            }||
|                             dd	          |                    d          d
||	<   | j         j                            |           t'          | j                  dk    r-| j        r(|dgz   D ]#}	| j         |	         }
|
d         | j         |	<    d S d S d S )Nr   rC   g      rD   )r,   global_tiltsrL   r   r	   r   )r
   ddof)r   	sample_sdabs_devsummary)re   r   r-   sumr,   r   r   r   r   r(   r*   r   r+   r)   listr   keysr   rangerP   r   r   rS   stdr   )r   tiltsnorm_refaxesr:   global_attrs	attrnamesr   statsnamer   r   devs                r   	_concludezHELANAL._conclude  s   ,..!EM1$))++s2L, 	5 	5D)DM4622d##h.C '#tS))CLLBIcNN334444CCC)..0011L@	!s4?++,, 	/ 	/AE!  |D)Aw|||++fT!Wt^,, !%a!!!<!<"xxQx// d
 L ''.... t1$$$!YK/ - -|D)%)!WT"" %$$$- -r   c                    	 | j         j        }n# t          $ r t          d          w xY wt	          |t
                    s|g}g }|D ]l}|j        d         }t          j        	                    ||t          j        |          d                              |          }|                    |           mt	          | j         j        t
                    s|d         }|S )z
        Create MDAnalysis Universe from the local origins.

        Returns
        -------
        Universe or list of Universes
        z'Call run() before universe_from_originsr   T)
n_residuesatom_resindexrx   r   )re   rK   AttributeError
ValueError
isinstancer   shapemdaUniverser   r   arangeload_newr   )r   rb   rr   xyzr   r   s         r   universe_from_originszHELANAL.universe_from_origins  s    	Hl0GG 	H 	H 	HFGGG	H '4(( 	 iG 	 	CIaLE""  i..	 #  
 hsmm  OOA$,4d;; 	#{Hs    ))rk   r   FTT)r   )__name__
__module____qualname____doc__r   rw   r   r   r   r   r   __classcell__)r   s   @r   rh   rh   9  s        C CN $ ")#	 	K ! $6- 6- 6- 6- 6- 6-p	2 	2 	2 	2

 

 

$ $ $ -  -  -D      r   rh   )r   )r   r~   numpyr   
MDAnalysisr   libr   r   baser   r   r?   rf   rh   ro   r   r   <module>r      s   0K KZ                         25  5  5 px x x xvg g g g gl g g g g gr   