
     ie                         d Z ddlZddlZddlZddlZddlZddlmZ ddl	m
Z
 d Zd Zd Zd	 Z G d
 dej                  ZdS )aK  =========================================================================
Reading trajectories from memory --- :mod:`MDAnalysis.coordinates.memory`
=========================================================================

:Author: Wouter Boomsma
:Year: 2016
:Copyright: Lesser GNU Public License v2.1+
:Maintainer: Wouter Boomsma <wb@di.ku.dk>, wouterboomsma on github


.. versionadded:: 0.16.0

The module contains a trajectory reader that operates on an array in
memory, rather than reading from file. This makes it possible to
operate on raw coordinates using existing MDAnalysis tools. In
addition, it allows the user to make changes to the coordinates in a
trajectory (e.g. through
:attr:`MDAnalysis.core.groups.AtomGroup.positions`) without having
to write the entire state to file.


How to use the :class:`MemoryReader`
====================================

The :class:`MemoryReader` can be used to either directly generate a
trajectory as a numpy array or by transferring an existing trajectory
to memory.

In-memory representation of arbitrary trajectories
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If sufficient memory is available to hold a whole trajectory in memory
then analysis can be sped up substantially by transferring the
trajectory to memory.

The most straightforward use of the :class:`MemoryReader` is to simply
use the ``in_memory=True`` flag for the
:class:`~MDAnalysis.core.universe.Universe` class, which
automatically transfers a trajectory to memory::

 import MDAnalysis as mda
 from MDAnalysisTests.datafiles import TPR, XTC

 universe = mda.Universe(TPR, XTC, in_memory=True)

Of course, sufficient memory has to be available to hold the whole
trajectory.


Switching a trajectory to an in-memory representation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The decision to transfer the trajectory to memory can be made at any
time with the
:meth:`~MDAnalysis.core.universe.Universe.transfer_to_memory` method
of a :class:`~MDAnalysis.core.universe.Universe`::

    universe = mda.Universe(TPR, XTC)
    universe.transfer_to_memory()

This operation may take a while (with `verbose=True` a progress bar is
displayed) but then subsequent operations on the trajectory directly
operate on the in-memory array and will be very fast.


Constructing a Reader from a numpy array
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The :class:`MemoryReader` provides great flexibility because it
becomes possible to create a :class:`~MDAnalysis.core.universe.Universe` directly
from a numpy array.

A simple example consists of a new universe created from the array
extracted from a DCD
:meth:`~MDAnalysis.coordinates.DCD.DCDReader.timeseries`::

    import MDAnalysis as mda
    from MDAnalysisTests.datafiles import DCD, PSF
    from MDAnalysis.coordinates.memory import MemoryReader

    universe = mda.Universe(PSF, DCD)

    coordinates = universe.trajectory.timeseries(universe.atoms)
    universe2 = mda.Universe(PSF, coordinates, format=MemoryReader, order='afc')


.. _create-in-memory-trajectory-with-AnalysisFromFunction:

.. rubric:: Creating an in-memory trajectory with
            :func:`~MDAnalysis.analysis.base.AnalysisFromFunction`

The :meth:`~MDAnalysis.coordinates.DCD.DCDReader.timeseries` is
currently only implemented for the
:class:`~MDAnalysis.coordinates.DCD.DCDReader`. However, the
:func:`MDAnalysis.analysis.base.AnalysisFromFunction` can provide the
same functionality for any supported trajectory format::

  import MDAnalysis as mda
  from MDAnalysis.tests.datafiles import PDB, XTC

  from MDAnalysis.coordinates.memory import MemoryReader
  from MDAnalysis.analysis.base import AnalysisFromFunction

  u = mda.Universe(PDB, XTC)

  coordinates = AnalysisFromFunction(lambda ag: ag.positions.copy(),
                                     u.atoms).run().results['timeseries']
  u2 = mda.Universe(PDB, coordinates, format=MemoryReader)

.. _creating-in-memory-trajectory-label:

