
     ib3                       d Z ddlZddl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mZ ddlmZ ddlmZmZmZmZ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 ddlmZmZm Z  ddlm!Z!  G d de"          Z# G d de#          Z$ G d de#          Z% G d de#          Z& G d de"          Z' G d dej(                  Z) G d de'e)          Z* G d d e*          Z+ G d! d"e,          Z- G d# d$e'e-          Z. G d% d&e*          Z/d' Z0 G d( d)e,          Z1 G d* d+e'e1          Z2 G d, d-e+          Z3 G d. d/e#          Z4dS )0a
  Base classes --- :mod:`MDAnalysis.coordinates.base`
===================================================

Derive, FrameIterator, Reader and Writer classes from the classes
in this module. The derived classes must follow the :ref:`Trajectory API`.


.. _FrameIterators:

FrameIterators
--------------

FrameIterators are "sliced trajectories" (a trajectory is a
:ref:`Reader <Readers>`) that can be iterated over. They are typically
created by slicing a trajectory or by fancy-indexing of a trajectory
with an array of frame numbers or a boolean mask of all frames.

Iterator classes used by the by the :class:`ProtoReader`:

.. autoclass:: FrameIteratorBase

.. autoclass:: FrameIteratorSliced

.. autoclass:: FrameIteratorAll

.. autoclass:: FrameIteratorIndices

.. autoclass:: StreamFrameIteratorSliced

.. _ReadersBase:

Readers
-------

Readers know how to take trajectory data in a given format and present it in a
common API to the user in MDAnalysis. There are two types of readers:

1. Readers for *multi frame trajectories*, i.e., file formats that typically
   contain many frames. These readers are typically derived from
   :class:`ReaderBase`.

2. Readers for *single frame formats*: These file formats only contain a single
   coordinate set. These readers are derived from
   :class:`SingleFrameReaderBase`.

The underlying low-level readers handle closing of files in different
ways. Typically, the MDAnalysis readers try to ensure that files are always
closed when a reader instance is garbage collected, which relies on
implementing a :meth:`~ReaderBase.__del__` method. However, in some cases, this
is not necessary (for instance, for the single frame formats) and then such a
method can lead to undesirable side effects (such as memory leaks). In this
case, :class:`ProtoReader` should be used.


.. autoclass:: ReaderBase
   :members:
   :inherited-members:

.. autoclass:: SingleFrameReaderBase
   :members:
   :inherited-members:

.. autoclass:: ProtoReader
   :members:

.. autoclass:: StreamReaderBase
   :members:
   
.. _WritersBase:

Writers
-------

Writers know how to write information in a :class:`Timestep` to a trajectory
file.

.. autoclass:: WriterBase
   :members:
   :inherited-members:

Converters
----------
Converters output information to other libraries.

.. deprecated:: 2.7.0
    All converter code has been moved to :mod:`MDAnalysis.converters` and will
    be removed from the :mod:`MDAnalysis.coordinates.base` module in 3.0.0.

.. autoclass:: ConverterBase
   :members:
   :inherited-members:

Helper classes
--------------

The following classes contain basic functionality that all readers and
writers share.

.. autoclass:: IOBase
   :members:

    N)AnyUnionOptionalListDict   )Timestep)core   )_READERS_READER_HINTS_SINGLEFRAME_WRITERS_MULTIFRAME_WRITERS_CONVERTERS)units)	AuxReader)	auxreader)get_auxreader_for)_AUXREADERS)
asiterable	Namespacestore_init_arguments)NamedStreamc                   J    e Zd ZdZd Zd Zed             Zed             Z	dS )FrameIteratorBaseaM  
    Base iterable over the frames of a trajectory.

    A frame iterable has a length that can be accessed with the :func:`len`
    function, and can be indexed similarly to a full trajectory. When indexed,
    indices are resolved relative to the iterable and not relative to the
    trajectory.

    .. versionadded:: 0.19.0

    c                     || _         d S N_trajectory)self
trajectorys     e/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/base.py__init__zFrameIteratorBase.__init__   s    %    c                     t                      r   NotImplementedErrorr    s    r"   __len__zFrameIteratorBase.__len__   s    !###r$   c                     t          | t                    r8| r6t          | d         t                    rt          j        | t                    S | S )Nr   dtype)
isinstancelistboolnparray)framess    r"   _avoid_bool_listz"FrameIteratorBase._avoid_bool_list   sJ    fd## 	0 	0:fQi3N3N 	08F$////r$   c                     | j         S r   r   r(   s    r"   r!   zFrameIteratorBase.trajectory   s    r$   N)
__name__
__module____qualname____doc__r#   r)   staticmethodr3   propertyr!    r$   r"   r   r      sr        
 
& & &$ $ $   \
     X     r$   r   c                   v     e Zd ZdZ fdZd Zd Zd Zed             Z	ed             Z
ed             Z xZS )	FrameIteratorSlicedaH  
    Iterable over the frames of a trajectory on the basis of a slice.

    Parameters
    ----------
    trajectory: ProtoReader
        The trajectory over which to iterate.
    frames: slice
        A slice to select the frames of interest.

    See Also
    --------
    FrameIteratorBase

    .. versionadded:: 0.19.0

    c                     t          t          |                               |           |                    |j        |j        |j                  \  | _        | _        | _	        d S r   )
superr=   r#   check_slice_indicesstartstopstep_start_stop_step)r    r!   r2   	__class__s      r"   r#   zFrameIteratorSliced.__init__   sW    
 	!4((11*===.8.L.LL&+v{/
 /
+TZr$   c                 B    t          | j        | j        | j                  S r   )range_lengthrA   rB   rC   r(   s    r"   r)   zFrameIteratorSliced.__len__   s    DJ	49===r$   c              #      K   t          | j        | j        | j                  D ]}| j        |         V  | j                                         d S r   )rangerA   rB   rC   r!   rewind)r    is     r"   __iter__zFrameIteratorSliced.__iter__   sW      tz49di88 	% 	%A/!$$$$$     r$   c           	         t          |t          j                  rt          |           }| |cxk     r|k     s%n t	          d                    ||                    |dk     rt          |           |z   }| j        || j        z  z   }| j        	                    |          S t          |t                    r|j        pd| j        z  }|j        =|j        |j        dk    r| j        }n<| j        t          |           dz
  | j        z  z   }n| j        |j        pd| j        z  z   }|j        Q|j        |j        dk    r |t          || j        |          dz
  |z  z   }n| j        }|t          j        |          z   }n| j        |j        pd| j        z  z   }t          |||          }t          | j        |          }||_        ||_        ||_        |S |                     |          }t          j        t+          t-          | j        | j        | j                                      |         }	t/          | j        |	          S )Nz3Index {} is out of range of the range of length {}.r   r   )r-   numbersIntegrallen
IndexErrorformatrA   rC   r!   _read_frame_with_auxslicerB   rI   r0   signr=   rD   rE   rF   r3   r1   r.   rK   FrameIteratorIndices)
r    framelengthrC   rA   lastrB   	new_sliceframe_iteratorr2   s
             r"   __getitem__zFrameIteratorSliced.__getitem__   s5   eW-.. *	AYYF7U++++V++++ !V"(&"7"79 9 9qyyD		E)J!22E?77>>>u%% !	AJO!ty0D{":%a JEE J#d))a-49)DDEE
ek&6Q$)%CCz!:%a L	4$H$H1$LPT#TTDD:Dbgdmm+zUZ_1	$AAeT400I0)LLN
 %*N!#'N #'N !! ))%00EXd5TY	#J#JKKLLUSF'@@@r$   c                     | j         S r   )rD   r(   s    r"   rA   zFrameIteratorSliced.start  s
    {r$   c                     | j         S r   )rE   r(   s    r"   rB   zFrameIteratorSliced.stop	  
    zr$   c                     | j         S r   rF   r(   s    r"   rC   zFrameIteratorSliced.step  ra   r$   )r5   r6   r7   r8   r#   r)   rN   r^   r:   rA   rB   rC   __classcell__rG   s   @r"   r=   r=      s         "
 
 
 
 
> > >! ! !
+A +A +AZ   X   X   X    r$   r=   c                   4     e Zd ZdZ fdZd Zd Zd Z xZS )FrameIteratorAllz
    Iterable over all the frames of a trajectory.

    Parameters
    ----------
    trajectory: ProtoReader
        The trajectory over which to iterate.

    See Also
    --------
    FrameIteratorBase

    .. versionadded:: 0.19.0

    c                 X    t          t          |                               |           d S r   )r?   rg   r#   )r    r!   rG   s     r"   r#   zFrameIteratorAll.__init__"  s(    %%..z:::::r$   c                     | j         j        S r   )r!   n_framesr(   s    r"   r)   zFrameIteratorAll.__len__%  s    ''r$   c                 *    t          | j                  S r   )iterr!   r(   s    r"   rN   zFrameIteratorAll.__iter__(  s    DO$$$r$   c                     | j         |         S r   )r!   r    rY   s     r"   r^   zFrameIteratorAll.__getitem__+  s    u%%r$   )	r5   r6   r7   r8   r#   r)   rN   r^   rd   re   s   @r"   rg   rg     so         ; ; ; ; ;( ( (% % %& & & & & & &r$   rg   c                   J     e Zd ZdZ fdZd Zd Zd Zed             Z	 xZ
