B
    ba                 @   s   d Z ddlmZ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mZ dd	lmZmZmZmZmZ dd
lmZmZ ddlmZ G dd deZdd Zdd ZdS )z
This module contains classes for parsing and processing CHARMM parameter,
topology, and stream files. It only extracts atom properties from the
topology files and extracts all parameters from the parameter files

Author: Jason M. Swails
    )absolute_importdivisionprint_functionN)OrderedDict)copy)permutations   )ParameterErrorParameterWarning)AtomTypeDihedralTypeDihedralTypeListNoUreyBradleyUnassignedAtomType)	iteritems
itervalues)rangec               @   sf   e Zd ZdZdd Zdd ZedddZdd	d
Ze	dd Z
edd Zejdd Zdd ZdS )ParameterSeta  
    Stores a parameter set defining a force field

    Attributes
    ----------
    atom_types : dict(str:AtomType)
        Dictionary mapping the names of the atom types to the corresponding AtomType instances
    atom_types_int : dict(int:AtomType)
        Dictionary mapping the serial indexes of the atom types to the corresponding AtomType
        instances
    atom_types_tuple : dict((str,int):AtomType)
        Dictionary mapping the (name,number) tuple of the atom types to the corresponding AtomType
        instances
    bond_types : dict((str,str):AtomType)
        Dictionary mapping the 2-element tuple of the names of the two atom types involved in the
        bond to the BondType instances
    angle_types : dict((str,str,str):AngleType)
        Dictionary mapping the 3-element tuple of the names of the three atom types involved in the
        angle to the AngleType instances
    urey_bradley_types : dict((str,str,str):BondType)
        Dictionary mapping the 3-element tuple of the names of the three atom types involved in the
        angle to the BondType instances of the Urey-Bradley terms
    dihedral_types : dict((str,str,str,str):list(DihedralType))
        Dictionary mapping the 4-element tuple of the names of the four atom types involved in the
        dihedral to the DihedralType instances. Since each torsion term can be a multiterm
        expansion, each item corresponding to a key in this dict is a list of `DihedralType`s for
        each term in the expansion
    improper_types : dict((str,str,str,str):ImproperType)
        Dictionary mapping the 4-element tuple of the names of the four atom types involved in the
        improper torsion to the ImproperType instances
    improper_periodic_types : dict((str,str,str,str):DihedralType)
        Dictionary mapping the 4-element tuple of the names of the four atom types involved in the
        improper torsion (modeled as a Fourier series) to the DihedralType instances. Note, the
        central atom should always be put in the *third* position of the key
    rb_torsion_types : dict((str,str,str,str):RBTorsionType)
        Dictionary mapping the 4-element tuple of the names of the four atom types involved in the
        Ryckaert-Bellemans torsion to the RBTorsionType instances
    cmap_types : dict((str,str,str,str,str,str,str,str):CmapType)
        Dictionary mapping the 5-element tuple of the names of the five atom types involved in the
        correction map to the CmapType instances
    nbfix_types : dict((str,str):(float,float))
        Dictionary mapping the 2-element tuple of the names of the two atom types whose LJ terms are
        modified to the tuple of the (epsilon,rmin) terms for that off-diagonal term
    pair_types : dict((str,str):NonbondedExceptionType)
        Dictionary mapping the 2-element tuple of atom type names for which explicit exclusion rules
        should be applied
    parametersets : list(str)
        List of parameter set names processed in the current ParameterSet
    residues : dict(str:ResidueTemplate|ResidueTemplateContainer)
        A library of ResidueTemplate objects mapped to the residue name defined in the force field
        library files
    c             C   s   t   | _| _t  | _t  | _t  | _t  | _t  | _t  | _t  | _	t  | _
