
     iF                        d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	 ddl
m
Z
 ddlZ ej        d	          Z ej         ed
          dd	d            ej         ed          dd	d           [ G d de          ZdS )a   
Mean Squared Displacement --- :mod:`MDAnalysis.analysis.msd`
==============================================================

:Authors: Hugo MacDermott-Opeskin
:Year: 2020
:Copyright: Lesser GNU Public License v2.1+

This module implements the calculation of Mean Squared Displacements (MSDs)
by the Einstein relation. MSDs can be used to characterize the speed at
which particles move and has its roots in the study of Brownian motion.
For a full explanation of the theory behind MSDs and the subsequent calculation
of self-diffusivities the reader is directed to :footcite:p:`Maginn2019`.
MSDs can be computed from the following expression, known as the
**Einstein formula**:

.. math::

   MSD(r_{d}) = \bigg{\langle} \frac{1}{N} \sum_{i=1}^{N} |r_{d}
    - r_{d}(t_0)|^2 \bigg{\rangle}_{t_{0}}

where :math:`N` is the number of equivalent particles the MSD is calculated
over, :math:`r` are their coordinates and :math:`d` the desired dimensionality
of the MSD. Note that while the definition of the MSD is universal, there are
many practical considerations to computing the MSD that vary between
implementations. In this module, we compute a "windowed" MSD, where the MSD
is averaged over all possible lag-times :math:`\tau \le \tau_{max}`,
where :math:`\tau_{max}` is the length of the trajectory, thereby maximizing
the number of samples.

The computation of the MSD in this way can be computationally intensive due to
its :math:`N^2` scaling with respect to :math:`\tau_{max}`. An algorithm to
compute the MSD with :math:`N log(N)` scaling based on a Fast Fourier
Transform is known and can be accessed by setting ``fft=True`` [Calandri2011]_
[Buyl2018]_. The FFT-based approach requires that the
`tidynamics <https://github.com/pdebuyl-lab/tidynamics>`_ package is
installed; otherwise the code will raise an :exc:`ImportError`.

Please cite [Calandri2011]_ [Buyl2018]_ if you use this module in addition to
the normal MDAnalysis citations.

.. warning::
   To correctly compute the MSD using this analysis module, you must supply
   coordinates in the **unwrapped** convention, also known as **no-jump**. 
   That is, when atoms pass the periodic boundary, they must not be wrapped 
   back into the primary simulation cell.
   
   In MDAnalysis you can use the 
   :class:`~MDAnalysis.transformations.nojump.NoJump`
   transformation. 
   
   In GROMACS, for example, this can be done using `gmx trjconv`_ with the
   ``-pbc nojump`` flag.

.. _`gmx trjconv`: https://manual.gromacs.org/current/onlinehelp/gmx-trjconv.html

.. SeeAlso::
   :mod:`MDAnalysis.transformations.nojump`


Computing an MSD
----------------
This example computes a 3D MSD for the movement of 100 particles undergoing a
random walk. Files provided as part of the MDAnalysis test suite are used
(in the variables :data:`~MDAnalysis.tests.datafiles.RANDOM_WALK` and
:data:`~MDAnalysis.tests.datafiles.RANDOM_WALK_TOPO`)

First load all modules and test data

.. code-block:: python

    import MDAnalysis as mda
    import MDAnalysis.analysis.msd as msd
    from MDAnalysis.tests.datafiles import RANDOM_WALK_TOPO, RANDOM_WALK

Given a universe containing trajectory data we can extract the MSD
analysis by using the class :class:`EinsteinMSD`

.. code-block:: python

    u = mda.Universe(RANDOM_WALK_TOPO, RANDOM_WALK)
    MSD = msd.EinsteinMSD(u, select='all', msd_type='xyz', fft=True)
    MSD.run()

The MSD can then be accessed as

.. code-block:: python

    msd =  MSD.results.timeseries
    lagtimes = MSD.results.delta_t_values

Visual inspection of the MSD is important, so let's take a look at it with a simple plot.

.. code-block:: python

    import matplotlib.pyplot as plt
    nframes = MSD.n_frames
    fig = plt.figure()
    ax = plt.axes()
    # plot the actual MSD
    ax.plot(lagtimes, msd, lc="black", ls="-", label=r'3D random walk')
    exact = lagtimes*6
    # plot the exact result
    ax.plot(lagtimes, exact, lc="black", ls="--", label=r'$y=2 D\tau$')
    plt.show()

