
     izE                     \   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Zn5# e$ r- d	ZddlZ G d
 d          Z ej        d          Z
ee
_        Y nw xY w ed          Z ed          Zd Z G d dej                  Z G d dej                  Z G d de
j                  ZdS )a  
Reading trajectories with *chemfiles* --- :mod:`MDAnalysis.coordinates.chemfiles`
=================================================================================

MDAnalysis interoperates with the `chemfiles`_ library. The *chemfiles* C++ library
supports an expanding set of file formats, some of which are not natively supported by
MDAnalysis. Using the *CHEMFILES* reader you can use  `chemfiles`_ for the low-level
file reading. Check the list of `chemfile-supported file formats`_.

.. _chemfiles: https://chemfiles.org
.. _chemfile-supported file formats: https://chemfiles.org/chemfiles/latest/formats.html#list-of-supported-formats

Using the CHEMFILES reader
--------------------------

When reading, set the ``format="CHEMFILES"`` keyword argument and I/O is delegated to
`chemfiles`_. For example::

   >>> import MDAnalysis as mda
   >>> from MDAnalysis.tests import datafiles as data
   >>> u = mda.Universe(data.TPR, data.TRR, format="CHEMFILES")
   >>> print(u.trajectory)
   <ChemfilesReader ~/anaconda3/envs/mda3/lib/python3.8/site-packages/MDAnalysisTests/data/adk_oplsaa.trr with 10 frames of 47681 atoms>

You can then use the :class:`~MDAnalysis.core.universe.Universe` as usual while chemfiles
is handling the I/O transparently in the background.

`chemfiles`_ can also *write* a number of formats for which there are no Writers in
MDAnalysis. For example, to write a mol2 file::

   >>> u = mda.Universe(data.mol2_ligand)
   >>> with mda.Writer("ligand.mol2", format="CHEMFILES") as W:
   ...     W.write(u.atoms)




Classes
-------

Classes to read and write files using the `chemfiles`_ library. This library
provides C++ implementation of multiple formats readers and writers.

.. autoclass:: ChemfilesReader

.. autoclass:: ChemfilesWriter

.. autoclass:: ChemfilesPicklable

Helper functions
----------------

.. autodata:: MIN_CHEMFILES_VERSION
.. autodata:: MAX_CHEMFILES_VERSION
.. autofunction:: check_chemfiles_version

    N)Version   )base   )store_init_argumentsTFc                       e Zd ZdS )MockTrajectoryN)__name__
__module____qualname__     j/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/chemfiles.pyr	   r	   ^   s        r   r	   	chemfilesz0.10z0.11c                      t           st          j        d           dS t          t          j                  } | t          k    o
| t          k     S )zCheck if an appropriate *chemfiles* is available

    Returns ``True`` if a usable chemfiles version is available,
    with :data:`MIN_CHEMFILES_VERSION` <= version <
    :data:`MAX_CHEMFILES_VERSION`

    .. versionadded:: 1.0.0
    zKchemfiles package not found, try installing it with 'pip install chemfiles'F)HAS_CHEMFILESwarningswarnr   r   __version__MIN_CHEMFILES_VERSIONMAX_CHEMFILES_VERSION)versions    r   check_chemfiles_versionr   m   sS      =	
 	
 	
 ui+,,G++O:O0OOr   c                        e Zd ZdZdZdddZed fd	            Zed             Z	d	 Z
d
 Zed             Zed             Zd Zd ZddZd ZddZ xZS )ChemfilesReadera  Coordinate reader using chemfiles.

    The file format to used is guessed based on the file extension. If no
    matching format is found, a ``ChemfilesError`` is raised. It is also
    possible to manually specify the format to use for a given file.

    .. versionadded:: 1.0.0
    r   fsAngstromtimelength c                 Z   t                      s't          d                    t                               t	          t
          |           j        |fi | || _        d| _        | 	                                  | j
        | j        fi | j        | _        |                                  dS )a  
        Parameters
        ----------
        filename : chemfiles.Trajectory or str
            the chemfiles object to read or filename to read
        chemfiles_format : str (optional)
            if *filename* was a string, use the given format name instead of
            guessing from the extension. The `list of supported formats
            <formats>`_ and the associated names is available in the chemfiles
            documentation.
        **kwargs : dict
            General reader arguments.

        Please install Chemfiles > {}N)r   RuntimeErrorformatr   superr   __init___format_cached_n_atoms_open	_Timestepn_atoms
