
     i                        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
Z
ddlmZ ddlmZ ddlmZ dd	lmZ  ej        d
          Z	 ddlZn"# e$ r dZe                    d           Y nw xY w G d dej                  Z G d dej                  Z G d dej                  Z G d dej        j                  ZdS )u  AMBER trajectories --- :mod:`MDAnalysis.coordinates.TRJ`
========================================================

AMBER_ can write :ref:`ASCII trajectories<ascii-trajectories>` ("traj") and
:ref:`binary trajectories<netcdf-trajectories>` ("netcdf"). MDAnalysis supports
reading of both formats and writing for the binary trajectories.

Note
----
Support for AMBER is still somewhat *experimental* and feedback and
contributions are highly appreciated. Use the `Issue Tracker`_ or get in touch
on the `GitHub Discussions`_.


.. rubric:: Units

AMBER trajectories are assumed to be in the following units:

* lengths in Angstrom (Å)
* time in ps (but see below)


.. _netcdf-trajectories:

Binary NetCDF trajectories
--------------------------

The `AMBER netcdf`_ format make use of NetCDF_ (Network Common Data
Form) format. Such binary trajectories are recognized in MDAnalysis by
the '.ncdf' suffix and read by the :class:`NCDFReader`.

Binary trajectories can also contain velocities and forces, and can record the
exact time
step. In principle, the trajectories can be in different units than the AMBER
defaults of ångström and picoseconds but at the moment MDAnalysis only supports
those and will raise a :exc:`NotImplementedError` if anything else is detected.

.. autoclass:: NCDFReader
   :members:

.. autoclass:: NCDFWriter
   :members:

.. autoclass:: NCDFPicklable
   :members:

.. _ascii-trajectories:

ASCII TRAJ trajectories
-----------------------

ASCII AMBER_ TRJ coordinate files (as defined in `AMBER TRJ format`_)
are handled by the :class:`TRJReader`. It is also possible to directly
read *bzip2* or *gzip* compressed files.

AMBER ASCII trajectories are recognised by the suffix '.trj',
'.mdcrd' or '.crdbox (possibly with an additional '.gz' or '.bz2').

.. Note::

   In the AMBER community, these trajectories are often saved with the
   suffix '.crd' but this extension conflicts with the CHARMM CRD
   format and MDAnalysis *will not correctly autodetect AMBER ".crd"
   trajectories*. Instead, explicitly provide the ``format="TRJ"``
   argument to :class:`~MDAnalysis.core.universe.Universe`::

     u = MDAnalysis.Universe("top.prmtop", "traj.crd", format="TRJ")

   In this way, the AMBER :class:`TRJReader` is used.


.. rubric:: Limitations

* Periodic boxes are only stored as box lengths A, B, C in an AMBER
  trajectory; the reader always assumes that these are orthorhombic
  boxes.

* The trajectory does not contain time information so we simply set
  the time step to 1 ps (or the user could provide it as kwarg *dt*)

* Trajectories with fewer than 4 atoms probably fail to be read (BUG).

* If the trajectory contains exactly *one* atom then it is always
  assumed to be non-periodic (for technical reasons).

* Velocities are currently *not supported* as ASCII trajectories.

.. autoclass:: TRJReader
   :members:



.. Links

.. _AMBER: http://ambermd.org
.. _AMBER TRJ format: https://ambermd.org/FileFormats.php#trajectory
..    The formats page was archived as
..    http://www.webcitation.org/query?url=http%3A%2F%2Fambermd.org%2Fformats.html&date=2018-02-11
..    Use the archived version if the original (https://ambermd.org/FileFormats.php#trajectory) disappears. [orbeckst]
.. _AMBER netcdf format: http://ambermd.org/netcdf/nctraj.xhtml
..    The formats page was archived as
..    http://www.webcitation.org/query?url=http%3A%2F%2Fambermd.org%2Fnetcdf%2Fnctraj.xhtml&date=2018-02-11
..    Use the archived version if the original disappears. [orbeckst]
.. _AMBER netcdf: http://ambermd.org/netcdf/nctraj.xhtml
.. _NetCDF: http://www.unidata.ucar.edu/software/netcdf
.. _Issue Tracker: https://github.com/MDAnalysis/mdanalysis/issues
.. _GitHub Discussions: https://github.com/MDAnalysis/mdanalysis/discussions

    N)isclose   )Timestep)base   )util)store_init_argumentszMDAnalysis.coordinates.AMBERz@netCDF4 is not available. Writing AMBER ncdf files will be slow.c                        e Zd ZdZg dZdddZeZed fd	            Z	d Z
d	 Zd
 Zed             Zd Zed             Zd Zd Zd Z xZS )	TRJReaderaC  AMBER trajectory reader.

    Reads the ASCII formatted `AMBER TRJ format`_. Periodic box information
    is auto-detected.

    The number of atoms in a timestep *must* be provided in the `n_atoms`
    keyword because it is not stored in the trajectory header and cannot be
    reliably autodetected. The constructor raises a :exc:`ValueError` if
    `n_atoms` is left at its default value of ``None``.

    The length of a timestep is not stored in the trajectory itself but can
    be set by passing the `dt` keyword argument to the constructor; it
    is assumed to be in ps. The default value is 1 ps.

    .. _AMBER TRJ format: https://ambermd.org/FileFormats.php#trajectory

    .. versionchanged:: 0.11.0
       Frames now 0-based instead of 1-based.
       kwarg `delta` renamed to `dt`, for uniformity with other Readers
    )TRJMDCRDCRDBOXpsAngstrom)timelengthNc                     t          t          |           j        |fi | |t          d          || _        d | _        d | _         | j        | j        fi | j	        | _
        t          j        d          | _        t          t          j        d| j        z  t#          | j                  z                      | _        d| j        z  t#          | j                  z  }t          j        d                    |                    | _        t          j        d          | _        |                                  |                                  d S )Nz-AMBER TRJ reader REQUIRES the n_atoms keywordz10F8.3g      @   z	{0:d}F8.3z3F8.3)superr   __init__
