
     igd                        d Z ddlZddlZddlmZ ddlmZ ddl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 ddlmZ ddlmZmZ  ee          5  ddlmZ ddd           n# 1 swxY w Y   dddddddddd	Z e            Zej        Zej        Zej        Zej         Z  e e                      j!        Z! G d dej"                  Z# G d dej$                  Z% ed          ddefd            a&d  Z'd*d"Z(d# Z)d$ Z*d% Z+d& Z,d' Z-d( Z.e/e)e0e*e
j1        e+e
j2        e+e3e,e
j4        e-e
j5        e-e
j6        e-e
j7        e-e
j8        e-e
j9        e-e
j:        e-e
j;        e-iZ<d) Z=dS )+a	  RDKit molecule I/O --- :mod:`MDAnalysis.converters.RDKit`
================================================================

Read coordinates data from an `RDKit <https://www.rdkit.org/docs/>`__
:class:`rdkit.Chem.rdchem.Mol` with
:class:`RDKitReader` into an MDAnalysis Universe. Convert it back to a
:class:`rdkit.Chem.rdchem.Mol` with :class:`RDKitConverter`.


Example
-------

To read an RDKit molecule and then convert the AtomGroup back to an RDKit
molecule::

    >>> from rdkit import Chem
    >>> import MDAnalysis as mda
    >>> mol = Chem.MolFromMol2File("docking_poses.mol2", removeHs=False)
    >>> u = mda.Universe(mol)
    >>> u
    <Universe with 42 atoms>
    >>> u.trajectory
    <RDKitReader with 10 frames of 42 atoms>
    >>> u.atoms.convert_to("RDKIT")
    <rdkit.Chem.rdchem.Mol object at 0x7fcebb958148>


.. warning::
    The RDKit converter is currently *experimental* and may not work as
    expected for all molecules. Currently the converter accurately
    infers the structures of approximately 99% of the `ChEMBL27`_ dataset.
    Work is currently ongoing on further improving this and updates to the
    converter are expected in future releases of MDAnalysis.
    Please see `Issue #3339`_ and the `RDKitConverter benchmark`_ for more
    details.

Instead of using the default bond-order and charge inferring algorithm that
relies on the topology alone and the presence of explicit hydrogen atoms, you
can also use alternative builtin algorithms (see the
:mod:`~MDAnalysis.converters.RDKitInferring` module) or even your own function
to modify the RDKit molecule::

    >>> template = Chem.MolFromSmiles("CC(=O)Oc1ccccc1C(=O)O")
    >>> inferrer = mda.converters.RDKitInferring.TemplateInferrer(
    ...     template=template
    ... )
    >>> u.atoms.convert_to.rdkit(inferrer=inferrer)
    <rdkit.Chem.rdchem.Mol at 0x7f70ee6f3ca0>
    >>> def dummy_inferrer(mol):
    ...     # assign bond orders and do any other modification here
    ...     return mol
    >>> u.atoms.convert_to.rdkit(inferrer=dummy_inferrer)
    <rdkit.Chem.rdchem.Mol at 0x7f70ee6f2b90>


Classes
-------

.. autoclass:: RDKitReader
   :members:

.. autoclass:: RDKitConverter
   :members:


.. Links

.. _`ChEMBL27`: https://ftp.ebi.ac.uk/pub/databases/chembl/ChEMBLdb/releases/chembl_27/
.. _`Issue #3339`: https://github.com/MDAnalysis/mdanalysis/issues/3339
.. _`RDKitConverter benchmark`: https://github.com/MDAnalysis/RDKitConverter-benchmark
    N)suppress)	lru_cache)StringIO   )memory)	PDBWriter)_TOPOLOGY_ATTRS)NoDataError   )base)RDBONDORDERMDAnalysisInferrerChemAltLocChainIdInsertionCodeName	OccupancyResidueNameResidueNumberSegmentNumber
TempFactor)	altLocschainIDsicodesnamesoccupanciesresnamesresids
segindicestempfactorsc                   F     e Zd ZdZdZdddZed             Z fdZ xZ	S )RDKitReaderz>Coordinate reader for RDKit.

    .. versionadded:: 2.0.0
    RDKITNAngstromtimelengthc                 ^    	 ddl m} n# t          $ r Y dS w xY wt          | |j                  S )zCan this reader read *thing*?r   r   F)rdkitr   ImportError
