
     i30                         d Z ddlZddlZddlmZmZ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 ddZd Z G d dej                  Z G d dej                  ZdS )a  XDR based trajectory files --- :mod:`MDAnalysis.coordinates.XDR`
================================================================

This module contains helper function and classes to read the XTC and TRR file
formats.

See Also
--------
MDAnalysis.coordinates.XTC: Read and write GROMACS XTC trajectory files.
MDAnalysis.coordinates.TRR: Read and write GROMACS TRR trajectory files.
MDAnalysis.lib.formats.libmdaxdr: Low level xdr format reader
    N)getctimegetsizeisfilesplitjoin)FileLock   )base   )triclinic_box)store_init_argumentsnpzc                 R    t          |           \  }}t          |d| d|           S )a>  Return offset or its lock filename for XDR files.
    For this the filename is appended
    with `_offsets.{ending}`.

    Parameters
    ----------
    filename : str
        filename of trajectory
    ending : str (optional)
        fileending of offsets file

    Returns
    -------
    offset_filename : str

    .z	_offsets.)r   r   )filenameendingheadtails       d/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/XDR.pyoffsets_filenamer   0   s4    " xJD$1$1111222    c                     	 d t          j        |                                           D             S # t          t          f$ r t          j        d|  d           Y dS w xY w)zread offsets into dictionary.

    This assume offsets have been saved using numpy

    Parameters
    ----------
    filename : str
        filename of offsets

    Returns
    -------
    offsets : dict
        dictionary of offsets information

    c                     i | ]\  }}||	S  r   ).0kvs      r   
<dictcomp>z&read_numpy_offsets.<locals>.<dictcomp>V   s    ;;;A1;;;r   zFailed to load offsets file 
F)nploaditems
ValueErrorIOErrorwarningswarn)r   s    r   read_numpy_offsetsr'   E   sv     ;;!2!2!8!8!:!:;;;;     AXAAABBBuus   /2 )AAc                        e Zd ZdZe	 	 	 	 d fd	            Zed             Zd Zd Z	dd	Z
ed
             Zd Zd ZddZ xZS )XDRBaseReaderaD  Base class for libmdaxdr file formats xtc and trr

    This class handles integration of XDR based formats into MDAnalysis. The
    XTC and TRR classes only implement `_write_next_frame` and
    `_frame_to_ts`.

    .. _offsets-label:

    Notes
    -----
    XDR based readers store persistent offsets on disk. The offsets are used to
    enable access to random frames efficiently. These offsets will be generated
    automatically the  first time the  trajectory is opened.  Generally offsets
    are stored  in hidden  `*_offsets.npz` files.  Afterwards opening  the same
    file again is fast. It sometimes can happen that the stored offsets get out
    off sync with the trajectory they refer to. For this the offsets also store
    the number of atoms, size of the file and last modification time. If any of
    them change  the offsets are recalculated.  Writing of the offset  file can
    fail when the  directory where the trajectory file resides  is not writable
    or if the  disk is full. In this  case a warning message will  be shown but
    the offsets will nevertheless be used during the lifetime of the trajectory
    Reader. However, the  next time the trajectory is opened,  the offsets will
    have to be rebuilt again.

    .. versionchanged:: 1.0.0
       XDR offsets read from trajectory if offsets file read-in fails
    .. versionchanged:: 2.0.0
       Add a InterProcessLock when generating offsets
    .. versionchanged:: 2.4.0
       Use a direct read into ts attributes
    .. versionchanged:: 2.9.0
       Changed fasteners.InterProcessLock() to filelock.FileLock
    TNFc                     t          t          |           j        |fd|i| |                     | j                  | _        || _        | j        t          | j                  | _        n| j        j        | _        |s| 	                                 n| 
                    d           | j                                        }	 | j                                        }||j        |j        z
  }n