ValueError_n_atoms	_n_framestrjfile	_Timestepn_atoms
_ts_kwargstsr   FORTRANReaderdefault_line_parserintnpceillenlines_per_frameformatlast_line_parserbox_line_parser_detect_amber_box_read_next_timestep)selffilenamer   kwargslast_per_line	__class__s        d/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/TRJ.pyr   zTRJReader.__init__   sR   'i';;F;;;?LMMM $.AAAA $(#5h#?#? "273+=$A& A& ,& $' $'  (  (
 DL(3t/G+H+HH $ 2;3E3E4 4 ! !
  $1':: 	    	  """""    c                     | j         |                                  | j                             | j        |                    |dz
  | j        _        |                                 S Nr   )r   open_trajectoryseek_offsetsr   framer*   )r+   r7   s     r0   _read_framezTRJReader._read_frame   sX    <  """$-.///	'')))r1   c                    | j         }| j        |                                  g }t          | j                  D ]\  }}	 |                    | j                            |                     n=# t          $ r0 |                    | j                            |                     Y nw xY w|| j	        dz
  k    r n|g k    rt          | j        r:t          | j                  }| j                            |          }|g dz   |_        t          j        |                              | j        d          |j        d d <   |xj        dz  c_        |S )Nr        V@r;   r;   r   )r   r   r4   	enumerateextendr    readr   r'   r%   EOFErrorperiodicnextr(   
dimensionsr"   arrayreshaper   _posr7   )r+   r   _coordsnumberlineboxs         r0   r*   zTRJReader._read_next_timestep   sl   W<  """ %dl33 	 	LFDAt7<<TBBCCCC A A At499$??@@@@@A -111 2 b==N = 	2%%D&++D11C///1BM
 Xg&&..t|Q??