isinstanceMol)thingr   s     e/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/converters/RDKit.py_format_hintzRDKitReader._format_hint   sR    	""""""" 	 	 	55	 %***s   	 
c                    |                                 }t          j        d |                                D             t          j                  }|j        dk    rHt          j        d           t          j        d|dft          j                  }t          j	        |dd<    t          t          |           j        |fdd	i| dS )
a  Read coordinates from an RDKit molecule.
        Each conformer in the original RDKit molecule will be read as a frame
        in the resulting universe.

        Parameters
        ----------
        filename : rdkit.Chem.rdchem.Mol
            RDKit molecule
        c                 6    g | ]}|                                 S  )GetPositions).0confs     r0   
<listcomp>z(RDKitReader.__init__.<locals>.<listcomp>   s$    FFFTT  FFF    )dtyper   z*No coordinates found in the RDKit moleculer      Norderfac)GetNumAtomsnparrayGetConformersfloat32sizewarningswarnemptynansuperr$   __init__)selffilenamekwargsn_atomscoordinates	__class__s        r0   rI   zRDKitReader.__init__   s     &&((hFFX-C-C-E-EFFF*
 
 
 q  MFGGG(Aw?"*EEEKVKN)k4  )+MMUMfMMMMMr9   )
__name__
__module____qualname____doc__formatunitsstaticmethodr1   rI   __classcell__)rO   s   @r0   r$   r$      sz         
 F Z00E+ + \+N N N N N N N N Nr9   r$   c                   0    e Zd ZdZdZdddZdddefdZdS )	RDKitConvertera  Convert MDAnalysis :class:`~MDAnalysis.core.groups.AtomGroup` or
    :class:`~MDAnalysis.core.universe.Universe` to RDKit
    :class:`~rdkit.Chem.rdchem.Mol`

    MDanalysis attributes are stored in each RDKit
    :class:`~rdkit.Chem.rdchem.Atom` of the resulting molecule in two different
    ways:

    * in an :class:`~rdkit.Chem.rdchem.AtomPDBResidueInfo` object available
      through the :meth:`~rdkit.Chem.rdchem.Atom.GetMonomerInfo` method if it's
      an attribute that is typically found in a PDB file,
    * directly as an atom property available through the
      :meth:`~rdkit.Chem.rdchem.Atom.GetProp` methods for the others.

    Supported attributes:

    +-----------------------+-------------------------------------------+
    | MDAnalysis attribute  | RDKit                                     |
    +=======================+===========================================+
    | altLocs               | atom.GetMonomerInfo().GetAltLoc()         |
    +-----------------------+-------------------------------------------+
    | chainIDs              | atom.GetMonomerInfo().GetChainId()        |
    +-----------------------+-------------------------------------------+
    | icodes                | atom.GetMonomerInfo().GetInsertionCode()  |
    +-----------------------+-------------------------------------------+
    | names                 | atom.GetMonomerInfo().GetName()           |
    |                       | atom.GetProp("_MDAnalysis_name")          |
    +-----------------------+-------------------------------------------+
    | occupancies           | atom.GetMonomerInfo().GetOccupancy()      |
    +-----------------------+-------------------------------------------+
    | resnames              | atom.GetMonomerInfo().GetResidueName()    |
    +-----------------------+-------------------------------------------+
    | resids                | atom.GetMonomerInfo().GetResidueNumber()  |
    +-----------------------+-------------------------------------------+
    | segindices            | atom.GetMonomerInfo().GetSegmentNumber()  |
    +-----------------------+-------------------------------------------+
    | tempfactors           | atom.GetMonomerInfo().GetTempFactor()     |
    +-----------------------+-------------------------------------------+
    | charges               | atom.GetDoubleProp("_MDAnalysis_charge")  |
    +-----------------------+-------------------------------------------+
    | indices               | atom.GetIntProp("_MDAnalysis_index")      |
    +-----------------------+-------------------------------------------+
    | segids                | atom.GetProp("_MDAnalysis_segid")         |
    +-----------------------+-------------------------------------------+
    | types                 | atom.GetProp("_MDAnalysis_type")          |
    +-----------------------+-------------------------------------------+

    Example
    -------

    To access MDAnalysis properties::

        >>> import MDAnalysis as mda
        >>> from MDAnalysis.tests.datafiles import PDB_full
        >>> u = mda.Universe(PDB_full)
        >>> mol = u.select_atoms('resname DMS').convert_to('RDKIT')
        >>> mol.GetAtomWithIdx(0).GetMonomerInfo().GetResidueName()
        'DMS'

    To create a molecule for each frame of a trajectory::

        from MDAnalysisTests.datafiles import PSF, DCD
        from rdkit.Chem.Descriptors3D import Asphericity

        u = mda.Universe(PSF, DCD, to_guess=['elements'])
        ag = u.select_atoms("resid 1-10")

        for ts in u.trajectory:
            mol = ag.convert_to("RDKIT")
            x = Asphericity(mol)


    Notes
    -----

    The converter requires the :class:`~MDAnalysis.core.topologyattrs.Elements`
    attribute to be present in the topology, else it will fail.

    It also requires the `bonds` attribute, although they will be automatically
    guessed if not present.

    Hydrogens should be explicit in the topology file. If this is not the case,
    use the parameter ``implicit_hydrogens=True`` when using the converter to
    allow implicit hydrogens, and ``inferrer=None`` to disable inferring bond
    orders and charges. You can also pass your own callable function to
    ``inferrer`` to assign bond orders and charges as you see fit::

        >>> from rdkit import Chem
        >>> from rdkit.Chem.AllChem import AssignBondOrdersFromTemplate
        >>> template = Chem.MolFromSmiles("NC(Cc1ccccc1)C(=O)O")
        >>> def infer_from_template(mol: Chem.Mol) -> Chem.Mol:
        ...     return AssignBondOrdersFromTemplate(template, mol)
        >>> mol = u.atoms.convert_to.rdkit(inferrer=infer_from_template)


    Note that all builtin inferrer functions can be found in the
    :mod:`RDKitInferring` module.

    Since one of the main use case of the converter is converting trajectories
    and not just a topology, creating a new molecule from scratch for every
    frame would be too slow so the converter uses a caching system. The cache
    only stores the 2 most recent AtomGroups that were converted, and is
    sensitive to the arguments that were passed to the converter. The number of
    objects cached can be changed with the function
    :func:`set_converter_cache_size`. However, ``ag.convert_to("RDKIT")``
    followed by ``ag.convert_to("RDKIT", implicit_hydrogens=False)`` will not
    use the cache since the arguments given are different. You can pass a
    ``cache=False`` argument to the converter to bypass the caching system.

    The ``_MDAnalysis_index`` property of the resulting molecule corresponds
    to the index of the specific :class:`~MDAnalysis.core.groups.AtomGroup`
    that was converted, which may not always match the ``index`` property.

    To get a better understanding of how the converter works under the hood,
    please refer to the following RDKit UGM presentation:

    * `Video (4:55 to 8:05) <https://youtu.be/5b5wYmK4URU>`__
    * `Slides <https://github.com/rdkit/UGM_2020/blob/master/Presentations/C%C3%A9dricBouysset_From_RDKit_to_the_Universe.pdf>`__

    There are some molecules containing specific patterns that the default
    inferrer cannot currently tackle correctly. See
    `Issue #3339 <https://github.com/MDAnalysis/mdanalysis/issues/3339>`__ for
    more info.

    .. versionadded:: 2.0.0

    .. versionchanged:: 2.2.0
        Improved the accuracy of the converter. Atoms in the resulting molecule
        now follow the same order as in the AtomGroup. The output of
        ``atom.GetMonomerInfo().GetName()`` now follows the guidelines for PDB
        files while the original name is still available through
        ``atom.GetProp("_MDAnalysis_name")``

    .. versionchanged:: 2.10.0
        Added ``inferrer`` to specify a callable that can transform the
        molecule (this operation is cached).

    .. deprecated:: 2.10.0
        Deprecated ``max_iter`` (moved to the inferrer class
        :class:`~MDAnalysis.converters.RDKitInferring.MDAnalysisInferrer`) and
        deprecated ``NoImplicit`` in favor of ``implicit_hydrogens``.

    r%   Nr&   r'   TFc                    	 ddl m} n# t          $ r t          d          dw xY w	 |j        }n/# t          $ r" t          dt          |          d          dw xY w|                    d          x}	?t          j	        dt                     t          |t                    rt          |		          }|                    d
          x}