_ts_kwargstsnext)selffilenamechemfiles_formatkwargs	__class__s       r   r'   zChemfilesReader.__init__   s      '(( 	6/00   	.ot$$-hAA&AAA'#

 $.AAAA		r   c                 D    t           ot          | t          j                  S )zCan this Reader read *thing*)r   
isinstancer   
Trajectory)things    r   _format_hintzChemfilesReader._format_hint   s    
 HE93G!H!HHr   c                     d| _         d| _        d| _        t          | j        t
          j                  r| j        | _        d S t          | j        d| j	                  | _        d S )NFr   r)
_closed_step_framer6   r1   r   r7   _fileChemfilesPicklabler(   r0   s    r   r*   zChemfilesReader._open   sW    
dmY%9:: 	NDJJJ+DM3MMDJJJr   c                 X    | j         s"| j                                         d| _         dS dS )zclose readerTN)r=   r@   closerB   s    r   rD   zChemfilesReader.close   s5    | 	 JDLLL	  	 r   c                     | j         j        S )znumber of frames in trajectory)r@   nstepsrB   s    r   n_frameszChemfilesReader.n_frames   s     z  r   c                     | j         1t          | j                            d          j                  | _         | j         S )z4number of atoms in the first frame of the trajectoryNr   )r)   lenr@   	read_stepatomsrB   s    r   r,   zChemfilesReader.n_atoms   s9     '#&tz';';A'>'>'D#E#ED ##r   c                 V    |                                   |                                  dS )zreopen trajectoryN)rD   r*   rB   s    r   _reopenzChemfilesReader._reopen   s     



r   c                 8    || _         |                                 S )zread frame i)r>   _read_next_timestep)r0   is     r   _read_framezChemfilesReader._read_frame   s    
'')))r   Nc                    | j         | j        k    rt          d          || j        }|| _        | j                            | j                   }|                     ||           |j        |_        | xj         dz  c_         |S )zcopy next frame into timestepz"trying to go over trajectory limitNr   )	r>   rG   IOErrorr.   r@   rJ   _frame_to_tsstepframe)r0   r.   rV   s      r   rO   z#ChemfilesReader._read_next_timestep   s}    :&&>???:B
$$TZ00%$$$:

a

	r   c                 V   t          |j                  | j        k    rt          d          t          j        |j        j        |j        j        f         |_	        |j
        dd         |j
        dd<   |                                r"d|_        |j        dd         |j        dd<   dS dS )z0convert a chemfiles frame to a :class:`TimeStep`zRThe number of atom changed in the trajectory. This is not supported by MDAnalysis.NT)rI   rK   r,   rS   npr_celllengthsangles
dimensions	positionshas_velocities
velocities)r0   rV   r.   s      r   rT   zChemfilesReader._frame_to_ts   s    u{t|++7  
 ej0%*2CCD/!!!,QQQ!! 	3 $B$/2BM!!!	3 	3r   c                 0    || j         }t          ||fi |S )z#Return writer for trajectory format)r,   ChemfilesWriter)r0   r1   r,   r3   s       r   WriterzChemfilesReader.Writer   s&    ?lGx;;F;;;r   )r!   N)r
   r   r   __doc__r%   unitsr   r'   staticmethodr9   r*   rD   propertyrG   r,   rM   rQ   rO   rT   rc   __classcell__r4   s   @r   r   r      s0         FZ00E     6 I I \IN N N      ! ! X! $ $ X$  
* * *
   3 3 3< < < < < < < <r   r   c                   L    e Zd ZdZdZdZdddZ	 	 	 	 ddZd Zd Z	d Z