S )rX   a!  
    Iterable over the frames of a trajectory listed in a sequence of indices.

    Parameters
    ----------
    trajectory: ProtoReader
        The trajectory over which to iterate.
    frames: sequence
        A sequence of indices.

    See Also
    --------
    FrameIteratorBase
    c                 R   t          t          |                               |           g | _        |D ]Z}t	          |t
          j                  st          d          |                    |          }| j        	                    |           [t          | j                  | _        d S )Nz Frames indices must be integers.)r?   rX   r#   _framesr-   rP   rQ   	TypeError_apply_limitsappendtuple)r    r!   r2   rY   rG   s       r"   r#   zFrameIteratorIndices.__init__>  s    "D))22:>>> 	' 	'EeW%566 D BCCC,,U33EL&&&&T\**r$   c                 *    t          | j                  S r   )rR   r2   r(   s    r"   r)   zFrameIteratorIndices.__len__H  s    4;r$   c              #      K   | j         D ]}| j                            |          V  | j                                         d S r   )r2   r!   rU   rL   rn   s     r"   rN   zFrameIteratorIndices.__iter__K  sP      [ 	> 	>E/66u======     r$   c                    t          |t          j                  r'| j        |         }| j                            |          S |                     |          }t          j        | j                  |         }t          | j        |          S r   )
r-   rP   rQ   r2   r!   rU   r3   r0   r1   rX   )r    rY   r2   s      r"   r^   z FrameIteratorIndices.__getitem__P  su    eW-.. 	AK&E?77>>>))%00EXdk**51F'@@@r$   c                     | j         S r   )rq   r(   s    r"   r2   zFrameIteratorIndices.framesY  s
    |r$   )r5   r6   r7   r8   r#   r)   rN   r^   r:   r2   rd   re   s   @r"   rX   rX   /  s         + + + + +     ! ! !
A A A   X    r$   rX   c                   p    e Zd ZdZddddZddZddZddZddZdd	Z	dd
Z
ddZddZd Zd Zd ZdS )IOBasezBase class bundling common functionality for trajectory I/O.

    .. versionchanged:: 0.8
       Added context manager protocol.
    N)timerZ   velocityTc                 p    t          j        d| j         d         d          }|dk    r|S |s||z  S ||z  }|S )a  Conversion of coordinate array x from native units to base units.

        Parameters
        ----------
        x : array_like
          Positions to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input `x` is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.


        .. versionchanged:: 0.7.5
           Keyword `inplace` can be set to ``False`` so that a
           modified copy is returned *unless* no conversion takes
           place, in which case the reference to the unmodified `x` is
           returned.

        rZ   Angstrom      ?r   get_conversion_factorr    xinplacefs       r"   convert_pos_from_nativezIOBase.convert_pos_from_nativei  sS    0 '(,
8(<jJ J77H 	q5L	Qr$   c                 p    t          j        d| j         d         d          }|dk    r|S |s||z  S ||z  }|S )a  Conversion of velocities array *v* from native to base units

        Parameters
        ----------
        v : array_like
          Velocities to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input *v* is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.


        .. versionadded:: 0.7.5
        speedr}   Angstrom/psr   r   r    vr   r   s       r"   convert_velocities_from_nativez%IOBase.convert_velocities_from_native  sQ    & 'TZ
+]< <77H 	q5L	Qr$   c                 p    t          j        d| j         d         d          }|dk    r|S |s||z  S ||z  }|S )a  Conversion of forces array *force* from native to base units

        Parameters
        ----------
        force : array_like
          Forces to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input *force* is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.

        .. versionadded:: 0.7.7
        forcekJ/(mol*Angstrom)r   r   r    r   r   r   s       r"   convert_forces_from_nativez!IOBase.convert_forces_from_native  sS    $ 'TZ(*=? ?77L 	u9
r$   c                 p    t          j        d| j         d         d          }|dk    r|S |s||z  S ||z  }|S )ad  Convert time *t* from native units to base units.

        Parameters
        ----------
        t : array_like
          Time values to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input `t` is modified in place and also returned
        (although note that scalar values `t` are passed by value in Python and
        hence an in-place modification has no effect on the caller.)  In-place
        operations improve performance because allocating new arrays is
        avoided.


        .. versionchanged:: 0.7.5
           Keyword `inplace` can be set to ``False`` so that a
           modified copy is returned *unless* no conversion takes
           place, in which case the reference to the unmodified `x` is
           returned.

        r|   psr   r   r    tr   r   s       r"   convert_time_from_nativezIOBase.convert_time_from_native  sQ    4 'DJv&. .77H 	q5L	Qr$   c                 p    t          j        dd| j         d                   }|dk    r|S |s||z  S ||z  }|S )a  Conversion of coordinate array `x` from base units to native units.

        Parameters
        ----------
        x : array_like
          Positions to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input `x` is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.


        .. versionchanged:: 0.7.5
           Keyword `inplace` can be set to ``False`` so that a
           modified copy is returned *unless* no conversion takes
           place, in which case the reference to the unmodified `x` is
           returned.

        rZ   r   r   r   r   s       r"   convert_pos_to_nativezIOBase.convert_pos_to_native  sQ    0 'j$*X"68 877H 	q5L	Qr$   c                 p    t          j        dd| j         d                   }|dk    r|S |s||z  S ||z  }|S )a  Conversion of coordinate array `v` from base to native units

        Parameters
        ----------
        v : array_like
          Velocities to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input `v` is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.


        .. versionadded:: 0.7.5
        r   r   r}   r   r   r   s       r"   convert_velocities_to_nativez#IOBase.convert_velocities_to_native  sQ    & ']DJz$:< <77H 	q5L	Qr$   c                 p    t          j        dd| j         d                   }|dk    r|S |s||z  S ||z  }|S )a  Conversion of force array *force* from base to native units.

        Parameters
        ----------
        force : array_like
          Forces to transform
        inplace : bool (optional)
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input `force` is modified in place and also returned.
        In-place operations improve performance because allocating new arrays
        is avoided.


        .. versionadded:: 0.7.7
        r   r   r   r   r   s       r"   convert_forces_to_nativezIOBase.convert_forces_to_native!  sS    & '($*W*=? ?77L 	u9
r$   c                 p    t          j        dd| j         d                   }|dk    r|S |s||z  S ||z  }|S )a  Convert time *t* from base units to native units.

        Parameters
        ----------
        t : array_like
          Time values to transform
        inplace : bool, optional
          Whether to modify the array inplace, overwriting previous data

        Note
        ----
        By default, the input *t* is modified in place and also
        returned. (Also note that scalar values *t* are passed by
        value in Python and hence an in-place modification has no
        effect on the caller.)

        .. versionchanged:: 0.7.5
           Keyword *inplace* can be set to ``False`` so that a
           modified copy is returned *unless* no conversion takes
           place, in which case the reference to the unmodified *x* is
           returned.

        r|   r   r   r   r   s       r"   convert_time_to_nativezIOBase.convert_time_to_native=  sQ    0 'D$*V,. .77H 	q5L	Qr$   c                     dS )zClose the trajectory file.Nr;   r(   s    r"   closezIOBase.close^      r$   c                     | S r   r;   r(   s    r"   	__enter__zIOBase.__enter__b  s    r$   c                 .    |                                   dS )NFr   )r    exc_typeexc_valexc_tbs       r"   __exit__zIOBase.__exit__e  s    

ur$   T)r5   r6   r7   r8   r   r   r   r   r   r   r   r   r   r   r   r   r;   r$   r"   r{   r{   ^  s          Tt<<E   B   8   6! ! ! !F   B   8   8   B        r$   r{   c                       e Zd ZdZd ZdS )_ReadermetazsAutomatic Reader registration metaclass

    .. versionchanged:: 1.0.0
       Added _format_hint functionality
    c                    t                               t           |||           	 t          |d                   }|D ]9}|                                }| t          |<   d|v r|d         j        t          |<   :d S # t          $ r Y d S w xY w)NrT   _format_hint)typer#   r   upperr   __func__r   KeyError)clsnamebases	classdictfmtfmt_names         r"   r#   z_Readermeta.__init__r  s    dD%333	QYx011C   Q Q#>>++%("!Y...7.G.PM(+Q Q  	 	 	DD	s   A7 7