Creating an in-memory trajectory of a sub-system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Creating a trajectory for just a selection of an existing trajectory
requires the transfer of the appropriate coordinates as well as
creation of a topology of the sub-system. For the latter one can use
the :func:`~MDAnalysis.core.universe.Merge` function, for the former
the :meth:`~MDAnalysis.core.universe.Universe.load_new` method of a
:class:`~MDAnalysis.core.universe.Universe` together with the
:class:`MemoryReader`. In the following, an in-memory trajectory of
only the protein is created::

  import MDAnalysis as mda
  from MDAnalysis.tests.datafiles import PDB, XTC

  from MDAnalysis.coordinates.memory import MemoryReader
  from MDAnalysis.analysis.base import AnalysisFromFunction

  u = mda.Universe(PDB, XTC)
  protein = u.select_atoms("protein")

  coordinates = AnalysisFromFunction(lambda ag: ag.positions.copy(),
                                     protein).run().results['timeseries']
  u2 = mda.Merge(protein)            # create the protein-only Universe
  u2.load_new(coordinates, format=MemoryReader)

The protein coordinates are extracted into ``coordinates`` and then
the in-memory trajectory is loaded from these coordinates. In
principle, this could have all be done in one line::

  u2 = mda.Merge(protein).load_new(
           AnalysisFromFunction(lambda ag: ag.positions.copy(),
                                protein).run().results['timeseries'],
           format=MemoryReader)

The new :class:`~MDAnalysis.core.universe.Universe` ``u2`` can be used
to, for instance, write out a new trajectory or perform fast analysis
on the sub-system.


Classes
=======


.. autoclass:: MemoryReader
   :members:
   :inherited-members:

    N   )base)Timestepc                 "    d| _         || _        dS )a  Replace the array of positions

    Replaces the array of positions by another array.


    Note
    ----
    The behavior of :meth:`_replace_positions_array` is different from the
    behavior of the :attr:`position` property that replaces the **content**
    of the array. The :meth:`_replace_positions_array` method should only be
    used to set the positions to a different frame in
    :meth:`MemoryReader._read_next_timestep`; there, the memory reader sets
    the positions to a view of the correct frame.  Modifying the positions
    for a given frame should be done with the :attr:`positions` attribute
    that does not break the link between the array of positions in the time
    step and the :attr:`MemoryReader.coordinate_array`.


    .. versionadded:: 0.19.0
    .. versionchanged:: 2.0.0
       This function, and the _repalace helper functions for velocities,
       forces, and dimensions, have been moved out of the now removed
       custom timestep object for :class:`MemoryReader`.
    TN)has_positions_postsnews     g/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/memory.py_replace_positions_arrayr      s    2 BBGGG    c                 "    d| _         || _        d S NT)has_velocities_velocitiesr	   s     r   _replace_velocities_arrayr      s    BBNNNr   c                 "    d| _         || _        d S r   )
has_forces_forcesr	   s     r   _replace_forces_arrayr      s    BMBJJJr   c                     || _         d S N)	_unitcellr	   s     r   _replace_dimensionsr      s    BLLLr   c                        e Zd ZdZdZ	 	 	 	 	 	 d fd	Zed             Zedd            Zd	 Z	dd
Z
d Zd Z	 ddZddZd Zd Z fdZd Z xZS )MemoryReadera  
    MemoryReader works with trajectories represented as numpy arrays.

    A trajectory reader interface to a numpy array of the coordinates.
    For compatibility with the timeseries interface, support is provided for
    specifying the order of columns through the `order` keyword.

    .. versionadded:: 0.16.0
    .. versionchanged:: 1.0.0
       Support for the deprecated `format` keyword for
       :meth:`MemoryReader.timeseries` has now been removed.
    MEMORYfacNr   c                    t          t          |                                            || _        || _        || _        	 |j        dk    r*|j        d         dk    r|t          j	        ddddf         }n # t          $ r d}	t          |	          dw xY w|                     ||           | j        j        | j                            d                   | _        | j        j        | j                            d                   | _        |	 t          j        |t          j                  }n0# t&          $ r# d	t)          |           }	t          |	          dw xY w|j        dk    r|t          j	        ddddf         }|j        | j        j        k    s2t'          d
                    |j        | j        j                            |                    t          j        d          | _        nd| _        |	 t          j        |t          j                  }n0# t&          $ r# dt)          |           }	t          |	          dw xY w|j        dk    r|t          j	        ddddf         }|j        | j        j        k    s2t'          d                    |j        | j        j                            |                    t          j        d          | _        nd| _        |                    dd          }