t  | _t  | _t  | _t  | _g | _d| _t  | _t  | _d | _| _t  | _d S )Nlorentzg      ?)r   
atom_typesZatom_types_stratom_types_intatom_types_tuple
bond_typesangle_typesurey_bradley_typesdihedral_typesimproper_typesimproper_periodic_typesrb_torsion_types
cmap_typesnbfix_types
pair_typesZparametersets_combining_ruleresiduespatchesZdefault_sceeZdefault_scnb_improper_key_map)self r'   0lib/python3.7/site-packages/parmed/parameters.py__init__K   s&    zParameterSet.__init__c             C   s  t |  }x$t| jD ]\}}t||j|< qW x$t| jD ]\}}t||j|< q<W x$t| jD ]\}}t||j|< qbW xFt| jD ]8\}}||jkrqt|}||j|< ||jtt|< qW xFt| j	D ]8\}}||j	krqt|}||j	|< ||j	tt|< qW xLt| j
D ]>\}}||j
kr0qt|}||j
|< ||j
tt|< qW xLt| jD ]>\}}||jkr~qft|}||j|< ||jtt|< qfW xLt| jD ]>\}}||jkr̐qt|}||j|< ||jtt|< qW x6t| jD ](\}}||jkrqt||j|< qW xLt| jD ]>\}}||jkrRq:t|}||j|< ||jtt|< q:W xLt| jD ]>\}}||jkrqt|}||j|< ||jtt|< qW xLt| jD ]>\}}||jkrqt|}||j|< ||jtt|< qW x&t| jD ]\}}t||j|< q$W x&t| jD ]\}}t||j|< qLW t| j|_| j|_|S )N)typer   r   r   r   r   r   tuplereversedr!   r   r   r   r   r   r   r   r#   r$   r%   combining_rule)r&   otherkeyitemtypr'   r'   r(   __copy__a   s    

 

 
 
 
 
  
 
 
zParameterSet.__copy__Tc          	   C   s&  |  }t  }x|jD ]}|jtdfkr`t|jd|j|j}||j	|j
|j|j ||j|j< qt|j}||jt|< |jdk	r||jt|< ||jt|t|f< qW | r&xp|jD ]f}|jjrt|jj }xH|D ]@}|jj| \}	}
}}||jf|jkr
q|	|
f|j|j|f< qW qW x|jD ]}|jdkrBq.|jj|jjf}||jkr|s.|j| |jkr.td| q.t|j}|jj|jjf}||j|< ||jtt|< q.W x|j D ]}|jdkrސq|jj|jj|j!jf}||j"kr(|s|j"| |jkrtd| qt|j}|jj|jj|j!jf}||j"|< ||j"tt|< |j#dkr|jj|jj|j!jf}t$|j%|< t$|j%tt|< qW x|j&D ]~}|jdkrȐq|j'r0xZt(|D ]N}||j)kr|s|j)| |jkrtd| qt|j}||j)|< qW q|jj|jj|j!j|j*jf}||j+kr|| r|st,|jt-r|j+| |jkrtd| n>t,|jt.rx.|j+| D ]}||jkrP qW td| qq||j+krt,|jt-r6d||< d|tt|< t|j}||j+|< ||j+tt|< n`x|j+| D ]6}|j/|jj/krB|st||jkrttd| P qBW t|j}|j+| 0| nt,|jt-rd||< d|tt|< t|j}||j+|< ||j+tt|< nJd||< d|tt|< t- }|0t|j ||j+|< ||j+tt|< qW x|j1D ]v}|jdkrRq>|jj|jj|j!j|j*jf}||j2kr|s>|j2| |jkr>td	| q>t|j|j2|< q>W x|j3D ]}|jdkrԐq|jj|jj|j!j|j*j|jj|j!j|j*j|j4jf}||j5krZ|s|j|j5| krtd
|d |d |d |d |d f qt|j}||j5|< ||j5tt|< qW t6|j%dk}x|j7D ]|}|jdks|jt$krqt8|}|dkrҐq|r||j%krt9:dt; t|j}||j%|< ||j%tt|< qW |s^t6|j%dkr^x*|j"D ] }||j%krNq:t$|j%|< q:W x|j<D ]}|jdkrzqf|jj|jjf}||j=kr|sf|j=| |jkrftd| qft|j}||j=|< ||j=tt|< qfW |j>s|j?s|j@s|jAs|j>s|jBr"tCd|S )a   Extracts known parameters from a Structure instance

        Parameters
        ----------
        struct : :class:`parmed.structure.Structure`
            The parametrized ``Structure`` instance from which to extract
            parameters into a ParameterSet
        allow_unequal_duplicates : bool, optional
            If True, if two or more unequal parameter types are defined by the
            same atom types, the last one encountered will be assigned. If
            False, an exception will be raised. Default is True

        Returns
        -------
        params : :class:`ParameterSet`
            The parameter set with all parameters defined in the Structure

        Notes
        -----
        The parameters here are copies of the ones in the Structure, so
        modifying the generated ParameterSet will have no effect on ``struct``.
        Furthermore, the *first* occurrence of each parameter will be used. If
        future ones differ, they will be silently ignored, since this is
        expected behavior in some instances (like with Gromacs topologies in the
        ff99sb-ildn force field) unless ``allow_unequal_duplicates`` is set to
        ``False``

        Dihedrals are a little trickier. They can be multi-term, which can be
        represented either as a *single* entry in dihedrals with a type of
        DihedralTypeList or multiple entries in dihedrals with a DihedralType
        parameter type. In this case, the parameter is constructed from either
        the first DihedralTypeList found or the first DihedralType of each
        periodicity found if no matching DihedralTypeList is found.

        Raises
        ------
        :class:`parmed.exceptions.ParameterError` if allow_unequal_duplicates is
        False and 2+ unequal parameters are defined between the same atom types.

        `NotImplementedError` if any AMOEBA potential terms are defined in the
        input structure
        Nz,Unequal bond types defined between %s and %sz2Unequal angle types defined between %s, %s, and %s   z9Unequal dihedral types defined between %s, %s, %s, and %sTz9Unequal dihedral types defined bewteen %s, %s, %s, and %sFz9Unequal improper types defined between %s, %s, %s, and %sz9Unequal CMAP types defined between %s, %s, %s, %s, and %sr   r            z2Angle corresponding to Urey-Bradley type not foundz,Unequal pair types defined between %s and %sz@Cannot extract parameters from an Amoeba-parametrized system yet)DdictZatoms	atom_typer   r   r*   ZmassZatomic_numberZset_lj_paramsepsilonrminZ