!t          j	        dt                     |
 }|rd}t          |||          }|r"t          |fi |}t          j        |          }nt          j        |fi |}t%          |d          rt'          j        |j                                                  st'          j        |j        ddd          rt          j	        d           n |j        |                                          }|                                D ]Q}|                                }|j        |                             t:                    }|                    ||           R|                    |            |j         |            |j!        |           |S )a  Write selection at current trajectory frame to
        :class:`~rdkit.Chem.rdchem.Mol`.

        Parameters
        -----------
        obj : :class:`~MDAnalysis.core.groups.AtomGroup` or
            :class:`~MDAnalysis.core.universe.Universe`
        cache : bool
            Use a cached copy of the molecule's topology when available. To be
            used, the cached molecule and the new one have to be made from the
            same AtomGroup selection and with the same arguments passed
            to the converter
        inferrer : Optional[Callable[[Chem.Mol], Chem.Mol]]
            A callable to infer bond orders and charges for the RDKit molecule
            created by the converter. If ``None``, inferring is skipped.
        implicit_hydrogens : bool
           Whether to allow implicit hydrogens on the molecule or not.
        force : bool
            Force the conversion when no hydrogens were detected but
            ``inferrer`` is not ``None``. Useful for inorganic molecules
            mostly.
        NoImplicit : bool
            Opposite of ``implicit_hydrogens``.

            .. deprecated:: 2.10.0
                Use ``implicit_hydrogens`` instead (with an opposite value).
        max_iter : int
            Maximum number of iterations to standardize conjugated systems.
            See :meth:`~MDAnalysis.converters.RDKitInferring.MDAnalysisInferrer._rebuild_conjugated_bonds`.

            .. deprecated:: 2.10.0
                Use ``inferrer=MDAnalysisInferrer(max_iter=...)`` instead.
        r   r   zRDKit is required for the RDKitConverter but it's not installed. Try installing it with 