BBN)r5   r6   r7   r8   r#   r;   r$   r"   r   r   k  s2         Q Q Q Q Qr$   r   c                      e Zd ZU dZeZeed<   eed<   e	ed<   e
ed<   d Zde
fdZed	             Zdefd
ZdefdZdefdZedefd            Zedefd            Zede
fd            Zed             Zed             Zd Zd Zej        d;d            Zd Zej        d             Zd Z d Z!d Z"d Z#d Z$d Z%d Z&	 	 	 	 	 d<d e'd!         d"e'd#         d$e'e
         d%e'e
         d&e'e
         d'e'e(         de)j*        fd(Z+	 	 	 d=d)e,e(e-e(e(f         f         d*e,e(e.f         d+e(ddfd,Z/d- Z0ed.             Z1d/ Z2d0 Z3d1 Z4	 	 d>d2Z5d3 Z6d4 Z7d5 Z8d;d6Z9ed7             Z:e:j;        d8             Z:d9 Z<d: Z=dS )?ProtoReaderak  Base class for Readers, without a :meth:`__del__` method.

    Extends :class:`IOBase` with most attributes and methods of a generic
    Reader, with the exception of a :meth:`__del__` method. It should be used
    as base for Readers that do not need :meth:`__del__`, especially since
    having even an empty :meth:`__del__` might lead to memory leaks.

    See the :ref:`Trajectory API` definition in
    :mod:`MDAnalysis.coordinates.__init__` for the required attributes and
    methods.

    See Also
    --------
    :class:`ReaderBase`


    .. versionchanged:: 0.11.0
       Frames now 0-based instead of 1-based
    .. versionchanged:: 2.0.0
       Now supports (un)pickle. Upon unpickling,
       the current timestep is retained by reconstrunction.
    .. versionchanged:: 2.8.0
       the modification of coordinates was preserved
       after serialization.
    _transformations_auxs	_filenamerj   c                 "    i | _         g | _        d S r   )r   r   r(   s    r"   r#   zProtoReader.__init__  s     
 r$   returnc                     | j         S r   )rj   r(   s    r"   r)   zProtoReader.__len__  s
    }r$   c                 P    t          d                    | j                            )a  Read the coordinate file and deduce the number of atoms

        Returns
        -------
        n_atoms : int
          the number of atoms in the coordinate file

        Raises
        ------
        NotImplementedError
          when the number of atoms can't be deduced
        z${} cannot deduce the number of atoms)r'   rT   r5   )r   filenamekwargss      r"   parse_n_atomszProtoReader.parse_n_atoms  s*     " #%%+VCL%9%9; ; 	;r$   c                 <   	 |                                  }| j                                        D ]%\  }}| j        |                             |          }&|                     |          }n1# t
          t          f$ r |                                  t          dw xY w|S )zForward one step to next frame.N)	_read_next_timestepr   items	update_ts_apply_transformationsEOFErrorIOErrorrL   StopIterationr    tsauxnamereaders       r"   nextzProtoReader.next  s    		1))++B
 $(:#3#3#5#5 7 7Z(22266,,R00BB '" 	* 	* 	*KKMMMT)	* 	s   A+ +.Bc                 *    |                                  S )z=Forward one step to next frame when using the `next` builtin.)r   r(   s    r"   __next__zProtoReader.__next__  s    yy{{r$   c                 V    |                                   |                                  dS )z#Position at beginning of trajectoryN)_reopenr   r(   s    r"   rL   zProtoReader.rewind  s     		r$   c                     | j         j        S )z2Time between two trajectory frames in picoseconds.)r   dtr(   s    r"   r   zProtoReader.dt  s     wzr$   c                 &    | j         dz
  | j        z  S )a\  Total length of the trajectory

        The time is calculated as ``(n_frames - 1) * dt``, i.e., we assume that
        the first frame no time as elapsed. Thus, a trajectory with two frames will
        be considered to have a length of a single time step `dt` and a
        "trajectory" with a single frame will be reported as length 0.

        r   )rj   r   r(   s    r"   	totaltimezProtoReader.totaltime  s     !TW,,r$   c                     | j         j        S )znFrame number of the current time step.

        This is a simple short cut to :attr:`Timestep.frame`.
        )r   rY   r(   s    r"   rY   zProtoReader.frame  s     w}r$   c                     | j         j        S )zTime of the current frame in MDAnalysis time units (typically ps).

        This is either read straight from the Timestep, or calculated as
        time = :attr:`Timestep.frame` * :attr:`Timestep.dt`
        )r   r|   r(   s    r"   r|   zProtoReader.time  s     w|r$   c                     | S r   r;   r(   s    r"   r!   zProtoReader.trajectory  s	     r$   c                      t          d          )z@A trajectory writer with the same properties as this trajectory.zSorry, there is no Writer for this format in MDAnalysis. Please file an enhancement request at https://github.com/MDAnalysis/mdanalysis/issuesr&   r    r   r   s      r"   WriterzProtoReader.Writer  s    !>? ? 	?r$   c                     | j         |d<   |                    d| j                   	 |                    d| j                   n# t          $ r Y nw xY wt          j        |fi |S )a  Returns a writer appropriate for *filename*.

        Sets the default keywords *start*, *step* and *dt* (if
        available). *n_atoms* is always set from :attr:`Reader.n_atoms`.


        See Also
        --------
        :meth:`Reader.Writer` and :func:`MDAnalysis.Writer`

        n_atomsrA   r   )r   
setdefaultrY   r   r   r
   writerr   s      r"   OtherWriterzProtoReader.OtherWriter  s     !Ly'4:...	dDG,,,, 	 	 	D	{8..v...s   A 
AANc                     d S r   r;   r    r   s     r"   r   zProtoReader._read_next_timestep  s	     	r$   c                 .    |                                   | S )z! Iterate over trajectory frames. )r   r(   s    r"   rN   zProtoReader.__iter__"  s    r$   c                     dS )zyShould position Reader to just before first frame

        Calling next after this should return the first frame
        Nr;   r(   s    r"   r   zProtoReader._reopen'  s	     	r$   c                     |dk     r|t          |           z  }|dk     s|t          |           k    r0t          d                    |t          |                               |S )Nr   z+Index {} exceeds length of trajectory ({}).)rR   rS   rT   rn   s     r"   rs   zProtoReader._apply_limits/  se    199SYYE199T**   &uc$ii 8 8: : :r$   c                    t          |t          j                  r*|                     |          }|                     |          S t          |t
          t          j        f          rt          |          dk    rit          |d         t          t          j
        f          rBt          j        |t                    }t          j        t          |                     |         }t          | |          S t          |t                    rh|                     |j        |j        |j                  \  }}}|dk    r(|t          |           k    r|dk    rt'          |           S t)          | |          S t+          d          )a|  Return the Timestep corresponding to *frame*.

        If `frame` is a integer then the corresponding frame is
        returned. Negative numbers are counted from the end.

        If frame is a :class:`slice` then an iterator is returned that
        allows iteration over that part of the trajectory.

        Note
        ----
        *frame* is a 0-based frame index.
        r   r+   r   zJTrajectories must be an indexed using an integer, slice or list of indices)r-   rP   rQ   rs   rU   r.   r0   ndarrayrR   r/   bool_asarrayarangerX   rV   r@   rA   rB   rC   rg   r=   rr   )r    rY   rA   rB   rC   s        r"   r^   zProtoReader.__getitem__7  sP    eW-.. 	9&&u--E,,U333bj122 	95zzQ:eAhrx8H#I#I
5555	#d)),,U3'e444u%% 		9 $ 8 8UZ!5 !5E4zzdc$ii//DAII'---*4777 8 9 9 9r$   c                 Z    t          d                    | j        j                            )z,Move to *frame* and fill timestep with data.z+{0} does not support direct frame indexing.)rr   rT   rG   r5   rn   s     r"   _read_framezProtoReader._read_frameY  s+     !6$."9::< < 	<r$   c                     |                      |          }| j        D ]"}| j        |                             |          }#|                     |          }|S )zQMove to *frame*, updating ts with trajectory, transformations and auxiliary data.)r   aux_listr   r   r   )r    rY   r   auxs       r"   rU   z ProtoReader._read_frame_with_auxd  sY    e$$= 	/ 	/CC**2..BB((,,	r$   c              #      K   	 t          |||          D ]}|                     |          V  |                                  dS # t          $ r  | j        j         d}t          |          dw xY w)a  Generator for slicing a trajectory.

        *start* *stop* and *step* are 3 integers describing the slice.
        Error checking is not done past this point.

        A :exc:`NotImplementedError` is raised if random access to
        frames is not implemented.
        z does not support slicing.N)rK   rU   rL   rr   rG   r5   )r    rA   rB   rC   rM   errmsgs         r"   _sliced_iterzProtoReader._sliced_itern  s      	.5$-- 3 3//222222KKMMMMM 	. 	. 	./KKKFF##-	.s   ?A *A/c                 "   |||d}|                                 D ]V\  }}t          |t          j                  rt	          |          ||<   2|5t          d                    |                    |d         }|d         }|d         }|dk    rt          d          t          |           }|pd	}||dk    rdn|d	z
  }n|dk     r||z  }|dk     rd}|dk     r||k    r|d	z
  }||dk    r|nd
}n|dk     r||z  }|dk    r||k    r|}|||fS )a_  Check frame indices are valid and clip to fit trajectory.

        The usage follows standard Python conventions for :func:`range` but see
        the warning below.

        Parameters
        ----------
        start : int or None
          Starting frame index (inclusive). ``None`` corresponds to the default
          of 0, i.e., the initial frame.
        stop : int or None
          Last frame index (exclusive). ``None`` corresponds to the default
          of n_frames, i.e., it includes the last frame of the trajectory.
        step : int or None
          step size of the slice, ``None`` corresponds to the default of 1, i.e,
          include every frame in the range `start`, `stop`.

        Returns
        -------
        start, stop, step : tuple (int, int, int)
          Integers representing the slice

        Warning
        -------
        The returned values `start`, `stop` and `step` give the expected result
        when passed in :func:`range` but gives unexpected behavior when passed
        in a :class:`slice` when ``stop=None`` and ``step=-1``

        This can be a problem for downstream processing of the output from this
        method. For example, slicing of trajectories is implemented by passing
        the values returned by :meth:`check_slice_indices` to :func:`range` ::

          range(start, stop, step)

        and using them as the indices to randomly seek to. On the other hand,
        in :class:`MDAnalysis.analysis.base.AnalysisBase` the values returned
        by :meth:`check_slice_indices` are used to splice the trajectory by
        creating a :class:`slice` instance ::

          slice(start, stop, step)

        This creates a discrepancy because these two lines are not equivalent::

            range(10, -1, -1)             # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
            range(10)[slice(10, -1, -1)]  # []

        rA   rB   rC   Nz{0} is not an integerrA   rB   rC   r   zStep size is zeror   )	r   r-   rP   rQ   intrr   rT   