This gives us the plot of the MSD with respect to lag-time (:math:`\tau`).
We can see that the MSD is approximately linear with respect to :math:`\tau`.
This is a numerical example of a known theoretical result that the MSD of a
random walk is linear with respect to lag-time, with a slope of :math:`2d`.
In this expression :math:`d` is the dimensionality of the MSD. For our 3D MSD,
this is 3. For comparison we have plotted the line :math:`y=6\tau` to which an
ensemble of 3D random walks should converge.

.. _figure-msd:

.. figure:: /images/msd_demo_plot.png
    :scale: 100 %
    :alt: MSD plot

Note that a segment of the MSD is required to be linear to accurately
determine self-diffusivity. This linear segment represents the so called
"middle" of the MSD plot, where ballistic trajectories at short time-lags are
excluded along with poorly averaged data at long time-lags. We can select the
"middle" of the MSD by indexing the MSD and the time-lags. Appropriately
linear segments of the MSD can be confirmed with a log-log plot as is often
reccomended :footcite:p:`Maginn2019` where the "middle" segment can be identified
as having a slope of 1.

.. code-block:: python

    plt.loglog(lagtimes, msd)
    plt.show()

Now that we have identified what segment of our MSD to analyse, let's compute
a self-diffusivity.

Computing Self-Diffusivity
--------------------------------
Self-diffusivity is closely related to the MSD.

.. math::

   D_d = \frac{1}{2d} \lim_{t \to \infty} \frac{d}{dt} MSD(r_{d})

From the MSD, self-diffusivities :math:`D` with the desired dimensionality
:math:`d` can be computed by fitting the MSD with respect to the lag-time to
a linear model. An example of this is shown below, using the MSD computed in
the example above. The segment between :math:`\tau = 20` and :math:`\tau = 60`
is used to demonstrate selection of a MSD segment.

.. code-block:: python

    from scipy.stats import linregress
    start_time = 20
    start_index = int(start_time/timestep)
    end_time = 60
    linear_model = linregress(lagtimes[start_index:end_index], msd[start_index:end_index])
    slope = linear_model.slope
    error = linear_model.stderr
    # dim_fac is 3 as we computed a 3D msd with 'xyz'
    D = slope * 1/(2*MSD.dim_fac)

We have now computed a self-diffusivity!

Combining Multiple Replicates
--------------------------------
It is common practice to combine replicates when calculating MSDs. An example
of this is shown below using MSD1 and MSD2.

.. code-block:: python

    u1 = mda.Universe(RANDOM_WALK_TOPO, RANDOM_WALK)
    MSD1 = msd.EinsteinMSD(u1, select='all', msd_type='xyz', fft=True)
    MSD1.run()

    u2 = mda.Universe(RANDOM_WALK_TOPO, RANDOM_WALK)
    MSD2 = msd.EinsteinMSD(u2, select='all', msd_type='xyz', fft=True)
    MSD2.run()

    combined_msds = np.concatenate((MSD1.results.msds_by_particle,
                                    MSD2.results.msds_by_particle), axis=1)
    average_msd = np.mean(combined_msds, axis=1)

The same cannot be achieved by concatenating the replicas in a single run as
the jump between the last frame of the first trajectory and frame 0 of the
next trajectory will lead to an artificial inflation of the MSD and hence
any subsequent diffusion coefficient calculated.

Notes
_____

There are several factors that must be taken into account when setting up and
processing trajectories for computation of self-diffusivities.
These include specific instructions around simulation settings, using
unwrapped trajectories and maintaining a relatively small elapsed time between
saved frames. Additionally, corrections for finite size effects are sometimes
employed along with various means of estimating errors
:footcite:p:`Yeh2004,Bulow2020` The reader is directed to the following review,
which describes many of the common pitfalls :footcite:p:`Maginn2019`. There are
other ways to compute self-diffusivity, such as from a Green-Kubo integral. At
this point in time, these methods are beyond the scope of this module.


Note also that computation of MSDs is highly memory intensive. If this is
proving a problem, judicious use of the ``start``, ``stop``, ``step`` keywords
to control which frames are incorporated may be required.

References
----------

.. footbibliography::


Classes
-------

.. autoclass:: EinsteinMSD
    :members:
    :inherited-members:

    N   )dueDoi   )AnalysisBase)groups)tqdmzMDAnalysis.analysis.msdz10.21105/joss.00877z*Mean Squared Displacements with tidynamicsT)descriptionpathcite_modulez10.1051/sfn/201112010zFCA fast correlation algorithmc                   V     e Zd ZdZ	 	 	 	 d fd	Zd Zd Zd	 Zd
 Zd Z	d Z