`conda install -c conda-forge rdkit` or `pip install rdkit`Nz'No `atoms` attribute in object of type z*, please use a valid AtomGroup or Universemax_iterzWUsing `max_iter` is deprecated, use `inferrer=MDAnalysisInferrer(max_iter=...)` instead)r[   
NoImplicitzUsing `NoImplicit` is deprecated, use `implicit_hydrogens`  instead. To disable bond order and formal charge inferring, use `inferrer=None`)implicit_hydrogensforceinferrer	positionsg        g-q=)rtolatolzkNaN or empty coordinates detected in coordinates, the output molecule will not have 3D coordinates assigned)"r+   r   r,   atomsAttributeError	TypeErrortypegetrD   rE   DeprecationWarningr-   r   dictatomgroup_to_molcopydeepcopy__wrapped__hasattrr?   isnanr`   anyallclose	Conformerr>   GetAtomsGetIdxastypefloatSetAtomPositionAddConformerAssignStereochemistryFrom3DSetDoubleBondNeighborDirections)rJ   objcacher]   r^   r_   rL   r   agr[   r\   paramsmolr7   atomidxxyzs                    r0   convertzRDKitConverter.convertF  s   V	""""""" 	 	 	N  			BB 	 	 	;$s)) ; ; ;  	 

:...H;MF"  
 ($677 A-x@@@ **\222J?M& #	   &0!   1
 
 

  	="20000C-$$CC".r<<V<<C 2{## 	:x%%))++ :r{c%0 0 0 :     &t~coo&7&788LLNN 3 3D++--C,s+22599C((c2222  &&&0055544S999
s   	 $0 ,A)rP   rQ   rR   rS   librU   DEFAULT_INFERERr   r4   r9   r0   rY   rY      s]        N N` CZ00E
   s s s s s sr9   rY   maxsizeFc           
         	 | j         }n# t          $ r t          d          dw xY wd| j         vr(|rt          j        d           n|t          d          |                    dd          x}!t          j        dt                     | }|rd}|rt          d| d	          i }t          D ]%}t          | |          rt          | |          ||<   &|                    d
d          d }	nfd}	i }
dD ]%}t          | |          rt          | |          |
|<   &t          j                    }| }i t          t          | |                    D ]\  }\  }}t          j        |                                          }|                    |           t          j                    }|                                D ]&\  }}t+          |||         | |	|                     '|                    |           |
                                D ]1\  }}dt.          |         j         }t3          ||||                    2t3          |d|           |                    |          }||j        <   	 | j         n8# t          $ r+ t          j        d           |                                  Y nw xY w| j        D ]_}	 fd|j        D             }n# t>          $ r Y #w xY wtA          j        |j!        t          j"        j#                  } |j$        g ||R   `|%                    d           | ||          }|S )a  Converts an AtomGroup to an RDKit molecule without coordinates.

    Parameters
    -----------
    ag : MDAnalysis.core.groups.AtomGroup
        The AtomGroup to convert
    implicit_hydrogens : bool
        Whether to allow implicit hydrogens on the molecule or not.
    force : bool
        Force the conversion when no hydrogens were detected but ``inferrer``
        is not ``None``. Useful for inorganic molecules mostly.
    inferrer : Optional[Callable[[rdkit.Chem.rdchem.Mol], rdkit.Chem.rdchem.Mol]]
        A callable to infer bond orders and charges for the RDKit molecule
        created by the converter. If ``None``, inferring is skipped.
    NoImplicit : bool
        Opposite of ``implicit_hydrogens``.

        .. deprecated:: 2.10.0
            Use ``implicit_hydrogens`` instead (with an opposite value).
    max_iter : int
        Maximum number of iterations to standardize conjugated systems.
        See :meth:`~MDAnalysis.converters.RDKitInferring.MDAnalysisInferrer._rebuild_conjugated_bonds`.

        .. deprecated:: 2.10.0
            Use ``inferrer=MDAnalysisInferrer(max_iter=...)`` instead.


    .. versionchanged:: 2.10.0
        Added ``inferrer`` to specify a callable that can transform the
        molecule (this operation is cached).

    .. deprecated:: 2.10.0
        Deprecated ``NoImplicit`` in favor of ``implicit_hydrogens``.
        Deprecated ``max_iter``, replaced by
        ``inferrer=MDAnalysisInferrer(max_iter=...)``.
    zThe `elements` attribute is required for the RDKitConverter but is not present in this AtomGroup. Please refer to the documentation to guess elements from other attributes or type `help(MDAnalysis.topology.guessers)`NHzKNo hydrogen atom found in the topology. Forcing to continue the conversion.a  No hydrogen atom could be found in the topology, but the converter requires all hydrogens to be explicit. You can use the parameter ``inferrer=None`` when using the converter to disable inferring bond orders and charges. You can also use ``force=True`` to ignore this error.r\   zUsing `NoImplicit` is deprecated, use `implicit_hydrogens` instead. To disable bond order and formal charge inferring, use `inferrer=None`zFound unexpected arguments: .r   c                     dS )N r4   )r   s    r0   get_resnamez%atomgroup_to_mol.<locals>.get_resname  s    2r9   c                     |          S Nr4   )r   r   s    r0   r   z%atomgroup_to_mol.<locals>.get_resname  s    C= r9   )chargessegidstypesr   _MDAnalysis__MDAnalysis_indexzQNo `bonds` attribute in this AtomGroup. Guessing bonds based on atoms coordinatesc                      g | ]
}|         S r4   r4   )r6   iatom_mappers     r0   r8   z$atomgroup_to_mol.<locals>.<listcomp>G  s    AAAqKNAAAr9   F)strict)&elementsr
   rd   rD   rE   poprh   