A	s   -A--7B'&B'c                    | j         dk    rd| _        d}t          j        |           dS |                                  d| _        |                                  | j        }t          | j                  }| j	        
                    |          }|dk    r,d| _        | j                            |          g dz   |_        nd| _        |                                  | j        S )a  Detecting a box in a AMBER trajectory

        Rewind trajectory and check for potential box data
        after the first frame.

        Set :attr:`TRJReader.periodic` to ``True`` if box was
        found, ``False`` otherwise.

        Only run at the beginning as it *rewinds* the trajctory.

         - see if there's data after the atoms have been read that looks
           like::

             FORMAT(10F8.3)  BOX(1), BOX(2), BOX(3)
             BOX    : size of periodic box

         - this WILL fail if we have exactly 1 atom in the trajectory because
           there's no way to distinguish the coordinates from the box
           so for 1 atom we always assume no box

        .. TODO:: needs a Timestep that knows about AMBER unitcells!
        r   Fz:Trajectory contains a single atom: assuming periodic=Falser   Tr:   )r   r@   warningswarn_reopenr*   r   rA   r   r    number_of_matchesr(   r>   rB   close)r+   wmsgr   rH   nentriess        r0   r)   zTRJReader._detect_amber_box   s    . <1!DMODM$5  """WDL!!+==dCCq== DM 055d;;oooMBMM!DM

}r1   c                     | j         | j         S 	 |                     | j                  | _         | j         S # t          $ r Y dS w xY w)z>Number of frames (obtained from reading the whole trajectory).Nr   )r   _read_trj_n_framesr,   IOErrorr+   s    r0   n_frameszTRJReader.n_frames*  s^     >%>!	"!44T]CCDN >!  	 	 	11	s   6 
AAc                    | j         }| j        r|dz  }g x| _        }d}t          j        | j                  5 }|                                }|rK||z  dk    r'|                    |                                           |                                }|dz  }|Kd d d            n# 1 swxY w Y   |	                                 t          |          S )Nr   r   )r%   r@   r6   r   openanyr,   readlineappendtellpopr$   )r+   r,   lpfoffsetscounterfrH   s          r0   rS   zTRJReader._read_trj_n_frames6  s   "= 	1HC"$$\$-(( 	A::<<D S=A%%NN16688,,,zz||1	  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	7||s   A"B&&B*-B*c                     | j         S N)r   rU   s    r0   r   zTRJReader.n_atomsG  s
    }r1   c                 V    |                                   |                                  d S rb   )rO   r4   rU   s    r0   rM   zTRJReader._reopenK  s'    

r1   c                    t          j        | j                  | _        | j                                        | _        t          | j                                                  dk    rt          d          | j	        }d|_
        | j        S )z5Open the trajectory for reading and load first frame.P   zeHeader of AMBER formatted trajectory has more than 80 chars. This is probably not a AMBER trajectory.)r   anyopenr,   r   rY   headerr$   rstripOSErrorr   r7   r+   r   s     r0   r4   zTRJReader.open_trajectoryO  sz    |DM22l++--t{!!##$$r));< < < W|r1   c                 X    | j         dS | j                                          d| _         dS )z)Close trj trajectory file if it was open.Nr   rO   rU   s    r0   rO   zTRJReader.close^  s.    <Fr1   rb   )__name__
__module____qualname____doc__r&   unitsr   r   r	   r   r8   r*   r)   propertyrV   rS   r   rM   r4   rO   __classcell__r/   s   @r0   r   r      s        ( (''FZ00EI# # # # # #>* * *! ! !F+ + +Z 	" 	" X	"  "   X          r1   r   c                        e Zd ZdZddgZdZdZdddd	d
ZeZ	e
d fd	            Zed             Zed             Zd Zd Zd ZddZd Zd Zd Z xZS )
NCDFReadera  Reader for `AMBER NETCDF format`_ (version 1.0).

    AMBER binary trajectories are automatically recognised by the
    file extension ".ncdf".

    The number of atoms (`n_atoms`) does not have to be provided as it can
    be read from the trajectory. The trajectory reader can randomly access
    frames and therefore supports direct indexing (with 0-based frame
    indices) and full-feature trajectory iteration, including slicing.

    Velocities are autodetected and read into the
    :attr:`Timestep._velocities` attribute.

    Forces are autodetected and read into the
    :attr:`Timestep._forces` attribute.

    Periodic unit cell information is detected and used to populate the
    :attr:`Timestep.dimensions` attribute. (If no unit cell is available in
    the trajectory, then :attr:`Timestep.dimensions` will return
    ``[0,0,0,0,0,0]``).

    Current limitations:

    * only trajectories with time in ps and lengths in Angstroem are processed

    The NCDF reader uses :mod:`scipy.io.netcdf` and therefore :mod:`scipy` must
    be installed. It supports the *mmap* keyword argument (when reading):
    ``mmap=True`` is memory efficient and directly maps the trajectory on disk
    to memory (using the :class:`~mmap.mmap`); ``mmap=False`` may consume large
    amounts of memory because it loads the whole trajectory into memory but it
    might be faster. The default is ``mmap=None`` and then default behavior of
    :class:`scipy.io.netcdf_file` prevails, i.e. ``True`` when
    *filename* is a file name, ``False`` when *filename* is a file-like object.

    .. _AMBER NETCDF format: http://ambermd.org/netcdf/nctraj.xhtml

    See Also
    --------
    :class:`NCDFWriter`


    .. versionadded: 0.7.6
    .. versionchanged:: 0.10.0
       Added ability to read Forces
    .. versionchanged:: 0.11.0
       Frame labels now 0-based instead of 1-based.
       kwarg `delta` renamed to `dt`, for uniformity with other Readers.
    .. versionchanged:: 0.17.0
       Uses :mod:`scipy.io.netcdf` and supports the *mmap* kwarg.
    .. versionchanged:: 0.20.0
       Now reads scale_factors for all expected AMBER convention variables.
       Timestep variables now adhere standard MDAnalysis units, with lengths
       of angstrom, time of ps, velocity of angstrom/ps and force of
       kJ/(mol*Angstrom). It is noted that with 0.19.2 and earlier versions,
       velocities would have often been reported in values of angstrom/AKMA
       time units instead (Issue #2323).
    .. versionchanged:: 1.0.0
       Support for reading `degrees` units for `cell_angles` has now been
       removed (Issue #2327)
    .. versionchanged:: 2.0.0
       Now use a picklable :class:`scipy.io.netcdf_file`--
       :class:`NCDFPicklable`.
       Reading of `dt` now defaults to 1.0 ps if `dt` cannot be extracted from
       the first two frames of the trajectory.
       :meth:`Writer` now also sets `convert_units`, `velocities`, `forces` and
       `scale_factor` information for the :class:`NCDFWriter`.

    NCDFNCT1.0r   r   Angstrom/pskcal/(mol*Angstrom)r   r   velocityforceNc                    || _          t          t          |           j        |fi | t	          | j        | j         d          | _        	 | j        j        }d|                    d          	                    d          v sld|                    d          	                                v sCd
                    | j                  }t                              |           t          |          nR# t          $ rE d
                    | j                  }t                              |           t          |          d w xY w	 | j        j                            d          }|| j        k    sId
                    || j                  }t%          j        |           t                              |           n8# t          $ r+ d	
                    | j                  }t          |          d w xY w| j        j        d
k    sCd
                    | j                  }t                              |           t          |          	 | j        j        d         dk    sd}t          |          n # t.          $ r d}t          |          d w xY wt1          | j        d          rt1          | j        d          sHd
                    | j                  }t%          j        |           t                              |           	 | j        j        d         | _        |5|| j        k    r*d
                    || j                  }t          |          n8# t.          $ r+ d
                    | j                  }t          |          d w xY w	 | j        j        d         | _        | j        "| j        j        d         j        d         | _        n)# t.          $ r d| j         d}t          |          d w xY w	 | j        j        | _        n# t          $ r
 d| _        Y nw xY w	 |                     | j        j        d         j         d           d| _!        nG# t.          $ r: d| _!        d}t%          j        |           t                              |           Y nw xY w|                     | j        j        d         j         d            d d d d d d d!| _"        | j        j        D ]}	t1          | j        j        |	         d"          r|	| j"        v rU| j        j        |	         j#        }
tI          |
tJ          tL          j'        f          st          |
 d#          |
| j"        |	<   d$
                    |	          }tQ          |          d%| j        j        v | _)        | j)        r+|                     | j        j        d%         j         d&           d'| j        j        v | _*        | j*        r+|                     | j        j        d'         j         d(           d)| j        j        v | _+        | j+        rX|                     | j        j        d)         j         d            | j        j        d*         j         }|                     |d+           d| _,         | j-        | j        f| j)        | j*        | d,| j.        | _/        | 0                    d           d S )-NF)mmapmaskandscaleAMBERutf-8,zNCDF trajectory {0} does not conform to AMBER specifications, http://ambermd.org/netcdf/nctraj.xhtml ('AMBER' must be one of the token in attribute Conventions)z*NCDF trajectory {0} is missing ConventionszFNCDF trajectory format is {0!s} but the reader implements format {1!s}z0NCDF trajectory {0} is missing ConventionVersionr   zNCDF trajectory {0} does not conform to AMBER specifications, as detailed in https://ambermd.org/netcdf/nctraj.xhtml (NetCDF file does not use 64 bit offsets [version_byte = 2])spatialr   z0Incorrect spatial value for NCDF trajectory filez2NCDF trajectory does not contain spatial dimensionprogramprogramVersionz~NCDF trajectory {0} may not fully adhere to AMBER standards as either the `program` or `programVersion` attributes are missingatomzkSupplied n_atoms ({0}) != natom from ncdf ({1}). Note: n_atoms can be None and then the ncdf value is used!z5NCDF trajectory {0} does not contain atom informationr7   coordinatesr   zNCDF trajectory z# does not contain frame information r   
picosecondTz^NCDF trajectory does not contain `time` information; `time` will be set as an increasing indexangstromr   cell_lengthscell_anglesr   
velocitiesforcesscale_factor is not a floatz2scale_factors for variable {0} are not implementedr   angstrom/picosecondr   kilocalorie/mole/angstromr   r   degree)r   r   reader)1_mmapr   rw   r   NCDFPicklabler,   r   Conventionsdecodesplitr&   loggerfatal	TypeErrorAttributeErrorr   ConventionVersionversionrK   rL   warningversion_byterB   KeyErrorhasattrr   rV   	variablesshapetitleremarks_verify_unitsrr   has_timescale_factorsr   
isinstancefloatr"   floatingNotImplementedErrorhas_velocities
has_forcesr@   _current_framer   r   r   r8   )r+   r,   r   r   r-   conventionserrmsgr   rP   variabler   cell_angle_unitsr/   s               r0   r   zNCDFReader.__init__  sX    
(j$(<<V<<< %T]*.*279 9 9
	/,2K{11'::@@EEEE{11'::@@BBBB) *0)>)>	 
 V$$$''' 	/ 	/ 	/AHHm% %FLL   V$$$.		/	/ $ > E Eg N N$44228&*DL3: 3:  d###t$$$ 	/ 	/ 	/GNNm% %FV$$$.	/ |(A--, -3F4=,A,A	 
 LL   F###	/<*95::K''' ;  	/ 	/ 	/IFV$$$.	/ i00 	!&677	!--3VDM-B-B  M$NN4   
	/<26:DL"w$,'>'>%%+VGT\%B%B  !((( 	/ 	/ 	/$$*F4=$9$9 V$$$.	/
	/ L3G<DM }$ $ 6} E KA N 	/ 	/ 	/+ + + +FV$$$.	/
	<-DLL 	 	 	DLLL		!t|5f=C\RRR DMM 	! 	! 	!!DMADM$NN4     	! 	4<1-@F%	' 	' 	'
 '+.2-1-1,0(,. . . 
	6 
	6Ht|-h7HH 	6t111#'<#9(#C#PL%lUBK4HII J'<(H(H(HIII3?D&x00006x0@0@ -f555	6 +dl.DD 	6t|5lCI46 6 6 #dl&<<? 	<t|5h?E:< < < '$,*@@= 	;t|5nEK)+ + +  $|5mDJ/::: $. 4,0,?(,(,4 4 $(?	4 4 	sf   B"C/ /AD>A3F6 65G+'I* *J=AM 5NA O &O,0P PP2Q ARRc                     |                      d          |k    r8d                    |                      d          |          }t          |          d S )Nr   z]NETCDFReader currently assumes that the trajectory was written in units of {0} instead of {1})r   r&   r   )	eval_unitexpected_unitsr   s      r0   r   zNCDFReader._verify_unitsc  sd    G$$66CCI6 ''00.DB DB  &f---	 76r1   c                     t           j                            | d           5 }|j        d         }d d d            n# 1 swxY w Y   |S )N)r   r   )scipyionetcdf_filerB   )r,   r-   r`   r   s       r0   parse_n_atomszNCDFReader.parse_n_atomsk  s    X!!(!66 	+!l6*G	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+s   <A A c                     | j         |         }|t          |d          r| j        j        |         |         S | j        j        |         |         |z  S )zHelper function to get variable at given frame from NETCDF file and
        scale if necessary.

        Note
        ----
        If scale_factor is 1.0 within numerical precision then we don't apply
        the scaling.
        Nr   )r   r   r   r   )r+   r   r7   r   s       r0   _get_var_and_scalezNCDFReader._get_var_and_scaleq  sU     )(37<#;#;<)(3E::<)(3E:\IIr1   c                    | j         }| j        t          d          t          j        t          |                    t          j        t                    k    rt          d          || j        k    s|dk     r't          d
                    | j                            |                     d|          |j        d d <   | j        r|                     d|          |_        | j        r |                     d|          |j        d d <   | j        r |                     d|          |j        d d <   | j        rQt          j        d	          }|                     d
|          |d d<   |                     d|          |dd <   ||_        | j        r|                     |j                   |                     |j                   | j        r|                     |j        d           | j        r|                     |j        d           | j        r"|                     |j        d d                    ||_        || _        |S )NzTrajectory is closedz(frame must be a positive integer or zeror   z$frame index must be 0 <= frame < {0}r   r   r   r      r   r   r   Tinplace)r   r   rT   r"   dtypetyper!   r   rV   
IndexErrorr&   r   rE   r   r   r   _velocitiesr   _forcesr@   zerosrB   convert_unitsconvert_pos_from_nativeconvert_time_from_nativeconvert_velocities_from_nativeconvert_forces_from_nativer7   r   )r+   r7   r   unitcells       r0   r8   zNCDFReader._read_frame  sW   W<01118DKK  BHSMM11FGGGDM!!UQYYCJJ        ,,]EBB
= 	=--fe<<BG 	M $ 7 7e L LBN111? 	E 33HeDDBJqqqM= 	%x{{H22>5IIHRaRL22=%HHHQRRL$BM 	@((111))  " B33BN<@ 4 B B B J//
D/III} @,,R]2A2->???#	r1   c                     d| _         d S )Nrf   )r   rU   s    r0   rM   zNCDFReader._reopen  s     r1   c                 |    || j         }	 |                     | j        dz             S # t          $ r	 t          d w xY wr3   )r   r8   r   r   rT   rk   s     r0   r*   zNCDFReader._read_next_timestep  sR    :B	$##D$7!$;<<< 	$ 	$ 	$t#	$s   ( ;c                     	 | j         j        d         d         }| j         j        d         d         }n# t          t          f$ r t          w xY w||z
  S )zGets dt based on the time difference between the first and second
        frame. If missing (i.e. an IndexError is triggered), raises an
        AttributeError which triggers the default 1 ps return of dt().
        r   r   r   )r   r   r   r   r   )r+   t1t0s      r0   _get_dtzNCDFReader._get_dt  s`    
	!'/2B'/2BBH% 	! 	! 	!  	!Bws	   03 Ac                 X    | j         "| j                                          d| _         dS dS )a^  Close trajectory; any further access will raise an :exc:`IOError`.

        .. Note:: The underlying :mod:`scipy.io.netcdf` module may open netcdf
                  files with :class:`~mmap.mmap` if ``mmap=True`` was
                  set. Hence *any* reference to an array *must* be removed
                  before the file can be closed.

        Nrm   rU   s    r0   rO   zNCDFReader.close  s3     <#L   DLLL $#r1   c                    |                     d| j                  }|                    d| j                   |                    d| j                   |                    d| j                   |                    d| j                   | j        D ]&}|                    d| | j        |                    't          ||fi |S )a  Returns a NCDFWriter for `filename` with the same parameters as this NCDF.

        All values can be changed through keyword arguments.

        Parameters
        ----------
        filename : str
            filename of the output NCDF trajectory
        n_atoms : int (optional)
            number of atoms
        remarks : str (optional)
            string that is stored in the title field
        convert_units : bool (optional)
            ``True``: units are converted to the AMBER base format
        velocities : bool (optional)
            Write velocities into the trajectory
        forces : bool (optional)
            Write forces into the trajectory
        scale_time : float (optional)
            Scale factor for time units
        scale_cell_lengths : float (optional)
            Scale factor for cell lengths
        scale_cell_angles : float (optional)
            Scale factor for cell angles
        scale_coordinates : float (optional)
            Scale factor for coordinates
        scale_velocities : float (optional)
            Scale factor for velocities
        scale_forces : float (optional)
            Scale factor for forces

        Returns
        -------
        :class:`NCDFWriter`
        r   r   r   r   r   scale_)	r\   r   
setdefaultr   r   r   r   r   
NCDFWriter)r+   r,   r-   r   keys        r0   WriterzNCDFReader.Writer  s    H **Y55)T\222/4+=>>>,(;<<<(DO444% 	G 	GCnsnnd.@.EFFFF(G66v666r1   )NNrb   )rn   ro   rp   rq   r&   
multiframer   rr   r   r   r	   r   staticmethodr   r   r   r8   rM   r*   r   rO   r   rt   ru   s   @r0   rw   rw   f  s8       C CJ d^FJG!&+- -E
 Ij j j j j jX . . \.   \
J J J& & &P! ! !$ $ $ $
 
 
     +7 +7 +7 +7 +7 +7 +7r1   rw   c                   h    e Zd ZdZddgZdZdZdddd	d
Z	 	 	 	 	 ddZddZ	d Z
d Zd Zd Zd ZdS )r   u  Writer for `AMBER NETCDF format`_ (version 1.0).

    AMBER binary trajectories are automatically recognised by the
    file extension ".ncdf" or ".nc".

    Velocities are written out if they are detected in the input
    :class:`Timestep`. The trajectories are always written with ångström
    for the lengths and picoseconds for the time (and hence Å/ps for
    velocities and kilocalorie/mole/Å for forces).

    Scale factor variables for time, velocities, cell lengths, cell angles,
    coordinates, velocities, or forces can be passed into the writer. If so,
    they will be written to the NetCDF file. In this case, the trajectory data
    will be written to the NetCDF file divided by the scale factor value. By
    default, scale factor variables are not written. The only exception is for
    velocities, where it is set to 20.455, replicating the default behaviour of
    AMBER.

    Unit cell information is written if available.

    .. _AMBER NETCDF format: http://ambermd.org/netcdf/nctraj.xhtml


    Parameters
    ----------
    filename : str
        name of output file
    n_atoms : int
        number of atoms in trajectory file
    convert_units : bool (optional)
        ``True``: units are converted to the AMBER base format; [``True``]
    velocities : bool (optional)
        Write velocities into the trajectory [``False``]
    forces : bool (optional)
        Write forces into the trajectory [``False``]
    scale_time : float (optional)
        Scale factor for time units [`None`]
    scale_cell_lengths : float (optional)
        Scale factor for cell lengths [``None``]
    scale_cell_angles : float (optional)
        Scale factor for cell angles [``None``]
    scale_coordinates : float (optional)
        Scale factor for coordinates [``None``]
    scale_velocities : float (optional)
        Scale factor for velocities [20.455]
    scale_forces : float (optional)
        Scale factor for forces [``None``]


    Note
    ----
    MDAnalysis uses :mod:`scipy.io.netcdf` to access AMBER files, which are in
    netcdf 3 format. Although :mod:`scipy.io.netcdf` is very fast at reading
    these files, it is *very* slow when writing, and it becomes slower the
    longer the files are. On the other hand, the netCDF4_ package (which
    requires the compiled netcdf library to be installed) is fast at writing
    but slow at reading. Therefore, we try to use :mod:`netCDF4` for writing if
    available but otherwise fall back to the slower :mod:`scipy.io.netcdf`.

    **AMBER users** might have a hard time getting netCDF4 to work with a
    conda-based installation (as discussed in `Issue #506`_) because of the way
    that AMBER itself handles netcdf: When the AMBER environment is loaded, the
    following can happen when trying to import netCDF4::

      >>> import netCDF4
      Traceback (most recent call last):
        File "<string>", line 1, in <module>
        File "/scratch2/miniconda/envs/py35/lib/python3.5/site-packages/netCDF4/__init__.py", line 3, in <module>
          from ._netCDF4 import *
      ImportError: /scratch2/miniconda/envs/py35/lib/python3.5/site-packages/netCDF4/_netCDF4.cpython-35m-x86_64-linux-gnu.so: undefined symbol: nc_inq_var_fletcher32

    The reason for this (figured out via :program:`ldd`) is that AMBER builds
    its own NetCDF library that it now inserts into :envvar:`LD_LIBRARY_PATH`
    *without the NetCDF4 API and HDF5 bindings*. Since the conda version of
    :mod:`netCDF4` was built against the full NetCDF package, the one
    :program:`ld` tries to link to at runtime (because AMBER requires
    :envvar:`LD_LIBRARY_PATH`) is missing some symbols. Removing AMBER from the
    environment fixes the import but is not really a convenient solution for
    users of AMBER.

    At the moment there is no obvious solution if one wants to use
    :mod:`netCDF4` and AMBER in the same shell session. If you need the fast
    writing capabilities of :mod:`netCDF4` then you need to unload your AMBER
    environment before importing MDAnalysis.


    .. _netCDF4: https://unidata.github.io/netcdf4-python/
    .. _`Issue #506`:
       https://github.com/MDAnalysis/mdanalysis/issues/506#issuecomment-225081416

    Raises
    ------
    FutureWarning
        When writing. The :class:`NCDFWriter` currently does not write any
        `scale_factor` values for the data variables. Whilst not in breach
        of the AMBER NetCDF standard, this behaviour differs from that of
        most AMBER writers, especially for velocities which usually have a
        `scale_factor` of 20.455. In MDAnalysis 2.0, the :class:`NCDFWriter`
        will enforce `scale_factor` writing to either match user inputs (either
        manually defined or via the :class:`NCDFReader`) or those as written by
        AmberTools's :program:`sander` under default operation.

    See Also
    --------
    :class:`NCDFReader`


    .. versionadded: 0.7.6
    .. versionchanged:: 0.10.0
       Added ability to write velocities and forces
    .. versionchanged:: 0.11.0
       kwarg `delta` renamed to `dt`, for uniformity with other Readers
    .. versionchanged:: 0.17.0
       Use fast :mod:`netCDF4` for writing but fall back to slow
       :mod:`scipy.io.netcdf` if :mod:`netCDF4` is not available.
    .. versionchanged:: 0.20.1
       Changes the `cell_angles` unit to the AMBER NetCDF convention standard
       of `degree` instead of the `degrees` written in previous version of
       MDAnalysis (Issue #2327).
    .. versionchanged:: 2.0.0
       ``dt``, ``start``, and ``step`` keywords were unused and are no longer
       set.
       Writing of ``scale_factor`` values has now been implemented. By default
       only velocities write a scale_factor of 20.455 (echoing the behaviour
       seen from AMBER).

    ry   rx   Trz   r   r   r{   r|   r}   NFc                    || _         |dk    rt          d          || _        || _        |pd| _        d| _        d | _        d | _        || _        || _	        |||	|
||d| _
        | j
                                        D ]:}|6t          |t          t          j        f          sd| d}t!          |          ;d| _        d S )Nr   z)NCDFWriter: no atoms in output trajectoryz;AMBER NetCDF format (MDAnalysis.coordinates.trj.NCDFWriter)Tr   zscale_factor r   )r,   r   r   r   r   _first_framer   r@   r   r   r   valuesr   r   r"   r   r   
curr_frame)r+   r,   r   r   r   r   r   
scale_timescale_cell_lengthsscale_cell_anglesscale_coordinatesscale_velocitiesscale_forcesr-   valuer   s                   r0   r   zNCDFWriter.__init__  s    
 !a<<HIII*_"_ (  # 200.&( ( '..00 	( 	(E!"55"+*>?? "????'''r1   c                    | j         s2t          t          j        d                    | j                            t          rt          j        | j        dd          }nXt          j	        
                    | j        ddd          }d}t                              |           t          j        |           t          |d	d
           t          |dt           j                   t          |dd           t          |dd           t          |dd           |                    dd           |                    d| j                   |                    dd           |                    dd           |                    dd           |                    dd           |                    ddd          }t          |dd           | j        d         r| j        d         |_        |                    dd d!          }t/          j        t3          d"                    |dd<   |                    d#dd$          }t          |dd%           | j        d#         r| j        d#         |_        || _        | j        r%|                    d&d'd(          }t          |dd           | j        d&         r| j        d&         |_        |                    dd d)          }t/          j        t3          d*                    |dd<   |                    d+d'd,          }	t          |	dd-           | j        d+         r| j        d+         |	_        |                    dd d.          }
t/          j        t3          d/          t3          d0          t3          d1          g          |
dd<   | j        rG|                    d2dd          }t          |dd3           | j        d2         r| j        d2         |_        | j        rG|                    d4dd          }t          |dd5           | j        d4         r| j        d4         |_        t          r|                    d           |                                 d| _         || _        dS )6a  Initialize netcdf AMBER 1.0 trajectory.

        The trajectory is opened when the first frame is written
        because that is the earliest time that we can detect if the
        output should contain periodicity information (i.e. the unit
        cell dimensions).

        Based on Joshua Adelman's `netcdf4storage.py`_ in `Issue 109`_ and uses
        Jason Swail's hack from `ParmEd/ParmEd#722`_ to switch between
        :mod:`scipy.io.netcdf` and :mod:`netCDF4`.

        .. _`Issue 109`:
           https://github.com/MDAnalysis/mdanalysis/issues/109
        .. _`netcdf4storage.py`:
           https://storage.googleapis.com/google-code-attachments/mdanalysis/issue-109/comment-2/netcdf4storage.py
        .. _`ParmEd/ParmEd#722`: https://github.com/ParmEd/ParmEd/pull/722

        z#Attempt to write to closed file {0}wNETCDF3_64BIT)r&   r   F)moder   r   zfCould not find netCDF4 module. Falling back to MUCH slower scipy.io.netcdf implementation for writing.r   z%MDAnalysis.coordinates.TRJ.NCDFWriterr   r   r   r   rz   application
MDAnalysisr7   Nr   r   r   cell_spatialcell_angularlabel   r   f4)r7   r   r   rr   r   c)r   xyzr   )r7   r   r   f8)r7   r   )r   abcr   )r7   r   r   )r   r   alphazbeta gammar   r   r   r   ) r   rT   errnoEIOr&   r,   netCDF4Datasetr   r   r   r   r   rK   rL   setattrr   __version__createDimensionr   createVariabler   r   r"   asarraylistr@   r   r   set_auto_maskandscalesyncr   )r+   r@   ncfilerP   coordsr   r   r   r   r   r   velocsr   s                r0   _init_netcdfzNCDFWriter._init_netcdf  s   &   	M	5<<T]KKM M M  
	 _T]C,;= = =FF X))$-/2A7< * > >FIDNN4   M$ 		#JKKK(**@AAAw///+U333|444 	w#	% 	% 	%v#|	- 	- 	-y!,,,~q111~q111w*** &&}d'CE E,,,m, 	D"&"4]"CF''	3FFZU,,
$$VT:>>g|,,,f% 	; $ 26 :D = 	!001JL LLL':666!.1 O,0,>~,N)!001CE EL je55LO //t0IK KKK(333!-0 M+/+=m+L(!001JL LL j$w--gI I *  LO  	G**<+GI IFFG%:;;;!,/ G&*&8&F#? 	C**8T+GI IFFG%@AAA!(+ C&*&8&B#  	0((///!r1   c                     |j         duS )a^  Test if timestep ``ts`` contains a periodic box.

        Parameters
        ----------
        ts : :class:`Timestep`
             :class:`Timestep` instance containing coordinates to
             be written to trajectory file

        Returns
        -------
        bool
            Return ``True`` if `ts` contains a valid simulation box
        N)rB   rk   s     r0   is_periodiczNCDFWriter.is_periodic  s     }D((r1   c                 X   	 |j         }n># t          $ r1 	 |j        j         }n # t          $ r d}t          |          dw xY wY nw xY w|j        | j        k    rt          d          | j        )|                     |                     |                     | 	                    |          S )a  Write information associated with ``ag`` at current frame into trajectory

        Parameters
        ----------
        ag : AtomGroup or Universe


        .. versionchanged:: 1.0.0
           Added ability to use either AtomGroup or Universe.
           Renamed from `write_next_timestep` to `_write_next_frame`.
        .. versionchanged:: 2.0.0
           Deprecated support for Timestep argument has now been removed.
           Use AtomGroup or Universe as an input instead.
        z-Input obj is neither an AtomGroup or UniverseNz>NCDFWriter: Timestep does not have the correct number of atoms)r@   )
r   r   
trajectoryr   r   rT   r   r  r  _write_next_timestep)r+   agr   r   s       r0   _write_next_framezNCDFWriter._write_next_frame)  s    		2BB 	2 	2 	22]%! 2 2 2H''T12 	2 :%%PR R R <t'7'7';';<<<((,,,s!   
 
A"A?AAc                     | j         |         }|t          |d          r|| j        j        |         | j        <   dS ||z  | j        j        |         | j        <   dS )zHelper function to set variables and scale them if necessary.

        Note
        ----
        If scale_factor is numerically close to 1.0, the variable data is not
        scaled.
        Nr   )r   r   r   r   r   )r+   varnamedatasfactors       r0   _set_frame_var_and_scalez#NCDFWriter._set_frame_var_and_scaleM  s`     $W-?ggq11??CDL"7+DO<<<?Cg~DL"7+DO<<<r1   c                    |j         }|j        }|j        }| j        rC|                     |d          }|                     |d          }|                     |          }|                     d|           |                     d|           | j        r<|                     d|dd                    |                     d|dd                    | j	        r;|j
        }| j        r|                     |d          }|                     d	|           | j        r;|j        }| j        r|                     |d          }|                     d
|           | j                                         | xj        dz  c_        dS )a  Write coordinates and unitcell information to NCDF file.

        Do not call this method directly; instead use
        :meth:`write` because some essential setup is done
        there before writing the first frame.

        Based on Joshua Adelman's `netcdf4storage.py`_ in `Issue 109`_.

        .. _`Issue 109`:
           https://github.com/MDAnalysis/mdanalysis/issues/109
        .. _`netcdf4storage.py`:
           https://storage.googleapis.com/google-code-attachments/mdanalysis/issue-109/comment-2/netcdf4storage.py


        .. versionchanged:: 2.0.0
           Can now write scale_factors, and scale variables accordingly.
        Fr   r   r   r   Nr   r   r   r   r   )rE   r   rB   r   convert_pos_to_nativeconvert_time_to_nativeconvert_dimensions_to_unitcellr  r@   r   r   convert_velocities_to_nativer   r   convert_forces_to_nativer   r  r   )r+   r   posr   r   r   r   s          r0   r  zNCDFWriter._write_next_timestep[  s   $ gw= 		? ,,S%,@@C..tU.CCD::2>>H 	%%mS999 	%%fd333 = 	G)).(2A2,GGG))-!""FFF  	DJ! /!>> ? / /
 )),
CCC ? 	<ZF! +66E 7 + + ))(F;;;1r1   c                 X    | j         "| j                                          d | _         d S d S rb   rm   rU   s    r0   rO   zNCDFWriter.close  s1    <#L   DLLL $#r1   )
NTFFNNNNNN)T)rn   ro   rp   rq   r&   r   r   rr   r   r  r  r  r  r  rO    r1   r0   r   r     s        ~ ~@ F^FJG!&+- -E
 GK<@<@:>"	" " " "Hp p p pd) ) ) "- "- "-HN N NB B BH         r1   r   c                       e Zd ZdZd Zd ZdS )r   a  NetCDF file object (read-only) that can be pickled.

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

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


    .. note::
        This class subclasses :class:`scipy.io.netcdf_file`, please
        see the `scipy netcdf API documentation`_ for more information on
        the parameters and how the class behaviour.


    Parameters
    ----------
    filename : str or file-like
        a filename given a text or byte string.
    mmap : None or bool, optional
        Whether to mmap `filename` when reading. True when `filename`
        is a file name, False when `filename` is a file-like object.
    version : {1, 2}, optional
        Sets the netcdf file version to read / write. 1 is classic, 2 is
        64-bit offset format. Default is 1 (but note AMBER ncdf *requires* 2).
    maskandscale : bool, optional
        Whether to automatically scale and mask data. Default is False.

    Example
    -------
    ::

        f = NCDFPicklable(NCDF)
        print(f.variables['coordinates'].data)
        f.close()

    can also be used as context manager::

        with NCDFPicklable(NCDF) as f:
            print(f.variables['coordinates'].data)

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


    .. versionadded:: 2.0.0


    .. _`scipy netcdf API documentation`: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.netcdf_file.html
    c                 6    | j         | j        | j        | j        fS rb   )r,   use_mmapr   r   rU   s    r0   __getstate__zNCDFPicklable.__getstate__  s     t}d.?!# 	#r1   c                 h    |                      |d         |d         |d         |d                    d S )Nr   r   r   r   )r   r   r   )r   )r+   argss     r0   __setstate__zNCDFPicklable.__setstate__  s@    d1gDGT!W#'7 	 	, 	, 	, 	, 	,r1   N)rn   ro   rp   rq   r(  r+  r$  r1   r0   r   r     s=        ; ;x# # #, , , , ,r1   r   ) rq   scipy.io.netcdfr   numpyr"   rK   r   loggingmathr   r   timestepr   r   r   libr   lib.utilr	   	getLoggerr   r  ImportErrorr   
ReaderBaser   rw   
WriterBaser   r   r   r   r$  r1   r0   <module>r7     s  .l lZ                                        + + + + + +		9	:	:WNNNN W W WG
NNUVVVVVW
I I I I I I I IXQ7 Q7 Q7 Q7 Q7 Q7 Q7 Q7hh  h  h  h  h  h  h  h VC, C, C, C, C,EH( C, C, C, C, C,s   
A A.-A.