ValueErrorrR   )r    rA   rB   rC   
slice_dictvarnamevarnframess           r"   r@   zProtoReader.check_slice_indices  ss   b  %dDAA
&,,.. 	I 	ILGS#w/00 I&)#hh
7##+ 7 > >w G GHHH7#&!&!1990111d))yq=AAw{EEQYYWE199E!88((aKE<"Qhh77BDDAXXGOD!88wDdD  r$   c                 f    d                     | j        j        | j        | j        | j                  S )Nz7<{cls} {fname} with {nframes} frames of {natoms} atoms>)r   fnamer   natoms)rT   rG   r5   r   rj   r   r(   s    r"   __repr__zProtoReader.__repr__  s7    6'-M<	  
 
	r$   facasel	AtomGroup	atomgroup	AtomgrouprA   rB   rC   orderc                    |.t          j        dt                     |rt          d          |}|                     |||          \  }}}t          t          |||                    }|9t          |          dk    rt          d          |j        }t          |          }	n| j        }	t          j
        |	          }t          j        ||	dft          j                  }
t          | |||                   D ]\  }}|j        |         |
|ddf<   d	|k    rn	 fd
|D             }n!# t          $ r t          d| d          w xY w	 t          j        |
|g d          }
n## t          $ r d| d}t          |          w xY w|
S )a  Return a subset of coordinate data for an AtomGroup

        Parameters
        ----------
        asel : AtomGroup (optional)
            The :class:`~MDAnalysis.core.groups.AtomGroup` to read the
            coordinates from. Defaults to ``None``, in which case the full set
            of coordinate data is returned.

            .. deprecated:: 2.7.0
                asel argument will be renamed to atomgroup in 3.0.0

        atomgroup: AtomGroup (optional)
            Same as `asel`, will replace `asel` in 3.0.0
        start :  int (optional)
            Begin reading the trajectory at frame index `start` (where 0 is the
            index of the first frame in the trajectory); the default
            ``None`` starts at the beginning.
        stop : int (optional)
            End reading the trajectory at frame index `stop`-1, i.e, `stop` is
            excluded. The trajectory is read to the end with the default
            ``None``.
        step : int (optional)
            Step size for reading; the default ``None`` is equivalent to 1 and
            means to read every frame.
        order : str (optional)
            the order/shape of the return data array, corresponding
            to (a)tom, (f)rame, (c)oordinates all six combinations
            of 'a', 'f', 'c' are allowed ie "fac" - return array
            where the shape is (frame, number of atoms,
            coordinates)

        See Also
        --------
        :class:`MDAnalysis.coordinates.memory`


        .. versionadded:: 2.4.0
        NzKasel argument to timeseries will be renamed to'atomgroup' in 3.0, see #3911)categoryz-Cannot provide both asel and atomgroup kwargsr   z0Timeseries requires at least one atom to analyze   r+   r  c                 :    g | ]}                     |          S r;   )index).0rM   default_orders     r"   
<listcomp>z*ProtoReader.timeseries.<locals>.<listcomp>,  s'    @@@Q---a00@@@r$   zUnrecognized order key in z, must be permutation of 'fac')r   r   r   z5Repeated or missing keys passed to argument `order`: z, each key must be used once)warningswarnDeprecationWarningr   r@   rR   rK   indicesr   r0   r   emptyfloat32	enumerate	positionsmoveaxis)r    r  r  rA   rB   rC   r
  r   atom_numbersr  coordinatesrM   r   newidxr   r  s                  @r"   
timeserieszProtoReader.timeseries  s-   X M0+- - - -  R !PQQQI 44UD$GGtTeE4..// 9~~"" FH H H$,L&&FF\F9V,,L h32:FFFtE$tO455 	; 	;EAr "\ :K111 M!!A@@@@%@@@ A A A  "@e "@ "@ "@ A A AA) k+vyyyII ) ) )J&+J J J ((() s   D. .EE) ) F	aux_specauxdatarT   c                     |t          d          t          |          t          t          j                              vrt          |          } ||          }n|} |j        | ||fi | dS )a\
  Add auxiliary data to be read alongside trajectory.

        Auxiliary data may be any data timeseries from the trajectory
        additional to that read in by the trajectory reader. *auxdata* can
        be an :class:`~MDAnalysis.auxiliary.base.AuxReader` instance, or the
        data itself as e.g. a filename; in the latter case an appropriate
        :class:`~MDAnalysis.auxiliary.base.AuxReader` is guessed from the
        data/file format. An appropriate `format` may also be directly provided
        as a key word argument.

        On adding, the AuxReader is initially matched to the current timestep
        of the trajectory, and will be updated when the trajectory timestep
        changes (through a call to :meth:`next()` or jumping timesteps with
        ``trajectory[i]``).

        The representative value(s) of the auxiliary data for each timestep (as
        calculated by the :class:`~MDAnalysis.auxiliary.base.AuxReader`) are
        stored in the current timestep in the ``ts.aux`` namespace under
        *aux_spec*; e.g. to add additional pull force data stored in
        pull-force.xvg::

            u = MDAnalysis.Universe(PDB, XTC)
            u.trajectory.add_auxiliary('pull', 'pull-force.xvg')

        The representative value for the current timestep may then be accessed
        as ``u.trajectory.ts.aux.pull`` or ``u.trajectory.ts.aux['pull']``.


        The following applies to energy readers like the
        :class:`~MDAnalysis.auxiliary.EDR.EDRReader`.

        All data that is present in the (energy) file can be added by omitting
        `aux_spec` like so::

            u.trajectory.add_auxiliary(auxdata="ener.edr")

        *aux_spec* is expected to be a dictionary that maps the desired
        attribute name in the ``ts.aux`` namespace to the precise data to be
        added as identified by a :attr:`data_selector`::

            term_dict = {"temp": "Temperature", "epot": "Potential"}
            u.trajectory.add_auxiliary(term_dict, "ener.edr")

        Adding this data can be useful, for example, to filter trajectory
        frames based on non-coordinate data like the potential energy of each
        time step. Trajectory slicing allows working on a subset of frames::

            selected_frames = np.array([ts.frame for ts in u.trajectory
                                        if ts.aux.epot < some_threshold])
            subset = u.trajectory[selected_frames]


        See Also
        --------
        :meth:`remove_auxiliary`

        Note
        ----
        Auxiliary data is assumed to be time-ordered, with no duplicates. See
        the :ref:`Auxiliary API`.
        Nz:No input `auxdata` specified, but it needs to be provided.)r   r   r.   r   valuesr   attach_auxiliary)r    r   r!  rT   r   reader_typer   s          r"   add_auxiliaryzProtoReader.add_auxiliary:  s    D ? / 0 0 0==[%7%9%9 : :::+G44K#G,,III"	"46DDVDDDDDr$   c                     |                      |          }|                                 ~t          | j        j        |           dS )zClear data and close the :class:`~MDAnalysis.auxiliary.base.AuxReader`
        for the auxiliary *auxname*.

        See Also
        --------
        :meth:`add_auxiliary`
        N)_check_for_auxr   delattrr   r   r    r   r   s      r"   remove_auxiliaryzProtoReader.remove_auxiliary  sA     !!'**		W%%%%%r$   c                 4    | j                                         S )z* Lists the names of added auxiliary data. )r   keysr(   s    r"   r   zProtoReader.aux_list  s     z   r$   c                 t    || j         v r| j        |         S t          d                    |                    )z Check for the existance of an auxiliary *auxname*. If present,
        return the AuxReader; if not, raise ValueError
        zNo auxiliary named {name}r   )r   r   r   rT   )r    r   s     r"   r(  zProtoReader._check_for_aux  s>     dm##:g&&8??W?MMNNNr$   c                    |                      |          }| j        }|                    |j        dz   |          -t	          |           |                    |j        dz   |          -|                    |          }|t          | j        |k    st          | dd          dk    r4|                                 }| j        |k    t          | dd          dk    4|S )a   Move to the next timestep for which there is at least one step from
        the auxiliary *auxname* within the cutoff specified in *auxname*.

        This allows progression through the trajectory without encountering
        ``NaN`` representative values (unless these are specifically part of the
        auxiliary data).

        If the auxiliary cutoff is not set, where auxiliary steps are less frequent
        (``auxiliary.dt > trajectory.dt``), this allows progression at the
        auxiliary pace (rounded to nearest timestep); while if the auxiliary
        steps are more frequent, this will work the same as calling
        :meth:`next()`.

        See the :ref:`Auxiliary API`.

        See Also
        --------
        :meth:`iter_as_aux`
        r   N_framer   r   )	r(  r   step_to_framerC   r   next_nonempty_framer   rY   getattr)r    r   r   r   