|
3|
| j        k    r(t'          d                    |
| j                             | j        | j        fi || _        || j        _        |-t          j        | j        dft          j                  | _        n	 t          j        |t          j                  }n0# t&          $ r# dt)          |           }	t          |	          dw xY w|j        dk    rt          j        || j        df          }n9|j        | j        dfk    r't'          d                    |j                            || _        d| j        _         d| j        _!        | "                                 dS )u  
        Parameters
        ----------
        coordinate_array : numpy.ndarray
            The underlying array of coordinates. The MemoryReader now
            necessarily requires a np.ndarray
        order : {"afc", "acf", "caf", "fac", "fca", "cfa"} (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).
        dimensions: [A, B, C, alpha, beta, gamma] (optional)
            unitcell dimensions (*A*, *B*, *C*, *alpha*, *beta*, *gamma*)
            lengths *A*, *B*, *C* are in the MDAnalysis length unit (Å), and
            angles are in degrees. An array of dimensions can be given,
            which must then be shape (nframes, 6)
        dt: float (optional)
            The time difference between frames (ps).  If :attr:`time`
            is set, then `dt` will be ignored.
        filename: string (optional)
            The name of the file from which this instance is created. Set to ``None``
            when created from an array
        velocities : numpy.ndarray (optional)
            Atom velocities.  Must match shape of coordinate_array.  Will share order
            with coordinates.
        forces : numpy.ndarray (optional)
            Atom forces.  Must match shape of coordinate_array  Will share order
            with coordinates

        Raises
        ------
        TypeError if the coordinate array passed is not a np.ndarray

        Note
        ----
        At the moment, only a fixed `dimension` is supported, i.e., the same
        unit cell for all frames in `coordinate_array`. See issue `#1041`_.


        .. _`#1041`: https://github.com/MDAnalysis/mdanalysis/issues/1041

        .. versionchanged:: 0.19.0
            The input to the MemoryReader now must be a np.ndarray
            Added optional velocities and forces
        .. versionchanged:: 2.2.0
            Input kwargs are now stored under the :attr:`_kwargs` attribute,
            and are passed on class creation in :meth:`copy`.
           r      NzdThe input has to be a numpy.ndarray that corresponds to the layout specified by the 'order' keyword.fa)dtypez$'velocities' must be array-like got z5Velocities has wrong shape {} to match coordinates {}Fcopyz 'forces' must be array like got z1Forces has wrong shape {} to match coordinates {}n_atomszYThe provided value for n_atoms ({}) does not match the shape of the coordinate array ({})   z$'dimensions' must be array-like got )r)   z[Provided dimensions array has shape {}. This must be a array of shape (6,) or (n_frames, 6))#superr   __init__filenamestored_order_kwargsndimshapenpnewaxisAttributeError	TypeError	set_arraycoordinate_arrayfindn_framesr(   asarrayfloat32
ValueErrortypeformatastypevelocity_arrayforce_arraypop	_Timestepr
   dtzerosdimensions_arraytileframetime_read_next_timestep)selfr7   order
dimensionsrD   r-   
velocitiesforceskwargserrmsgprovided_n_atoms	__class__s              r   r,   zMemoryReader.__init__   s   z 	lD!!**,,, !
	.$)).>.DQ.G1.L.L#3BJ1114D#E  	. 	. 	.B  F##-	. 	'///-3""3''
 ,243D3I3I#3N3NO!2Z
"*EEE

 2 2 2*J''* *   ''T12 !##'
AAAqqq(89
#t'<'BBB vj.0E0KLL  
 #-"3"3BJU"3"K"KD"&D2F"*=== 2 2 2JDLLJJ''T12 {a
AAAqqq 01<4#8#>>> vflD,A,GHH  
  &}}RZe}DDD#D!::i66',<,L,L#V$4dlCC   !$.8888