d Zd
S )rb   a  
    Coordinate writer using chemfiles.

    The file format to used is guessed based on the file extension. If no
    matching format is found, a ``ChemfilesError`` is raised. It is also
    possible to manually specify the format to use for a given file.

    Chemfiles support writting to files with varying number of atoms if the
    underlying format support it. This is the case of most of text-based
    formats.

    .. versionadded:: 1.0.0
    r   Tr   r   r   r   wr!   Nc                    t                      s't          d                    t                              || _        || _        |dk    r|dk    rt          d          t          j        | j        ||          | _	        d| _
        |ct          |t                    r| j	                            |           dS |                     ||          }| j	                            |           dS dS )a  
        Parameters
        ----------
        filename: str
            filename of trajectory file.
        n_atoms: int
            number of atoms in the trajectory to write. This value is not
            used and can vary during trajectory, if the underlying format
            support it
        mode : str (optional)
            file opening mode: use 'a' to append to an existing file or 'w' to
            create a new file
        chemfiles_format : str (optional)
            use the given format name instead of guessing from the extension.
            The `list of supported formats <formats>`_ and the associated names
            is available in chemfiles documentation.
        topology : Universe or AtomGroup (optional)
            use the topology from this :class:`~MDAnalysis.core.groups.AtomGroup`
            or :class:`~MDAnalysis.core.universe.Universe` to write all the
            timesteps to the file
        **kwargs : dict
            General writer arguments.

        r#   arl   z.Expected 'a' or 'w' as mode in ChemfilesWriterFN)r   r$   r%   r   r1   r,   rS   r   r7   r@   r=   r6   strset_topology_topology_to_chemfiles)r0   r1   r,   moder2   topologyr3   s          r   r'   zChemfilesWriter.__init__  s    B '(( 	6/00   !3;;43;;JKKK)M4!1
 

 (C(( 2
''1111166xII
''11111  r   c                 |    t          | d          r)| j        s$| j                                         d| _        dS dS dS )z2Close the trajectory file and finalize the writingr=   TN)hasattrr=   r@   rD   rB   s    r   rD   zChemfilesWriter.closeE  sP    4## 	 DL 	 JDLLL	  	  	  	 r   c                    	 |j         }t          |d          r?|j        j        j        }|j        |j        k    r|}nX|                    |j                  }n=t          |d          r|j        j        }n # t          $ r d}t          |          dw xY w| 
                    |          }|                     |t          |j                             |_        | j                            |           dS )a3  Write information associated with ``obj`` at current frame into
        trajectory.

        Topology for the output is taken from the `obj` or default to the value
        of the `topology` keyword supplied to the :class:`ChemfilesWriter`
        constructor.

        If `obj` contains velocities, and the underlying format supports it, the
        velocities are written to the file. Writing forces is unsupported at the
        moment.

        Parameters
        ----------
        obj : AtomGroup or Universe
            The :class:`~MDAnalysis.core.groups.AtomGroup` or
            :class:`~MDAnalysis.core.universe.Universe` to write.


        .. versionchanged:: 2.0.0
           Deprecated support for Timestep argument has now been removed.
           Use AtomGroup or Universe as an input instead.
        universe
trajectoryz-Input obj is neither an AtomGroup or UniverseN)rK   ru   rw   rx   r.   r,   
copy_sliceindicesAttributeError	TypeError_timestep_to_chemfilesrq   rI   rs   r@   write)r0   objrK   ts_fullr.   errmsgrV   s          r   _write_next_framez!ChemfilesWriter._write_next_frameK  s    .	'IE
 sJ'' 