next_frames        r"   next_as_auxzProtoReader.next_as_aux  s    * !!'**W1b119III 1b119 ,,R00
 jJ&&'$!*D*D*J*JB jJ&&'$!*D*D*J*J 	r$   c              #      K   |                      |          }|                                  |                                 	 	 |                     |          V  n# t          $ r Y dS w xY w+)zIterate through timesteps for which there is at least one assigned
        step from the auxiliary *auxname* within the cutoff specified in *auxname*.

        See Also
        --------
        :meth:`next_as_aux`
        :meth:`iter_auxiliary`
        TN)r(  r   _restartr6  r   r*  s      r"   iter_as_auxzProtoReader.iter_as_aux  s       !!'**	&&w//////    	s   A 
A('A(c              #      K   |                      |          }||}nt          |||          }||         D ]}|V  |                    | j                   dS )az   Iterate through the auxiliary *auxname* independently of the trajectory.

        Will iterate over the specified steps of the auxiliary (defaults to all
        steps). Allows to access all values in an auxiliary, including those out
        of the time range of the trajectory, without having to also iterate
        through the trajectory.

        After interation, the auxiliary will be repositioned at the current step.

        Parameters
        ----------
        auxname : str
            Name of the auxiliary to iterate over.
        (start, stop, step) : optional
            Options for iterating over a slice of the auxiliary.
        selected : lst | ndarray, optional
            List of steps to iterate over.

        Yields
        ------
        :class:`~MDAnalysis.auxiliary.base.AuxStep` object

        See Also
        --------
        :meth:`iter_as_aux`
        N)r(  rV   read_tsr   )	r    r   rA   rB   rC   selectedr   	selectionrM   s	            r"   iter_auxiliaryzProtoReader.iter_auxiliary  sq      8 !!'** IIeT400IY 	 	AGGGGDGr$   c                 L    |                      |          }t          ||          S )aL  Get the value of *attrname* from the auxiliary *auxname*

        Parameters
        ----------
        auxname : str
            Name of the auxiliary to get value for
        attrname : str
            Name of gettable attribute in the auxiliary reader

        See Also
        --------
        :meth:`set_aux_attribute`
        )r(  r4  )r    r   attrnamer   s       r"   get_aux_attributezProtoReader.get_aux_attribute  s'     !!'**sH%%%r$   c                     |                      |          }|dk    r|                     ||           dS t          |||           dS )a   Set the value of *attrname* in the auxiliary *auxname*.

        Parameters
        ----------
        auxname : str
            Name of the auxiliary to alter
        attrname : str
            Name of settable attribute in the auxiliary reader
        new
            New value to try set *attrname* to

        See Also
        --------
        :meth:`get_aux_attribute`
        :meth:`rename_aux` - to change the *auxname* attribute
        r   N)r(  
rename_auxsetattr)r    r   r@  newr   s        r"   set_aux_attributezProtoReader.set_aux_attribute  sT    " !!'**y  OOGS)))))C3'''''r$   c                 d   |                      |          }|| j        v r#t          d                    |                    ||_        | j                            |          | j        |<   t          | j        j	        || j        j	        |                    t          | j        j	        |           dS )a1   Change the name of the auxiliary *auxname* to *new*.

        Provided there is not already an auxiliary named *new*, the auxiliary
        name will be changed in ts.aux namespace, the trajectory's
        list of added auxiliaries, and in the auxiliary reader itself.

        Parameters
        ----------
        auxname : str
             Name of the auxiliary to rename
        new : str
             New name to try set

        Raises
        ------
        ValueError
             If the name *new* is already in use by an existing auxiliary.
        z.Auxiliary data with name {name} already existsr/  N)r(  r   r   rT   r   r   poprD  r   r   r)  )r    r   rE  r   s       r"   rC  zProtoReader.rename_aux'  s    & !!'**$- &&,f#f&6&68 8 8*..11
3S$'+g"6777W%%%%%r$   c                 6     |s j         } fd|D             }|S )a  Get descriptions to allow reloading the specified auxiliaries.

        If no auxnames are provided, defaults to the full list of added
        auxiliaries.

        Passing the resultant description to ``add_auxiliary()`` will allow
        recreation of the auxiliary. e.g., to duplicate all auxiliaries into a
        second trajectory::

           descriptions = trajectory_1.get_aux_descriptions()
           for aux in descriptions:
               trajectory_2.add_auxiliary(**aux)


        Returns
        -------
        list
            List of dictionaries of the args/kwargs describing each auxiliary.

        See Also
        --------
        :meth:`MDAnalysis.auxiliary.base.AuxReader.get_description`
        c                 N    g | ]!}j         |                                         "S r;   )r   get_description)r  r   r    s     r"   r  z4ProtoReader.get_aux_descriptions.<locals>.<listcomp>]  s+    NNNc
37799NNNr$   )r   )r    auxnamesdescriptionss   `  r"   get_aux_descriptionsz ProtoReader.get_aux_descriptionsC  s3    0  	%}HNNNNXNNNr$   c                     | j         S )z$ Returns the list of transformations)r   r(   s    r"   transformationszProtoReader.transformations`  s     $$r$   c                 @    | j         s	|| _         d S t          d          )NzTransformations are already set)r   r   )r    rP  s     r"   rP  zProtoReader.transformationse  s+    $ 	@$3D!!!>???r$   c                     	 || _         |                     | j                  | _        dS # t          $ r d}t          |          dw xY w)a  Add all transformations to be applied to the trajectory.

        This function take as list of transformations as an argument. These
        transformations are functions that will be called by the Reader and given
        a :class:`Timestep` object as argument, which will be transformed and returned
        to the Reader.
        The transformations can be part of the :mod:`~MDAnalysis.transformations`
        module, or created by the user, and are stored as a list `transformations`.
        This list can only be modified once, and further calls of this function will
        raise an exception.

        .. code-block:: python

          u = MDAnalysis.Universe(topology, coordinates)
          workflow = [some_transform, another_transform, this_transform]
          u.trajectory.add_transformations(*workflow)

        The transformations are applied in the order given in the list
        `transformations`, i.e., the first transformation is the first
        or innermost one to be applied to the :class:`Timestep`. The
        example above would be equivalent to

        .. code-block:: python

          for ts in u.trajectory:
             ts = this_transform(another_transform(some_transform(ts)))


        Parameters
        ----------
        transform_list : list
            list of all the transformations that will be applied to the coordinates
            in the order given in the list

        See Also
        --------
        :mod:`MDAnalysis.transformations`

        zDCan't add transformations again. Please create a new Universe objectN)rP  r   r   r   )r    rP  r   s      r"   add_transformationszProtoReader.add_transformationsl  sa    R	;#2D  11$'::DGGG  	/ 	/ 	/(FV$$$.	/s	   * Ac                 0    | j         D ]} ||          }|S )z2Applies all the transformations given by the user )rP  )r    r   	transforms      r"   r   z"ProtoReader._apply_transformations  s*     - 	 	I2BB	r$   r   )NNNNNr  )NNN)NNNN)>r5   r6   r7   r8   r	   	_Timestepr.   __annotations__dictr   r   r#   r)   classmethodr   r   r   rL   r:   floatr   r   rY   r|   r!   r   r   abcabstractmethodr   rN   r   rs   r^   r   rU   r   r@   r  r   strr0   r   r  r   r   r   r&  r+  r   r(  r6  r9  r>  rA  rF  rC  rN  rP  setterrS  r   r;   r$   r"   r   r     s         8 IKKKNNNMMM! ! !     ; ; [; h    (        
 E    X 	-5 	- 	- 	- X	- s    X   X   X? ? ?/ / /( 	     
 	     9  9  9D< < <  . . .&V! V! V!p   6:48BF'+(-	U Ux4 U&{3U"3-U4<SMU "#U #3-	U 35*	U U U Ur >B7;$(KE KE %c4S>&9 :KE$S)^4KE "KE $(	KE KE KE KEZ& & & ! ! X!O O O$ $ $L  $ CG $# # # #J& & &"( ( (.& & &8   : % % X% @ @ @0; 0; 0;l    r$   r   )	metaclassc                   @     e Zd ZdZed fd	            Zd Zd Z xZS )
ReaderBaseaK  Base class for trajectory readers that extends :class:`ProtoReader` with a
    :meth:`__del__` method.

    New Readers should subclass :class:`ReaderBase` and properly implement a
    :meth:`close` method, to ensure proper release of resources (mainly file
    handles). Readers that are inherently safe in this regard should subclass
    :class:`ProtoReader` instead.

    See the :ref:`Trajectory API` definition in for the required attributes and
    methods.

    See Also
    --------
    :class:`ProtoReader`


    .. versionchanged:: 0.11.0
       Most of the base Reader class definitions were offloaded to
       :class:`ProtoReader` so as to allow the subclassing of ReaderBases without a
       :meth:`__del__` method.  Created init method to create common
       functionality, all ReaderBase subclasses must now :func:`super` through this
       class.  Added attribute :attr:`_ts_kwargs`, which is created in init.
       Provides kwargs to be passed to :class:`Timestep`
    .. versionchanged:: 1.0
       Removed deprecated flags functionality, use convert_units kwarg instead

    Tc                    t          t          |                                            t          |t                    r|| _        nt          |          | _        || _        i }dD ] }	 ||         }|||<   # t          $ r Y w xY w|| _	        d S )Nr   time_offset)
r?   ra  r#   r-   r   r   r]  convert_unitsr   
_ts_kwargs)r    r   re  r   	ts_kwargsattvalrG   s          r"   r#   zReaderBase.__init__  s    j$((***h,, 	*$DMMMMDM*	( 	% 	%C%Sk "%	#    
 $s   (A66
BBc                 D    | j         di | j        }| j        r |j        | j          || j        j                  | j                                        |_        | j                                        D ]-\  }}|	                    ||                                           .|S aQ  Return independent copy of this Reader.

        New Reader will have its own file handle and can seek/iterate
        independently of the original.

        Will also copy the current state of the Timestep held in the original
        Reader.


        .. versionchanged:: 2.2.0
           Arguments used to construct the reader are correctly captured and
           passed to the creation of the new class. Previously the only
           ``n_atoms`` was passed to class copies, leading to a class created
           with default parameters which may differ from the original class.
        r;   )
rG   _kwargsrP  rS  r   rY   copyr   r   r&  r    rE  r   auxreads       r"   rm  zReaderBase.copy  s    " dn,,t|,, 	;#C#T%9::DGM  $
 0 0 2 2 	7 	7GWgw||~~6666
r$   c                     | j         D ]!}| j        |                                          "|                                  d S r   )r   r   r   )r    r   s     r"   __del__zReaderBase.__del__  s?    = 	$ 	$CJsO!!####

r$   r   )	r5   r6   r7   r8   r   r#   rm  rq  rd   re   s   @r"   ra  ra    sr         6 $ $ $ $ $ $(  <      r$   ra  c                       e Zd Zd ZdS )_Writermetac                    t                               t           |||           	 t          |d                   }|                    dd          }|                    dd          }|r#|D ] }|                                }| t
          |<   !|r#|D ]"}|                                }| t          |<   !d S d S # t          $ r Y d S w xY w)NrT   singleframeT
multiframeF)r   r#   r   getr   r   r   r   )r   r   r   r   r   singlemultir   s           r"   r#   z_Writermeta.__init__  s    dD%333	1 Yx011C ]]=$77FMM,66E 2 2 2A		A.1(++ 1 1 1A		A-0'**1 11 1  	 	 	DD	s   B3 3
C CNr5   r6   r7   r#   r;   r$   r"   rs  rs     s#        1 1 1 1 1r$   rs  c                   2    e Zd ZdZd	dZd Zd Zd Zd ZdS )

WriterBasea  Base class for trajectory writers.

    See :ref:`Trajectory API` definition in for the required attributes and
    methods.


    .. versionchanged:: 2.0.0
       Deprecated :func:`write_next_timestep` has now been removed, please use
       :func:`write` instead.

    Tc                     |j         )t          j        d          t          j        d          }}n|j         dd         |j         dd         }}|s|                                }|                     |          }t          j        ||g          S )zRead dimensions from timestep *ts* and return appropriate unitcell.

        The default is to return ``[A,B,C,alpha,beta,gamma]``; if this
        is not appropriate then this method has to be overriden.
        Nr  )
dimensionsr0   zerosrm  r   concatenate)r    r   r   lengthsangless        r"   convert_dimensions_to_unitcellz)WriterBase.convert_dimensions_to_unitcell'  s     =  hqkk28A;;VGG mBQB/qrr1BVG 	%llnnG,,W55~w/000r$   c                 ,    |                      |          S )aJ  Write current timestep, using the supplied `obj`.

        Parameters
        ----------
        obj : :class:`~MDAnalysis.core.groups.AtomGroup` or :class:`~MDAnalysis.core.universe.Universe`
            write coordinate information associate with `obj`

        Note
        ----
        The size of the `obj` must be the same as the number of atoms provided
        when setting up the trajectory.


        .. versionchanged:: 2.0.0
           Deprecated support for Timestep argument to write has now been
           removed. Use AtomGroup or Universe as an input instead.
        )_write_next_framer    objs     r"   writezWriterBase.write8  s    $ %%c***r$   c                 .    |                                   d S r   r   r(   s    r"   rq  zWriterBase.__del__L  s    

r$   c                     	 d                     | j        j        | j        | j                  S # t
          t          f$ r( d                     | j        j        | j                  cY S w xY w)Nz< {0!s} {1!r} for {2:d} atoms >z< {0!s} {1!r} >)rT   rG   r5   r   r   rr   AttributeErrorr(   s    r"   r  zWriterBase.__repr__O  sv    	T4;;DN<SUYUbdhdpqqq>* 	T 	T 	T %++DN,CT]SSSSS	Ts   *- 6A&%A&c                     t          j        |          }t          j        |d         |k               ot          j        ||d         k              S )a  Returns ``True`` if all values are within limit values of their formats.

        Due to rounding, the test is asymmetric (and *min* is supposed to be negative)::

            min < x <= max

        Parameters
        ----------
        criteria : dict
            dictionary containing the *max* and *min* values in native units
        x : numpy.ndarray
            ``(x, y, z)`` coordinates of atoms selected to be written out

        Returns
        -------
        bool
        minmax)r0   ravelall)r    criteriar   s      r"   has_valid_coordinatesz WriterBase.has_valid_coordinatesW  sB    $ HQKKvhuo)**Krva8E?6J/K/KKr$   Nr   )	r5   r6   r7   r8   r  r  rq  r  r  r;   r$   r"   r|  r|    sv        
 
1 1 1 1"+ + +(  T T TL L L L Lr$   r|  c                        e Zd ZdZdZed fd	            Zd Zd Z fdZ	d	 Z
d
 ZddZd Zd Zd Z fdZd Z xZS )SingleFrameReaderBaseu  Base class for Readers that only have one frame.

    To use this base class, define the method :meth:`_read_first_frame` to
    read from file `self.filename`.  This should populate the attribute
    `self.ts` with a :class:`Timestep` object.

    .. versionadded:: 0.10.0
    .. versionchanged:: 0.11.0
       Added attribute "_ts_kwargs" for subclasses
       Keywords "dt" and "time_offset" read into _ts_kwargs
    .. versionchanged:: 2.2.0
       Calling `__iter__` now rewinds the reader before yielding a
       :class:`Timestep` object (fixing behavior that was not
       well defined previously).
    .. versionchanged:: 2.10.0
       Fixed a typo in the attribute assignment (`self.atom` → `self.atoms`),
       which may affect subclasses relying on this value.
    z {0} only contains a single frameTNc                    t          t          |                                            || _        || _        d| _        || _        i }dD ] }	 ||         }|||<   # t          $ r Y w xY w|| _        | 	                                 d S )Nr   rc  )
r?   r  r#   r   re  rj   r   r   rf  _read_first_frame)	r    r   re  r   r   rg  rh  ri  rG   s	           r"   r#   zSingleFrameReaderBase.__init__  s    #T**33555 *	( 	% 	%C%Sk "%	#    
 $     s   A
A'&A'c                     | j         di | j        }| j                                        |_        | j                                        D ]-\  }}|                    ||                                           .| j        |_        |S rk  )rG   rl  r   rm  r   r   r&  rP  rn  s       r"   rm  zSingleFrameReaderBase.copy  s      dn,,t|,, $
 0 0 2 2 	7 	7GWgw||~~6666 #2
r$   c                     d S r   r;   r(   s    r"   r  z'SingleFrameReaderBase._read_first_frame  r   r$   c                    |                                   | j                                        D ]$\  }}|                    | j                  | _        %t          t          |                               | j                   d S r   )r  r   r   r   r   r?   r  r   )r    r   ro  rG   s      r"   rL   zSingleFrameReaderBase.rewind  sw        $
 0 0 2 2 	1 	1GW''00DGG#T**AA$'JJJJJr$   c                     d S r   r;   r(   s    r"   r   zSingleFrameReaderBase._reopen  s    r$   c                 d    t          | j                            | j        j                            r   )r   _errrT   rG   r5   r(   s    r"   r   zSingleFrameReaderBase.next  s%    DI,,T^-DEEFFFr$   c                 d    t          | j                            | j        j                            r   )r'   r  rT   rG   r5   r   s     r"   r   z)SingleFrameReaderBase._read_next_timestep  s%    !$)"2"24>3J"K"KLLLr$   c              #   D   K   |                                   | j        V  d S r   )rL   r   r(   s    r"   rN   zSingleFrameReaderBase.__iter__  s#      gr$   c                 ~    |dk    r1t          | j                            | j        j                            | j        S )Nr   )rS   r  rT   rG   r5   r   rn   s     r"   r   z!SingleFrameReaderBase._read_frame  s5    A::TY--dn.EFFGGGwr$   c                     d S r   r;   r(   s    r"   r   zSingleFrameReaderBase.close  s	     	r$   c                      t          t          |           j        |  | j        D ]} || j                  | _        dS )a%   Add all transformations to be applied to the trajectory.

        This function take as list of transformations as an argument. These
        transformations are functions that will be called by the Reader and given
        a :class:`Timestep` object as argument, which will be transformed and returned
        to the Reader.
        The transformations can be part of the :mod:`~MDAnalysis.transformations`
        module, or created by the user, and are stored as a list `transformations`.
        This list can only be modified once, and further calls of this function will
        raise an exception.

        .. code-block:: python

          u = MDAnalysis.Universe(topology, coordinates)
          workflow = [some_transform, another_transform, this_transform]
          u.trajectory.add_transformations(*workflow)

        Parameters
        ----------
        transform_list : list
            list of all the transformations that will be applied to the coordinates

        See Also
        --------
        :mod:`MDAnalysis.transformations`
        N)r?   r  rS  rP  r   )r    rP  rU  rG   s      r"   rS  z)SingleFrameReaderBase.add_transformations  sR    @ 	?#T**>PP- 	) 	)Ii((DGG	) 	)r$   c                     |S )z- Applies the transformations to the timestep.r;   r   s     r"   r   z,SingleFrameReaderBase._apply_transformations  s	    
 	r$   )TNr   )r5   r6   r7   r8   r  r   r#   rm  r  rL   r   r   r   rN   r   r   rS  r   rd   re   s   @r"   r  r  m  s$        $ .D! ! ! ! ! !*  6  K K K K K  G G GM M M M  
    ") ") ") ") ")H      r$   r  c                     |dk    r!| |k     rt          d|dz
  | z
  |z  z             S |dk     r"| |k    rt          d| dz
  |z
  | z  z             S dS )Nr   r   )r   r   s      r"   rI   rI     so    qUT\\1q5(T11222
((ut||1	D(te44555 qr$   c                       e Zd Zd ZdS )_Convertermetac                     t                               t           |||           	 t          |d                   }|D ] }|                                }| t          |<   !d S # t
          $ r Y d S w xY w)Nlib)r   r#   r   r   r   r   )r   r   r   r   r   r   s         r"   r#   z_Convertermeta.__init__  s    dD%333	%Yu-..C  % %GGII!$A% %  	 	 	DD	s   A 
A,+A,Nrz  r;   r$   r"   r  r    s#        	% 	% 	% 	% 	%r$   r  c                   $    e Zd ZdZd Zd Zd ZdS )ConverterBasezBase class for converting to other libraries.

    .. deprecated:: 2.7.0
        This class has been moved to
        :class:`MDAnalysis.converters.base.ConverterBase` and will be removed
        from :mod:`MDAnalysis.coordinates.base` in 3.0.0.
    c                 B    d}t          j        |t          d           d S )NzConverterBase moved from coordinates.base.ConverterBase to converters.base.ConverterBase and will be removed from coordinates.base in MDAnalysis release 3.0.0r   )
stacklevel)r  r  r  )r   wmsgs     r"   __init_subclass__zConverterBase.__init_subclass__-  s)    . 	d.1======r$   c                 B    d                     | j        j                  S )Nz<{cls}>)r   )rT   rG   r5   r(   s    r"   r  zConverterBase.__repr__4  s    DN$;<<<r$   c                     t           r   r&   r  s     r"   convertzConverterBase.convert7  s    !!r$   N)r5   r6   r7   r8   r  r  r  r;   r$   r"   r  r  $  sK         > > >= = =" " " " "r$   r  c                        e Zd ZdZd fd	Zd Zed             Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zd ZdefdZd Z xZS )StreamReaderBasea  Base class for readers that read a continuous stream of data.

    This class is designed for readers that process continuous data streams,
    such as live feeds from simulations. Unlike traditional trajectory readers
    that can randomly access frames, streaming readers have fundamental constraints:

    - **No random access**: Cannot seek to arbitrary frames (no ``traj[5]``)
    - **Forward-only**: Can only iterate sequentially through frames
    - **No length**: Total number of frames is unknown until stream ends
    - **No rewinding**: Cannot restart or rewind the stream
    - **No copying**: Cannot create independent copies of the reader
    - **No reopening**: Cannot restart iteration once stream is consumed
    - **No timeseries**: Cannot use ``timeseries()`` or bulk data extraction
    - **No writers**: Cannot create ``Writer()`` or ``OtherWriter()`` instances
    - **No pickling**: Cannot serialize reader instances (limits multiprocessing)
    - **No StreamWriterBase**: No complementary Writer class available for streaming data


    The reader raises :exc:`RuntimeError` for operations that require random
    access or rewinding, including ``rewind()``, ``copy()``, ``timeseries()``,
    ``Writer()``, ``OtherWriter()``, and ``len()``. Only slice notation is supported for iteration.

    Parameters
    ----------
    filename : str or file-like
        Source of the streaming data
    convert_units : bool, optional
        Whether to convert units from native to MDAnalysis units (default: True)
    **kwargs
        Additional keyword arguments passed to the parent ReaderBase

    See Also
    --------
    StreamFrameIteratorSliced : Iterator for stepped streaming access
    ReaderBase : Base class for standard trajectory readers


    .. versionadded:: 2.10.0 
    Tc                      t          t          |           j        |fd|i| d| _        d| _        d | _        d| _        d S )Nre  TFr   )r?   r  r#   _init_scope_reopen_called	_first_tsr1  )r    r   re  r   rG   s       r"   r#   zStreamReaderBase.__init__c  sa    .%%.	
 	
$1	
5;	
 	
 	
  #r$   c                     | j         s"| j        dk    r| xj        dz  c_        | j        S |                     | j        dz             }| j         r%| j                                        | _        d| _         |S )Nr   r   F)r  r1  r  r   r   rm  r   s     r"   r   z$StreamReaderBase._read_next_timestepl  sw      	"DK2$5$5KK1KK >!dkAo.. 	%!W\\^^DN$D	r$   c                 Z    t          d                    | j        j                            )z3Changes as stream is processed unlike other readersz{}: n_frames is unknownRuntimeErrorrT   rG   r5   r(   s    r"   rj   zStreamReaderBase.n_frames}  s,     %,,T^-DEE
 
 	
r$   c                 Z    t          d                    | j        j                            Nz{} has unknown lengthr  r(   s    r"   r)   zStreamReaderBase.__len__  *    #**4>+BCC
 
 	
r$   c                    	 |                                  }| j                                        D ]%\  }}| j        |                             |          }&|                     |          }n# t
          t          f$ r	 t          dw xY w|S )a  Advance to the next timestep in the streaming trajectory.
        
        Streaming readers process frames sequentially and cannot rewind
        once iteration completes. Use ``for ts in trajectory`` for iteration.
        
        Returns
        -------
        Timestep
            The next timestep in the stream
            
        Raises
        ------
        StopIteration
            When the stream ends or no more frames are available
        N)r   r   r   r   r   r   r   r   r   s       r"   r   zStreamReaderBase.next  s     		1))++B
 $(:#3#3#5#5 7 7Z(22266,,R00BB '" 	* 	* 	*T)	* 	s   A+ +Bc                 Z    t          d                    | j        j                            )aX  Rewinding is not supported for streaming trajectories.
        
        Streaming readers process data continuously from streams
        and cannot restart or go backward in the stream once consumed.

        Raises
        ------
        RuntimeError
            Always raised, as rewinding is not supported for streaming trajectories
        z){}: Stream-based readers can't be rewoundr  r(   s    r"   rL   zStreamReaderBase.rewind  s1     7>>' 
 
 	
r$   c                 Z    t          d                    | j        j                            )a  Reader copying is not supported for streaming trajectories.
        
        Streaming readers maintain internal state and connection resources
        that cannot be duplicated. Each stream connection is unique and
        cannot be copied.
        
        Raises
        ------
        RuntimeError
            Always raised, as copying is not supported for streaming trajectories
        z{} does not support copyingr  r(   s    r"   rm  zStreamReaderBase.copy  s,     )001HII
 
 	
r$   c                     | j         r,t          d                    | j        j                            d| _        d| _         dS )a  Prepare stream for iteration - can only be called once.
        
        Streaming readers cannot be reopened once iteration begins.
        This method is called internally during iteration setup and
        will raise an error if called multiple times.
        
        Raises
        ------
        RuntimeError
            If the stream has already been opened for iteration
        z{}: Cannot reopen streamr   TN)r  r  rT   rG   r5   r1  r(   s    r"   r   zStreamReaderBase._reopen  sN      	*11$.2IJJ   "r$   c                 Z    t          d                    | j        j                            )aO  Timeseries extraction is not supported for streaming trajectories.
        
        Streaming readers cannot randomly access frames or store bulk coordinate
        data in memory, which ``timeseries()`` requires. Use sequential frame
        iteration instead.
                    
        Parameters
        ----------
        **kwargs
            Any keyword arguments (ignored, as method is not supported)
            
        Raises
        ------
        RuntimeError
            Always raised, as timeseries extraction is not supported for 
            streaming trajectories
        z6{}: cannot access timeseries for streamed trajectoriesr  )r    r   s     r"   r  zStreamReaderBase.timeseries  s,    $ DKKDNLcdd
 
 	
r$   c                     t          |t                    rK|                     |j        |j        |j                  \  }}}|t          |           S t          | |          S t          d          )a  Return an iterator for slicing a streaming trajectory.

        Parameters
        ----------
        frame : slice
            Slice object. Only the step parameter is meaningful for streams.

        Returns
        -------
        FrameIteratorAll or StreamFrameIteratorSliced
            Iterator for the requested slice.

        Raises
        ------
        TypeError
            If frame is not a slice object.
        ValueError
            If slice contains start or stop values.

        Examples
        --------
        >>> for ts in traj[:]:          # All frames sequentially
        ...     process(ts)
        >>> for ts in traj[::5]:        # Every 5th frame
        ...     process(ts)

        See Also
        --------
        StreamFrameIteratorSliced
        Nz6Streamed trajectories must be an indexed using a slice)	r-   rV   r@   rA   rB   rC   rg   StreamFrameIteratorSlicedrr   )r    rY   _rC   s       r"   r^   zStreamReaderBase.__getitem__  sx    > eU## 	11UZ JAq$ |'---0t<<<H  r$   c                    |,t          d                    | j        j                            |,t          d                    | j        j                            |yt	          |t
          j                  r3|dk     r,t          d                    | j        j                            n,t          d                    | j        j                            |||fS )a  Check and validate slice indices for streaming trajectories.
        
        Streaming trajectories have fundamental constraints that differ from 
        traditional trajectory files:
        
        * **No start/stop indices**: Since streams process data continuously
          without knowing the total length, ``start`` and ``stop`` must be ``None``
        * **Step-only slicing**: Only the ``step`` parameter is meaningful,
          controlling how many frames to skip during iteration
        * **Forward-only**: ``step`` must be positive (> 0) as streams cannot
          be processed backward in time
          
        Parameters
        ----------
        start : int or None
            Starting frame index. Must be ``None`` for streaming readers.
        stop : int or None
            Ending frame index. Must be ``None`` for streaming readers.
        step : int or None
            Step size for iteration. Must be positive integer or ``None`` 
            (equivalent to 1).
            
        Returns
        -------
        tuple
            (start, stop, step) with validated values
            
        Raises
        ------
        ValueError
            If ``start`` or ``stop`` are not ``None``, or if ``step`` is 
            not a positive integer.
            
        Examples
        --------
        Valid streaming slices::
        
            traj[:]        # All frames (step=None, equivalent to step=1)
            traj[::2]      # Every 2nd frame 
            traj[::10]     # Every 10th frame
            
        Invalid streaming slices::
        
            traj[5:]       # Cannot specify start index
            traj[:100]     # Cannot specify stop index  
            traj[5:100:2]  # Cannot specify start or stop indices
            traj[::-1]     # Cannot go backwards (negative step)
            
        See Also
        --------
        __getitem__
        StreamFrameIteratorSliced


        .. versionadded:: 2.10.0
        NzC{}: Cannot expect a start index from a stream, 'start' must be NonezA{}: Cannot expect a stop index from a stream, 'stop' must be Noner   z7{}: Cannot go backwards in a stream, 'step' must be > 0z{}: 'step' must be an integer)r   rT   rG   r5   r-   rP   rQ   )r    rA   rB   rC   s       r"   r@   z$StreamReaderBase.check_slice_indices  s   r U\\N+   
 SZZN+   
 $ 011 !88$QXX N3     !3::/    dD  r$   c                 Z    t          d                    | j        j                            )aV  Writer creation is not supported for streaming trajectories.
        
        Writer creation requires trajectory metadata that streaming readers
        cannot provide due to their sequential processing nature.

        Parameters
        ----------
        filename : str
            Output filename (ignored, as method is not supported)
        **kwargs
            Additional keyword arguments (ignored, as method is not supported)
            
        Raises
        ------
        RuntimeError
            Always raised, as writer creation is not supported for streaming trajectories
        z2{}: cannot create Writer for streamed trajectoriesr  r   s      r"   r   zStreamReaderBase.Writers  s1    $ @GG' 
 
 	
r$   c                 Z    t          d                    | j        j                            )a  Writer creation is not supported for streaming trajectories.
        
        OtherWriter initialization requires frame-based parameters and trajectory
        indexing information. Streaming readers process data sequentially
        without meaningful frame indexing, making writer setup impossible.
        
        Parameters
        ----------
        filename : str
            Output filename (ignored, as method is not supported)
        **kwargs
            Additional keyword arguments (ignored, as method is not supported)
            
        Raises
        ------
        RuntimeError
            Always raised, as writer creation is not supported for streaming trajectories
        z7{}: cannot create OtherWriter for streamed trajectoriesr  r   s      r"   r   zStreamReaderBase.OtherWriter  s1    & ELL' 
 
 	
r$   c                 Z    t          d                    | j        j                            Nz{} does not support picklingr'   rT   rG   r5   r(   s    r"   __getstate__zStreamReaderBase.__getstate__  *    !*11$.2IJJ
 
 	
r$   statec                 Z    t          d                    | j        j                            r  r  )r    r  s     r"   __setstate__zStreamReaderBase.__setstate__  r  r$   c                 Z    d                     | j        j        | j        | j                  S )Nz8<{cls} {fname} with continuous stream of {natoms} atoms>)r   r  r  )rT   rG   r5   r   r   r(   s    r"   r  zStreamReaderBase.__repr__  s2    vN+m|   	
r$   r   )r5   r6   r7   r8   r#   r   r:   rj   r)   r   rL   rm  r   r  r^   r@   r   r   r  objectr  r  rd   re   s   @r"   r  r  :  sF       & &P       " 
 
 X

 
 

  :
 
 
$
 
 
 # # #&
 
 
,* * *XT! T! T!l
 
 
0
 
 
2
 
 


& 
 
 
 


 
 
 
 
 
 
r$   r  c                   P     e Zd ZdZ fdZd Zd Zd Zd Ze	d             Z
 xZS )r  a  Iterator for sliced frames in a streamed trajectory.
    
    Created when slicing a streaming trajectory with a step parameter 
    (e.g., ``trajectory[::n]``). Reads every nth frame from the continuous 
    stream, discarding intermediate frames for performance.
    
    This differs from iterating over all frames (``trajectory[:]``) which uses
    :class:`FrameIteratorAll` and processes every frame sequentially without 
    skipping.
    
    Streaming constraints apply to the sliced iterator:
    
    - Frames cannot be accessed randomly (no indexing support)
    - The total number of frames is unknown until streaming ends  
    - Rewinding or restarting iteration is not possible
    - Only forward iteration with a fixed step size is supported
    
    Parameters
    ----------
    trajectory : StreamReaderBase
        The streaming trajectory reader to iterate over. Must be a 
        stream-based reader that supports continuous data reading.
    step : int
        Step size for iteration. Must be a positive integer. A step 
        of 1 reads every frame, step of 2 reads every other frame, etc.
        
    See Also
    --------
    StreamReaderBase
    FrameIteratorBase


    .. versionadded:: 2.10.0
    c                 X    t                                          |           || _        d S r   )r?   r#   rF   )r    r!   rC   rG   s      r"   r#   z"StreamFrameIteratorSliced.__init__  s&    $$$


r$   c                 8    | j                                          | S r   )r!   r   r(   s    r"   rN   z"StreamFrameIteratorSliced.__iter__  s     	!!!r$   c                    	 | j         j        dz   | j        z  dk    r4| j                                          | j         j        dz   | j        z  dk    4n# t          t
          f$ r	 t          d w xY w| j                                         S )Nr   r   )r!   r1  rF   r   r   r   r   r   r(   s    r"   r   z"StreamFrameIteratorSliced.__next__  s    	* ?)A-;q@@33555 ?)A-;q@@'" 	* 	* 	*T)	* ##%%%s   AA A,c                 Z    t          d                    | j        j                            r  r  r(   s    r"   r)   z!StreamFrameIteratorSliced.__len__  r  r$   c                      t          d          )Nz)Sliced iterator does not support indexing)r  rn   s     r"   r^   z%StreamFrameIteratorSliced.__getitem__  s    FGGGr$   c                     | j         S )a  The step size for sliced frame iteration.
        
        Returns the step interval used when iterating through frames in a 
        streaming trajectory. For example, a step of 2 means every second 
        frame is processed, while a step of 1 processes every frame.
        
        Returns
        -------
        int
            Step size for iteration. Always a positive integer greater than 0.
            
        rc   r(   s    r"   rC   zStreamFrameIteratorSliced.step  s     zr$   )r5   r6   r7   r8   r#   rN   r   r)   r^   r:   rC   rd   re   s   @r"   r  r    s        ! !F      
& 
& 
&
 
 

H H H   X    r$   r  )5r8   r[  numpyr0   rP   r  typingr   r   r   r   r   timestepr	    r
   r   r   r   r   r   r   auxiliary.baser   auxiliary.corer   r   	auxiliaryr   lib.utilr   r   r   r   r  r   r=   rg   rX   r{   ABCMetar   r   ra  r   rs  r|  r  rI   r  r  r  r  r;   r$   r"   <module>r     sb  2f fN 


       3 3 3 3 3 3 3 3 3 3 3 3 3 3                                & & & & & & & & & & & & . . . . . . # # # # # # B B B B B B B B B B " " " " " "               :[ [ [ [ [+ [ [ [|& & & & &( & & &:, , , , ,, , , ,^J J J J JV J J JZQ Q Q Q Q#+ Q Q Q.f f f f f&K f f f fRR R R R R R R Rj1 1 1 1 1$ 1 1 14PL PL PL PL PL; PL PL PL PLfS S S S SK S S Sl	 	 	% % % % %T % % %$" " " " "Fn " " " ",|
 |
 |
 |
 |
z |
 |
 |
~P P P P P 1 P P P P Pr$   