ValueErrorRDATTRIBUTESrn   getattrrg   r   RWMol	enumeratezipAtom
capitalizeSetNoImplicitAtomPDBResidueInfoitems_add_mda_attr_to_rdkitSetMonomerInfor	   singular_set_atom_propertyAddAtomixbondsguess_bondsindicesKeyErrorr   r<   BondTypeSINGLEAddBondUpdatePropertyCache)r}   r]   r^   r_   rL   r   r\   	pdb_attrsattrr   other_attrsr   r   r   elementrdatommivaluesindexbondbond_indices	bond_typer   r   s                         @@r0   rj   rj     s;   X;   8
 

 	 "+ 	M6    ! ;   jjt444
A 		
 	
 	
 ",^ 	H CAAAABBB I 0 02t 	0%b$//IdO}}Z..H	 	 	 	
	! 	! 	! 	! 	! K7 2 22t 	2 'D 1 1K
*,,C''JK'B(9(9:: % %?D'7--//00Z((($&&%OO-- 	H 	HLD&"4BAGGGGb!!!'--// 	8 	8LD&B/$"7"@BBDvtVAY77776#6:::F##$DG
   #	
 	
 	
 	  . .	AAAADLAAALL 	 	 	H	ODJ0DEE	-\-9-----5)))hsmmJs,    '8J   2J54J5K