|| j        d<   | j                            d           n# t          $ r d}Y nw xY w | j        | j        fi | j        | _        d| _        |                     || j                   || j        _        t+          |j         | j        _        | j        r5| j        j        +|                     | j        j        dd                    dS dS dS )	a  
        Parameters
        ----------
        filename : str
            trajectory filename
        convert_units : bool (optional)
            convert units to MDAnalysis units
        sub : array_like (optional)
            `sub` is an array of indices to pick out the corresponding
            coordinates and load only them; this requires that the topology
            itself is that of the sub system.
        refresh_offsets : bool (optional)
            force refresh of offsets
        dt : float (optional)
            timestep in MDAnalysis units to load trajectory with;
            if `dt` is ``None``, the time is taken from the xdr file;
            else, the time is set to `dt` * frame
        **kwargs : dict
            General reader arguments.

        convert_unitsNTstoredtr	   r      )superr)   __init___filer   _xdr_sublenn_atoms_load_offsets_read_offsetsreadtime
_ts_kwargsseekStopIteration	_Timestepts_frame_frame_to_tsr.   r   box
dimensionsr+   convert_pos_from_native)
selfr   r+   subrefresh_offsetsr.   kwargsframe	xdr_frame	__class__s
            r   r1   zXDRBaseReader.__init__   s   > 	,mT""+	
 	
$1	
5;	
 	
 	
 JJt}--		9 ty>>DLL9,DL 	+    T***	  		((Iz^ej0(*%INN1 	 	 	BBB	 !$.AAAA%)))
*EI6 	Ew!-,,TW-?-CDDDDD	E 	E--s   AD D#"D#c                 n    |                      |          5 }|j        }d d d            n# 1 swxY w Y   |S N)r2   r6   )clsr   rH   fr6   s        r   parse_n_atomszXDRBaseReader.parse_n_atoms   sr    YYx   	 AiG	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 s   *..c                 8    | j                                          dS )zclose readerNr3   closerE   s    r   rS   zXDRBaseReader.close       	r   c                 `   t          | j                  }t          | j        d          }	 t          |          5 }	 ddd           n# 1 swxY w Y   nv# t          $ ri}t	          |t
                    s|j        t          j        k    r9t          j	        d| j         d           | 
                    d           Y d}~dS  d}~ww xY wt          |          5 }t          |          s$| 
                    d           	 ddd           dS t          |          }|s<t          j	        d	| d
           | 
                    d           	 ddd           dS dx}x}}	 t          | j                  |d         k    }t          | j                  |d         k    }| j        j        |d         k    }n# t"          $ r Y nw xY w|r|r|s+t          j	        d           | 
                    d           n | j                            |d                    ddd           dS # 1 swxY w Y   dS )zload frame offsets from file, reread them from the trajectory if that
        fails. To prevent the competition of generating the same offset file
        from multiple processes, an `InterProcessLock` is used.lock)r   Nz2Cannot write lock/offset file in same location as z . Using slow offset calculation.Fr,   TzReading offsets from zu failed, reading offsets from trajectory instead.
Consider setting 'refresh_offsets=True' when loading your Universe.ctimesizer6   zFReload offsets from trajectory
 ctime or size or n_atoms did not matchoffsets)r   r   r   OSError