d Z xZS )EinsteinMSDux  Class to calculate Mean Squared Displacement by the Einstein relation.

    Parameters
    ----------
    u : Universe or AtomGroup
        An MDAnalysis :class:`Universe` or :class:`AtomGroup`.
        Note that :class:`UpdatingAtomGroup` instances are not accepted.
    select : str
        A selection string. Defaults to "all" in which case
        all atoms are selected.
    msd_type : {'xyz', 'xy', 'yz', 'xz', 'x', 'y', 'z'}
        Desired dimensions to be included in the MSD. Defaults to 'xyz'.
    fft : bool
        If ``True``, uses a fast FFT based algorithm for computation of
        the MSD. Otherwise, use the simple "windowed" algorithm.
        The tidynamics package is required for `fft=True`.
        Defaults to ``True``.
    non_linear : bool
        If ``True``, calculates MSD for trajectory where frames are
        non-linearly dumped. To use this set `fft=False`.
        Defaults to ``False``.

        .. versionadded:: 2.10.0


    Attributes
    ----------
    dim_fac : int
        Dimensionality :math:`d` of the MSD.
    results.timeseries : :class:`numpy.ndarray`
        The averaged MSD over all the particles with respect to constant lag-time or
        unique Δt intervals.
    results.msds_by_particle : :class:`numpy.ndarray`
        The MSD of each individual particle with respect to constant lag-time or
        unique Δt intervals.
            - for `non_linear=False`: a 2D array of shape (n_lagtimes, n_atoms)
            - for `non_linear=True`: a 2D array of shape (n_delta_t_values, n_atoms)
    results.delta_t_values : :class:`numpy.ndarray`
        Array of unique Δt (time differences) at which time-averaged MSD values are
        computed.

        .. versionadded:: 2.10.0

    ag : :class:`AtomGroup`
        The :class:`AtomGroup` resulting from your selection
    n_frames : int
        Number of frames included in the analysis.
    n_particles : int
        Number of particles MSD was calculated over.


    .. versionadded:: 2.0.0
    .. versionchanged:: 2.10.0
       Added ability to calculate MSD from samples that are not linearly spaced with the
       new `non_linear` keyword argument.
    allxyzTFc                    t          |t          j                  rt          d           t	          t
          |           j        |j        j        fi | || _	        || _
        |                                  || _        || _        |                    | j	                  | _        t!          | j                  | _        d | _        d | j        _        d | j        _        d | j        _        d S )Nz4UpdatingAtomGroups are not valid for MSD computation)
isinstancer   UpdatingAtomGroup	TypeErrorsuperr   __init__universe
trajectoryselectmsd_type_parse_msd_typefft
non_linearselect_atomsaglenn_particles_position_arrayresultsmsds_by_particle
timeseriesdelta_t_values)selfur   r   r   r   kwargs	__class__s          a/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/analysis/msd.pyr   zEinsteinMSD.__init__J  s     a122 	F   	*k4  )!**?JJ6JJJ  $ ..--tw<<# )-%"&&*###    c                     t          j        | j        | j        f          | j        _        t          j        | j        | j        | j        f          | _        d S N)npzerosn_framesr!   r#   r$   dim_facr"   r'   s    r+   _preparezEinsteinMSD._preparek  sT     )+]D,-)
 )
%  "x]D,dl; 
  
r,   c                 0   dgdgdgddgddgddgg dd}| j                                         | _         	 || j                  | _        n5# t          $ r( t	          d                    | j                             w xY wt          | j                  | _        dS )z.Sets up the desired dimensionality of the MSD.r   r   r   )r   r   r   )xyzxyxzyzr   zNinvalid msd_type: {} specified, please specify one of xyz, xy, xz, yz, x, y, zN)r   lower_dimKeyError
ValueErrorformatr    r2   )r'   keyss     r+   r   zEinsteinMSD._parse_msd_typev  s     a&a&a&99
 
 ++--	T]+DII 	 	 	&&,fT]&;&;  	 49~~s   A 2A:c                 V    | j         j        dd| j        f         | j        | j        <   dS )z2Constructs array of positions for MSD calculation.N)r   	positionsr=   r"   _frame_indexr3   s    r+   _single_framezEinsteinMSD._single_frame  s1     37'2CAAtyL3