K#"K#c                 L     t          |           t          j                  adS )a7  Set the maximum cache size of the RDKit converter

    Parameters
    ----------
    maxsize : int or None
        If int, the cache will only keep the ``maxsize`` most recent
        conversions in memory. Using ``maxsize=None`` will remove all limits
        to the cache size, i.e. everything is cached.
    r   N)r   rj   rm   r   s    r0   set_converter_cache_sizer   V  s)     2y1112B2NOOr9   r   c                     t          |t          j                  r|                                }| dk    rt	          ||          }t
          |          } t          |d|           |           dS )a  Converts an MDAnalysis atom attribute into the RDKit equivalent and
    stores it into an RDKit :class:`~rdkit.Chem.rdchem.AtomPDBResidueInfo`.

    Parameters
    ----------
    attr : str
        Name of the atom attribute in MDAnalysis in the singular form
    value : object, np.int or np.float
        Attribute value as found in the AtomGroup
    mi : rdkit.Chem.rdchem.AtomPDBResidueInfo
        MonomerInfo object that will store the relevant atom attributes
    resname : str
        Residue name of the atom, if available
    r   SetN)r-   r?   genericitem_deduce_PDB_atom_namer   r   )r   valuer   resnamerdattrs        r0   r   r   d  so     %$$ 

w%eW55 $FGBf&&&&&r9   c                 2    |                      ||           d S r   )SetPropr   r   r   s      r0   _set_str_propr     s    LLur9   c                 2    |                      ||           d S r   )SetDoublePropr   s      r0   _set_float_propr     s    tU#####r9   c                 L    |                      |t          |                     d S r   )r   rv   r   s      r0   _set_np_float_propr     s$    tU5\\*****r9   c                 2    |                      ||           d S r   )
SetIntPropr   s      r0   _set_int_propr     s    OOD%     r9   c                 L    |                      |t          |                     d S r   )r   intr   s      r0   _set_np_int_propr     s"    OOD#e**%%%%%r9   c                     d S r   r4   r   s      r0   _ignore_propr     s    Dr9   c                 t    t                              t          |          t                    | ||           dS )z9Saves any attribute and value into an RDKit atom propertyN)_atom_property_dispatcherrg   rf   r   r   s      r0   r   r     s0    !!$u++|<<T4OOOOOr9   )r   )>rS   rk   rD   
contextlibr   	functoolsr   ior   numpyr?   rN   r   coordinates.PDBr   core.topologyattrsr	   
exceptionsr
   r   r   RDKitInferringr   r   r,   r+   r   r   r   _infer_bo_and_charges_standardize_patternsMONATOMIC_CATION_CHARGESSTANDARDIZATION_REACTIONSr   MemoryReaderr$   ConverterBaserY   rj   r   r   r   r   r   r   r   r   strrv   rB   float64r   int8int16int32int64uint8uint16uint32uint64r   r   r4   r9   r0   <module>r      sx  0F FP                                     ' ' ' ' ' ' 0 0 0 0 0 0 $ $ $ $ $ $       ; ; ; ; ; ; ; ;Xk                 !
 
 %$&&'= '= -F .H !	((**--C (N (N (N (N (N&% (N (N (NVG G G G GT' G G GT 1 
	V V V VrP P P' ' ' '6  $ $ $+ + +! ! !& & &	 	 	
 	?J"J"GHHHHIII "P P P P Ps   A%%A),A)