epsilon_14Zrmin_14r   r   strZnumberr   intr   Z	has_NBFIXZnbfixlistkeysr    Zbondsatom1atom2r   r	   r+   r,   Zanglesatom3r   Zfunctr   r   Z	dihedralsimproper_find_improper_keysr   atom4r   
isinstancer   r   ZperappendZ	impropersr   ZcmapsZatom5r   lenZurey_bradleys_find_ureybrad_keywarningswarnr
   Zadjustsr!   Ztrigonal_anglesZout_of_plane_bendsZtorsion_torsionsZstretch_bendsZpi_torsionsNotImplementedError)clsZstructZallow_unequal_duplicatesZparamsZfound_dihed_type_listatomr8   Zother_atomsZ
other_atomr:   r9   Zrmin14Z	epsilon14Zbondr/   r1   ZangleZdihedralZdttrB   ZcmapZurey_brads_preassignedureyZadjustr'   r'   r(   from_structure   sB   ,



 

 


 







  &

 
 

  

zParameterSet.from_structurec             C   sh   |  | j |  | j |  | j |r@|  | j |  | j |  | j |  | j |  | j | S )aW  
        This function goes through each of the parameter type dicts and
        eliminates duplicate types. After calling this function, every unique
        bond, angle, dihedral, improper, or cmap type will pair with EVERY key
        in the type mapping dictionaries that points to the equivalent type

        Parameters
        ----------
        do_dihedrals : bool=True
            Dihedrals can take the longest time to compress since testing their
            equality takes the longest (this is complicated by the existence of
            multi-term torsions). This flag will allow you to *skip* condensing
            the dihedral parameter types (for large parameter sets, this can cut
            the compression time in half)

        Returns
        -------
        self
            The instance that is being condensed

        Notes
        -----
        The return value allows you to condense the types at construction time.

        Example
        -------
        >>> params = ParameterSet().condense()
        >>> params
        <parmed.parameters.ParameterSet at 0x7f88757de090>
        )	_condense_typesr   r   r   r   r   r   r   r   )r&   Zdo_dihedralsr'   r'   r(   condense|  s     zParameterSet.condensec             C   sr   t |  }x`tt|d D ]L}|| }x>t|d t|D ](}|| }| | | | kr>| | | |< q>W qW dS )z
        Loops through the given dict and condenses all types.

        Parameter
        ---------
        typedict : dict
            Type dictionary to condense
        r   N)r=   r>   r   rG   )ZtypedictZkeylistiZkey1jZkey2r'   r'   r(   rQ     s    
zParameterSet._condense_typesc             C   s   | j S )N)r"   )r&   r'   r'   r(   r-     s    zParameterSet.combining_rulec             C   s   |dkrt d|| _d S )N)r   Z	geometricz/combining_rule must be "lorentz" or "geometric")
ValueErrorr"   )r&   valuer'   r'   r(   r-     s    c             C   s   ddl m}m} xvt| jD ]h}t||rVxX|D ] }x|D ]}| j|j |_q:W q0W qt||sht	dx|D ]}| j|j |_qnW qW dS )z. Assign atom types to atom names in templates r   )ResidueTemplateContainerResidueTemplatezWrong type!N)
Zparmed.modellerrW   rX   r   r#   rE   r   r*   r8   AssertionError)r&   rW   rX   ZresidueZresrM   r'   r'   r(   typeify_templates  s    



zParameterSet.typeify_templatesN)T)T)__name__
__module____qualname____doc__r)   r2   classmethodrP   rR   staticmethodrQ   propertyr-   setterrZ   r'   r'   r'   r(   r      s   4< _
+r   c             C   s\   | j | j }}t|jt|j@ }tdd |D dkrDtdt |jt	|d j|jfS )z
    Finds a key for a given Urey-Bradley by finding the middle atom in an angle.
    Raises a ParameterWarning if no middle atom found
    c             S   s   h | ]
}|j qS r'   )r*   ).0ar'   r'   r(   	<setcomp>  s    z%_find_ureybrad_key.<locals>.<setcomp>r   z-Urey-Bradley %r shares multiple central atomsr   )
r?   r@   setbond_partnersrG   rI   rJ   r
   r*   r=   )rO   Za1Za2Zshared_bond_partnersr'   r'   r(   rH     s
    rH   c             #   s   | j std| j| j| j| jh}xp|D ]h xb|D ]}| kr@q2| jkr2P q2W x:t fdd|D D ] }|d |d  j|d fV  qhW dS q(W x@t| jj| jj| jjgD ]"}|d |d | jj|d fV  qW dS )z? Finds the central atom (i.e., that bonded to everything else) z%Should not be called on non-improper!c                s   g | ]}| k	r|j qS r'   )r*   )rc   rd   )rM   r'   r(   
<listcomp>  s    z'_find_improper_keys.<locals>.<listcomp>r   r   r4   N)	rB   rY   r?   r@   rA   rD   rg   r   r*   )ZdihZ	all_atomsZoatomr/   r'   )rM   r(   rC     s    


  rC   )r^   Z
__future__r   r   r   rI   collectionsr   r   	itertoolsr   
exceptionsr	   r
   Ztopologyobjectsr   r   r   r   r   Z	utils.sixr   r   Zutils.six.movesr   objectr   rH   rC   r'   r'   r'   r(   <module>   s      >