isinstancePermissionErrorerrnoEROFSr%   r&   r8   r   r'   r   r   r3   r6   KeyErrorset_offsets)	rE   fname	lock_namefilelockedatactime_oksize_ok
n_atoms_oks	            r   r7   zXDRBaseReader._load_offsets   sR    !//$T]6BBB		)$$                		 		 		!_-- EK1G1GG}G G G   """///		 i   '	7H%== """...'	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 &e,,D 2E 2 2 2   """...)'	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7, /43H3w#DM22d7mC!$-00DL@!Y.$y/A

     7 7Z 7=   """....	%%d9o666O'	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7 '	7s   A A	A 	AA AA 
CACCC'H#A H#H#"AF54H#5
G?H#GAH##H'*H'c                 D   t          | j                  }| j        j        }|r}t	          | j                  }t          | j                  }	 t          j        ||||| j        j                   dS # t          $ r"}t          j        d|            Y d}~dS d}~ww xY wdS )z"read frame offsets from trajectory)rZ   rY   rX   r6   zCouldn't save offsets because: N)r   r   r3   rZ   r   r   r    savezr6   	Exceptionr%   r&   )rE   r-   rb   rZ   rX   rY   re   s          r   r8   zXDRBaseReader._read_offsets  s     //)# 	ET]++E4=))D	E# I-       E E ECCCDDDDDDDDDE	E 	Es   #A1 1
B;BBc                 *    t          | j                  S )znumber of frames in trajectory)r5   r3   rT   s    r   n_frameszXDRBaseReader.n_frames  s     49~~r   c                 ^   d| j         _        d| _        | j        j                                        }| j                                         | j                            | j        	                    d          d           t          |          dk    r| j                            |           dS dS )zreopen trajectoryr   zutf-8rN)r?   rI   r@   r3   rZ   copyrS   openr   encoder5   ra   )rE   rZ   s     r   _reopenzXDRBaseReader._reopen$  s    )#((**		t}++G44c:::w<<1I!!'***** r   c                    |dz
  | _         	 | j                            |           |                                 }n# t          $ r t          j        d           | j                                        }| j                            |           | 	                    d           | j                            |           |                                 }Y nw xY w|S )zread frame ir	   z/seek failed, recalculating offsets and retryingTr,   )
r@   r3   r<   _read_next_timestepr$   r%   r&   calc_offsetsra   r8   )rE   itimesteprZ   s       r   _read_framezXDRBaseReader._read_frame/  s    !e		2INN1//11HH 	2 	2 	2MKLLLi,,..GI!!'***T***INN1//11HHH	2 s   .; BCCc                 4    || j         } | j        |fd|i|S )z#Return writer for trajectory formatNr6   )r6   _writer)rE   r   r6   rH   s       r   WriterzXDRBaseReader.Writer>  s-    ?lGt|H@@g@@@@r   )TNFN)FrM   )__name__
__module____qualname____doc__r   r1   classmethodrP   rS   r7   r8   propertyrn   ru   r{   r~   __classcell__)rK   s   @r   r)   r)   ^   s          D  @E @E @E @E @E @ED   [
  =7 =7 =7~E E E E$   X	+ 	+ 	+  A A A A A A A Ar   r)   c                   (    e Zd ZdZ	 ddZd Zd ZdS )XDRBaseWriterz1Base class for libmdaxdr file formats xtc and trrTNc                 ~    || _         || _        || _        |                     | j         d          | _        || _        dS )a5  
        Parameters
        ----------
        filename : str
            filename of trajectory
        n_atoms : int
            number of atoms to be written
        convert_units : bool (optional)
            convert from MDAnalysis units to format specific units
        dt : float (optional)
            timestep in MDAnalysis units to write trajectory with;
            if `dt` is ``None``, time for a frame is set from the timestep;
            else, the time for a frame is `dt` * frame
        **kwargs : dict
            General writer arguments
        wN)r   _convert_unitsr6   r2   r3   _dt)rE   r   r6   r+   r.   rH   s         r   r1   zXDRBaseWriter.__init__H  s<    & !+JJt}c22	r   c                 8    | j                                          dS )zclose trajectoryNrR   rT   s    r   rS   zXDRBaseWriter.closea  rU   r   c                 .    |                                   d S rM   )rS   rT   s    r   __del__zXDRBaseWriter.__del__e  s    

r   )TN)r   r   r   r   r1   rS   r   r   r   r   r   r   E  sQ        ;; 9=   2      r   r   )r   )r   r^   numpyr    os.pathr   r   r   r   r   r%   rd   r    r
   lib.mdamathr   lib.utilr   r   r'   
ReaderBaser)   
WriterBaser   r   r   r   <module>r      s7  .       : : : : : : : : : : : : : :              ' ' ' ' ' ' + + + + + +3 3 3 3*  2dA dA dA dA dADO dA dA dAN! ! ! ! !DO ! ! ! ! !r   