',14?em33 BB !++EM::BBl++ '^&  	. 	. 	.DFF##-	.  ++B//44S#ek:J:JKK
s   A5 5Bc                    t          j                    }|                    |j                   |j        r|j        dd         |j        dd<   |j        r-|                                 |j        dd         |j        dd<   |j	        +t          j        d          t          j        g d          }}n|j	        dd         }|j	        dd         }t          j        ||          |_        |S )z9
        Convert a Timestep to a chemfiles Frame
        N   )Z   r   g     V@)r   Frameresizer,   has_positionsr^   r_   add_velocitiesr`   r]   rX   zerosarrayUnitCellrZ   )r0   r.   rV   r[   r\   s        r   r}   z&ChemfilesWriter._timestep_to_chemfilesy  s    
 !!RZ    	1!#aaaEOAAA 	3  """"$-"2EQQQ =  hqkk28NNN+C+CVGGmBQB'G]122&F'88
r   c                    t          j                    }t          |d          s|                    |           |S i }|j        D ]}t          |dd          }t          |d|          }t          j        ||          }t          |d          rt          |j                  |d<   t          |d          rt          |j	                  |d<   t          |d          rt          |j                  |d<   t          |d	          rt          |d
d          }	|j        |                                vr"t          j        |	|j                  ||j        <   ||j                 }
t          |j                  }|
j                            |           t          |d          r|j        dk    rd|
d<   nd|
d<   |j                            |           |                                D ]}
|j                            |
           t          |dg           D ]8}|                    |j        d         j        |j        d         j                   9|S )zM
        Convert an AtomGroup or an Universe to a chemfiles Topology
        rK   namer!   typealtLocaltlocsegidsegindexresidresnamerecord_typeATOMTis_standard_pdbFbondsr   r   )r   Topologyru   r   rK   getattrAtomro   r   r   intr   r   keysResiduerI   appendr   valuesresiduesadd_bondix)r0   r   r,   rs   r   atomr   r   chemfiles_atomr   residueatom_idxbonds                r   rq   z&ChemfilesWriter._topology_to_chemfiles  sX    %''sG$$ 	OOG$$$O I  	2  	2D4,,D4..D&^D$77NtX&& <+.t{+;+;x(tW%% :*-dj//w'tZ(( @-0-?-?z*tW%% ;!$	266:X]]__44+4+<, ,HTZ( #4:.x~..$$X...4// ;'61159 1225: 12N!!.1111  (( 	. 	.G$$W---- C"-- 	B 	BDdjm.
10@AAAAr   )r   rl   r!   N)r
   r   r   re   r%   
multiframerf   r'   rD   r   r}   rq   r   r   r   rb   rb      s          FJ Z00E
 32 32 32 32j     ,  ,  , \  26 6 6 6 6r   rb   c                   0     e Zd ZdZd fd	Zd Zd Z xZS )rA   a  Chemfiles file object (read-only) that can be pickled.

    This class provides a file-like object (as returned by
    :class:`chemfiles.Trajectory`) that,
    unlike standard Python file objects,
    can be pickled. Only read mode is supported.

    When the file is pickled, path, mode, and format of the file handle
    are saved. On unpickling, the file is opened by path with mode,
    and saved format.
    This means that for a successful unpickle, the original file still has
    to be accessible with its filename.

    Note
    ----
    Can only be used with reading ('r') mode.
    Upon pickling, the current frame is reset. `universe.trajectory[i]` has
    to be used to return to its original frame.

    Parameters
    ----------
    filename : str
        a filename given a text or byte string.
    mode : 'r' , optional
        only 'r' can be used for pickling.
    format : '', optional
        guessed from the file extension if empty.

    Example
    -------
    ::

        f = ChemfilesPicklable(XYZ, 'r', '')
        print(f.read())
        f.close()

    can also be used as context manager::

        with ChemfilesPicklable(XYZ) as f:
            print(f.read())

    See Also
    ---------
    :class:`MDAnalysis.lib.picklable_file_io.FileIOPicklable`
    :class:`MDAnalysis.lib.picklable_file_io.BufferIOPicklable`
    :class:`MDAnalysis.lib.picklable_file_io.TextIOPicklable`
    :class:`MDAnalysis.lib.picklable_file_io.GzipPicklable`
    :class:`MDAnalysis.lib.picklable_file_io.BZ2Picklable`


    .. versionadded:: 2.0.0
    r<   r!   c                 z    |dk    rt          d          t                                          |||           d S )Nr<   z*Only read mode ('r') files can be pickled.)pathrr   r%   )
ValueErrorr&   r'   )r0   r   rr   r%   r4   s       r   r'   zChemfilesPicklable.__init__  s@    3;;IJJJdf=====r   c                 *    | j         | j        | j        fS rd   )r   _Trajectory__mode_Trajectory__formatrB   s    r   __getstate__zChemfilesPicklable.__getstate__  s    y$0$2JJJr   c                      | j         |  d S rd   )r'   )r0   argss     r   __setstate__zChemfilesPicklable.__setstate__	  s    tr   )r<   r!   )r
   r   r   re   r'   r   r   ri   rj   s   @r   rA   rA     si        3 3j> > > > > >
K K K      r   rA   )re   numpyrX   r   packaging.versionr   r!   r   lib.utilr   r   r   ImportErrortypesr	   
ModuleTyper7   r   r   r   
ReaderBaser   
WriterBaserb   rA   r   r   r   <module>r      s  ,8 8r      % % % % % %       + + + + + + MM  
* 
* 
*M LLL        ! --I)I
*     P P P&t< t< t< t< t<do t< t< t<nQ Q Q Q Qdo Q Q Qh? ? ? ? ?- ? ? ? ? ?s   % /AA