$&H""*% % %D!!2Z
"*EEE

 2 2 2*J''* *   ''T12 4''  WZ$-1CDD

!dmQ%777 $$*F:+;$<$<  
 %/D!  """""s/   5A5 5B D- --E9 H -I N# #-Oc                 6    t          | t          j                  S )zhFor internal use: Check if MemoryReader can operate on *thing*

        .. versionadded:: 1.0.0
        )
isinstancer2   ndarray)things    r   _format_hintzMemoryReader._format_hint  s     %,,,r   c                 B    | j         |                    d                   S )az  Deduce number of atoms in a given array of coordinates

        Parameters
        ----------
        filename : numpy.ndarray
          data which will be used later in MemoryReader
        order : {"afc", "acf", "caf", "fac", "fca", "cfa"} (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).

        Returns
        -------
        n_atoms : int
          number of atoms in system
        r$   )r1   r8   )r-   rL   rP   s      r   parse_n_atomszMemoryReader.parse_n_atoms  s    * ~ejjoo..r   c           
         | j         | j                                         nd}| j        | j                                        nd}| j                                        } | j        | j                                        f| j        |||| j        j        | j	        d| j
        }|| j        j                  | j                                        D ]-\  }}|                    ||                                           .| j        |_        |S )z#Return a copy of this Memory ReaderN)rL   rM   rN   rO   rD   r-   )r@   r'   rA   rF   rS   r7   r.   r
   rD   r-   r/   rH   _auxsitemsadd_auxiliarytransformations)rK   velsforsdimsr   auxnameauxreads          r   r'   zMemoryReader.copy  s$    ". $$&&& 	 (,'7'CD!!### 	 $))++dn!&&((	
#wz]	
 	
 l	
 	
 	DGM $
 0 0 2 2 	7 	7GWgw||~~6666 #2
r   c                 L    |                     dd          | _        || _        dS )a0  
        Set underlying array in desired column order.

        Parameters
        ----------
        coordinate_array : :class:`~numpy.ndarray` object
            The underlying array of coordinates
        order : {"afc", "acf", "caf", "fac", "fca", "cfa"} (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).
        r;   Fr&   N)r?   r7   stored_format)rK   r7   rL   s      r   r6   zMemoryReader.set_array  s-      !1 7 7	 7 N N"r   c                     | j         S )z*
        Return underlying array.
        )r7   rK   s    r   	get_arrayzMemoryReader.get_array  s     $$r   c                 6    d| j         _        d| j         _        dS )zReset iteration to first framer*   N)r
   rH   rI   rh   s    r   _reopenzMemoryReader._reopen  s    r   r   r*   afcc                    |.t          j        dt                     |rt          d          |}|dk    rt          j        dt                     |                                 }|| j        k    rn|d         | j        d         k    rt          j        |dd	          }n|d         | j        d         k    rt          j        |dd	          }n|d	         | j        d	         k    rt          j        |dd          }n|d         | j        d         k    r-t          j        |dd          }t          j        |dd	          }nC|d         | j        d	         k    r,t          j        |d	d          }t          j        |dd	          }|                    d
          }|                    d          }	|dz   }
|
dk    rd}
t          d          g|	z  t          ||
|          gz   t          d          gd	|	z
  z  z   }|t          |                   }|||j        j        u r|S t          |          dk    rt          d          |                    |j        |          S )a  Return a subset of coordinate data for an AtomGroup in desired
        column order. If no selection is given, it will return a view of the
        underlying array, while a copy is returned otherwise.

        Parameters
        ---------
        asel : AtomGroup (optional)
            Atom selection. Defaults to ``None``, in which case the full set of
            coordinate data is returned. Note that in this case, a view
            of the underlying numpy array is returned, while a copy of the
            data is returned whenever `asel` is different from ``None``.

            .. 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)
            the start trajectory frame
        stop : int (optional)
            the end trajectory frame

            .. deprecated:: 2.4.0
               Note that `stop` is currently *inclusive* but will be
               changed in favour of being *exclusive* in version 3.0.

        step : int (optional)
            the number of trajectory frames to skip
        order : {"afc", "acf", "caf", "fac", "fca", "cfa"} (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).


        .. versionchanged:: 1.0.0
           Deprecated `format` keyword has been removed. Use `order` instead.
        .. versionchanged:: 2.4.0
            ValueError now raised instead of NoDataError for empty input
            AtomGroup
        NzKasel argument to timeseries will be renamed to'atomgroup' in 3.0, see #3911)categoryz-Cannot provide both asel and atomgroup kwargsr*   zhMemoryReader.timeseries inclusive `stop` indexing will be removed in 3.0 in favour of exclusive indexingr   r   r!   r$   r#   z0Timeseries requires at least one atom to analyze)warningswarnDeprecationWarningr<   ri   r.   r2   swapaxesr8   slicetupleuniverseatomslentakeindices)rK   asel	atomgroupstartstopsteprL   arraya_indexf_index
stop_indexbasic_slices               r   
timeserieszMemoryReader.timeseries   s   Z M0+   
   C   I2::M ,	      D%%%1X*1---Kq!,,EE1X*1---Kq!,,EE1X*1---Kq!,,EE1X*1---Kq!,,EKq!,,EE1X*1---Kq!,,EKq!,,E**S//**S//AX
??J4[[MG#UJ--./T{{mq7{+, 	 eK(()	Y-?-E E EL9~~"" I   ::dlG444r   c                    | j         j        | j        dz
  k    rt          t          j        d          || j         }|xj        dz  c_        | j                            d          }t          d          g|z  | j         j        gz   t          d          gd|z
  z  z   }t          || j
        t          |                              t          || j        | j         j                            | j        (t          || j        t          |                              | j        (t#          || j        t          |                              | j         j        | j        z  |_        |S )zcopy next frame into timestepr   z"trying to go over trajectory limitNr#   r!   )r
   rH   r9   IOErrorerrnoEIOr.   r8   rs   r   r7   rt   r   rF   r@   r   rA   r   rD   rI   )rK   r
   r   r   s       r   rJ   z MemoryReader._read_next_timestepj  sJ    7=DMA---%)%IJJJ:B
A#((--4[[MW%w}oT{{mq7{+, 	
 	!T%:5;M;M%NOOOB 5dgm DEEE*%D'k(:(:;   '!"d&6u[7I7I&JKKK'-$')	r   c                 H    |dz
  | j         _        |                                 S )zread frame ir   )r
   rH   rJ   )rK   is     r   _read_framezMemoryReader._read_frame  s#     A'')))r   c                 Z    d                     | j        j        | j        | j                  S )zString representationz/<{cls} with {nframes} frames of {natoms} atoms>)clsnframesnatoms)r>   rS   __name__r9   r(   rh   s    r   __repr__zMemoryReader.__repr__  s2    CJJ'M< K 
 
 	
r   c                      t          t          |           j        |  t          |           D ]\  }}| j        D ]} ||          }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   add_transformations	enumerater_   )rK   r_   r   r
   	transformrS   s        r   r   z MemoryReader.add_transformations  si    @ 	6lD!!5GGt__ 	# 	#EAr!1 # #	Yr]]#	# 	#r   c                     |S )z,Applies the transformations to the timestep. )rK   r
   s     r   _apply_transformationsz#MemoryReader._apply_transformations  s	    
 	r   )r   Nr   NNN)r   )NNr   r*   r   rl   r   )r   
__module____qualname____doc__r>   r,   staticmethodrX   rZ   r'   r6   ri   rk   r   rJ   r   r   r   r   __classcell__)rS   s   @r   r   r      sa         F
 c# c# c# c# c# c#J - - \- / / / \/,  @# # # #&% % %   JOh5 h5 h5 h5T   4* * *
 
 
## ## ## ## ##J      r   r   )r   loggingr   numpyr2   ro   r'    r   timestepr   r   r   r   r   ProtoReaderr   r   r   r   <module>r      s   .` `B                      :  
  
  N N N N N4# N N N N Nr   