T.///r,   c                     | j         r|                                  d S | j        r|                                  d S |                                  d S r.   )r   _conclude_non_linearr   _conclude_fft_conclude_simpler3   s    r+   	_concludezEinsteinMSD._conclude  s^    ? 	(%%'''''x (""$$$$$%%'''''r,   c                 ^   t          j        d| j                  }| j                            t           j                  }t          |          D ]u}|d| ddddf         ||dddddf         z
  }t          j        |                              d          }t          j	        |d          | j
        j        |ddf<   v| j
        j        	                    d          | j
        _        t          j        | j                  | j        d         | j        d         z
  z  | j
        _        dS )z7Calculates the MSD via the simple "windowed" algorithm.r   Naxisr   )r/   aranger1   r"   astypefloat64r	   squaresummeanr#   r$   r%   timesr&   )r'   lagtimesrC   lagdispsqdists         r+   rI   zEinsteinMSD._conclude_simple  s   9Q..(//
;;	>> 	L 	LCUsdUAAAqqq[)IcddAAAqqqj,AADYt__((b(11F46GF4K4K4KDL)#qqq&11"&,"?"D"D!"D"L"L&(i&>&>JqMDJqM)'
###r,   c                    	 ddl }n# t          $ r t          d          w xY w| j                            t          j                  }t          t          | j                            D ]5}|	                    |dd|ddf                   | j
        j        dd|f<   6| j
        j                            d          | j
        _        t	          j        | j                  | j        d         | j        d         z
  z  | j
        _        dS )z:Calculates the MSD via the FCA fast correlation algorithm.r   NzERROR --- tidynamics was not found!

                tidynamics is required to compute an FFT based MSD (default)

                try installing it using pip eg:

                    pip install tidynamics

                or set fft=Falser   rM   )
tidynamicsImportErrorr"   rP   r/   rQ   r	   ranger!   msdr#   r$   rT   r%   rO   r1   rU   r&   )r'   r[   rC   ns       r+   rH   zEinsteinMSD._conclude_fft  s   	 	 	 	$
 
 
	 (//
;;	eD,--.. 	 	A2<..!!!Q'"3 3DL)!!!Q$// #',"?"D"D!"D"L"L&(i&>&>JqMDJqM)'
###s    !c                 F   | j         }| j        }| j                            t          j                  }t          j        t                    t          j        t                    }t          |          D ]}t          |dz   |          D ]}| j
        |         | j
        |         z
  }||         ||         z
  }t	          j        |dz  d          }	t	          j        |	          }
|                             |
           ||                             |	           dgd<   t	          j        |          g|d<   t                                                    }fd|D             }t	          j        t#          |          |f          }t%          |          D ]<\  }}t	          j        ||                   }t	          j        |d          ||d d f<   =t	          j        |          | j        _        t	          j        |          | j        _        || j        _        d S )Nr   r   rM   r   g        c                 D    g | ]}t          j        |                   S  )r/   rT   ).0dtmsd_dicts     r+   
<listcomp>z4EinsteinMSD._conclude_non_linear.<locals>.<listcomp>  s'    CCCbBGHRL))CCCr,   )r1   r!   r"   rP   r/   rQ   collectionsdefaultdictlistr]   rU   rS   rT   appendr0   sortedrA   r    	enumeratevstackarrayr#   r%   r&   r$   )r'   r1   n_atomsrC   msds_by_particle_dictijdelta_trX   squared_dispr^   r&   avg_msdsmsds_by_particle_arrayidxrd   arrre   s                    @r+   rG   z EinsteinMSD._conclude_non_linear  s   ="(//
;;	*400 + 7 = = x 		D 		DA1q5(++ D D*Q-$*Q-7 |il2!vdAgA666gl++!((---%g.55lCCCCD c&(hw&7&7%8c"  00CCCCNCCC!#3~+>+>*H!I!I 00 	B 	BGC)1"566C-/WSq-A-A-A"36**"$(8"4"4&(h~&>&>#(>%%%r,   )r   r   TF)__name__
__module____qualname____doc__r   r4   r   rE   rJ   rI   rH   rG   __classcell__)r*   s   @r+   r   r     s        7 7x + + + + + +B
 
 
& & &0
 
 
( ( (
 
 

 
 
6$? $? $? $? $? $? $?r,   r   )r|   numpyr/   loggingr   r   baser   corer   r	   rg   	getLoggerloggerciter   rb   r,   r+   <module>r      s?  0] ]~                                   		4	5	5 C<	"	    	C  0	"	    [? [? [? [? [?, [? [? [? [? [?r,   