
     i                     d   d Z ddlmZmZ ddlZddlZddlZddl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dlmZ dd	lmZ dd
lmZ  e	j        d          Z e
j        dd          Z G d dej                  Z G d dej                  Z G d de          Z  G d de          Z!dS )a^  PDB structure files in MDAnalysis --- :mod:`MDAnalysis.coordinates.PDB`
========================================================================

MDAnalysis reads coordinates from PDB files and additional optional
data such as B-factors. It is also possible to substitute a PDB file
instead of PSF file in order to define the list of atoms (but no
connectivity information will be available in this case).

PDB files contain both coordinate and atom information. It is also possible to
write trajectories as multi-frame (or multi-model) PDB files. This is not very
space efficient but is sometimes the lowest common denominator for exchanging
trajectories. Single frame and multi-frame PDB files are automatically
recognized; the only difference is thath the single-frame PDB is represented as
a trajectory with only one frame.

In order to write a selection to a PDB file one typically uses the
:meth:`MDAnalysis.core.groups.AtomGroup.write` method of the selection::

  calphas = universe.select_atoms("name CA")
  calphas.write("calpha_only.pdb")

This uses the coordinates from the current timestep of the trajectory.

In order to write a PDB trajectory one needs to first obtain a multi-frame
writer (keyword *multiframe* = ``True``) and then iterate through the
trajectory, while writing each frame::

  calphas = universe.select_atoms("name CA")
  with MDAnalysis.Writer("calpha_traj.pdb", multiframe=True) as W:
      for ts in u.trajectory:
          W.write(calphas)

It is important to *always close the trajectory* when done because only at this
step is the final END_ record written, which is required by the `PDB 3.3
standard`_. Using the writer as a context manager ensures that this always
happens.


Capabilities
------------

A pure-Python implementation for PDB files commonly encountered in MD
simulations comes under the names :class:`PDBReader` and :class:`PDBWriter`. It
only implements a subset of the `PDB 3.3 standard`_ and also allows some
typical enhancements such as 4-letter resids (introduced by CHARMM/NAMD).

The :class:`PDBReader` can read multi-frame PDB files and represents
them as a trajectory. The :class:`PDBWriter` can write single and
multi-frame PDB files as specified by the *multiframe* keyword. By default, it
writes single frames. On the other hand, the :class:`MultiPDBWriter` is set up
to write a PDB trajectory by default (equivalent to using *multiframe* =
``True``).


Examples for working with PDB files
-----------------------------------

A **single frame PDB** can be written with the
:meth:`~MDAnalysis.core.groups.AtomGroup.write` method of any
:class:`~MDAnalysis.core.groups.AtomGroup`::

   protein = u.select_atoms("protein")
   protein.write("protein.pdb")

Alternatively, get the single frame writer and supply the
:class:`~MDAnalysis.core.groups.AtomGroup`::

  protein = u.select_atoms("protein")
  with MDAnalysis.Writer("protein.pdb") as pdb:
      pdb.write(protein)

In order to write a **multi-frame PDB trajectory** from a universe *u* one can
do the following::

  with MDAnalysis.Writer("all.pdb", multiframe=True) as pdb:
      for ts in u.trajectory:
          pdb.write(u)

Similarly, writing only a protein::

  protein = u.select_atoms("protein")
  with MDAnalysis.Writer("protein.pdb", multiframe=True) as pdb:
      for ts in u.trajectory:
          pdb.write(protein)



Classes
-------

.. versionchanged:: 0.16.0
   PDB readers and writers based on :class:`Bio.PDB.PDBParser` were retired and
   removed.


.. autoclass:: PDBReader
   :members:

.. autoclass:: PDBWriter
   :members:

   .. automethod:: _check_pdb_coordinates
   .. automethod:: _write_pdb_bonds
   .. automethod:: _update_frame
   .. automethod:: _write_timestep

.. autoclass:: MultiPDBWriter
   :members:

.. autoclass:: ExtendedPDBReader
   :members:
   :inherited-members:


.. _`PDB 3.3 standard`:
    http://www.wwpdb.org/documentation/file-format-content/format33/v3.3.html

    )StringIOBytesION   )util)store_init_arguments   )base)Timestep)NoDataErrorzMDAnalysis.coordinates.PBDAtomzresname namec                   d     e Zd ZdZddgZdddZe fd            Zd Zd	 Z	dd
Z
d Zd Z xZS )	PDBReaderu  PDBReader that reads a `PDB-formatted`_ file, no frills.

    The following *PDB records* are parsed (see `PDB coordinate section`_ for
    details):

    - *CRYST1* for unitcell A,B,C, alpha,beta,gamma
    - *ATOM* or *HETATM* for serial,name,resName,chainID,resSeq,x,y,z,occupancy,tempFactor
    - *HEADER* (:attr:`header`), *TITLE* (:attr:`title`), *COMPND*
        (:attr:`compound`), *REMARK* (:attr:`remarks`)
    - all other lines are ignored


    Reads multi-`MODEL`_ PDB files as trajectories.  The `Timestep.data` dictionary
    holds the occupancy and tempfactor (bfactor) values for each atom for a given frame.
    These attributes are commonly appropriated to store other time varying properties
    and so they are exposed here. Note this does not update the `AtomGroup` attributes,
    as the topology does not change with trajectory iteration.

    .. _PDB-formatted:
       http://www.wwpdb.org/documentation/file-format-content/format33/v3.3.html
    .. _PDB coordinate section:
       http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html
    .. _MODEL:
       http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#MODEL

    =============  ============  ===========  =============================================
    COLUMNS        DATA  TYPE    FIELD        DEFINITION
    =============  ============  ===========  =============================================
    1 -  6         Record name   "CRYST1"
    7 - 15         Real(9.3)     a              a (Angstroms).
    16 - 24        Real(9.3)     b              b (Angstroms).
    25 - 33        Real(9.3)     c              c (Angstroms).
    34 - 40        Real(7.2)     alpha          alpha (degrees).
    41 - 47        Real(7.2)     beta           beta (degrees).
    48 - 54        Real(7.2)     gamma          gamma (degrees).

    1 -  6         Record name   "ATOM  "
    7 - 11         Integer       serial       Atom  serial number.
    13 - 16        Atom          name         Atom name.
    17             Character     altLoc       Alternate location indicator.
    18 - 21        Residue name  resName      Residue name.
    22             Character     chainID      Chain identifier.
    23 - 26        Integer       resSeq       Residue sequence number.
    27             AChar         iCode        Code for insertion of residues.
    31 - 38        Real(8.3)     x            Orthogonal coordinates for X in Angstroms.
    39 - 46        Real(8.3)     y            Orthogonal coordinates for Y in Angstroms.
    47 - 54        Real(8.3)     z            Orthogonal coordinates for Z in Angstroms.
    55 - 60        Real(6.2)     occupancy    Occupancy.
    61 - 66        Real(6.2)     tempFactor   Temperature  factor.
    67 - 72                                   (not used in the official PDB format)
    73 - 76        String        segID        (unofficial PDB format*)
    77 - 78        LString(2)    element      Element symbol, right-justified.
    79 - 80        LString(2)    charge       Charge  on the atom.
    =============  ============  ===========  =============================================

    Notes
    -----
    If a system does not have unit cell parameters (such as in electron
    microscopy structures), the PDB file format requires the CRYST1_ field to
    be provided with unitary values (cubic box with sides of 1 Å) and an
    appropriate REMARK. If unitary values are found within the CRYST1_ field,
    :code:`PDBReader` will not set unit cell dimensions (which will take the
    default value :code:`np.zeros(6)`, see Issue #2698)
    and it will warn the user.

    .. _CRYST1: http://www.wwpdb.org/documentation/file-format-content/format33/sect8.html#CRYST1

    *The columns 73-76 are not part of the official PDB format but are used by
    some programs to store/operate the segment ID. For instance, Chimera_ assigns
    it as the attribute `pdbSegment` to allow command-line specification.

    .. _Chimera:
        https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/tutorials/pdbintro.html#note6

    See Also
    --------
    :class:`PDBWriter`
    :class:`PDBReader`

    If you would like to force the use of chainID as the segID when parsing PDB,
    please use the keyword argument `force_chainids_to_segids=True`
    (:class:`MDAnalysis.topology.PDBParser.PDBParser`).
    This will prioritize the chain ID to the segment ID.


    .. versionchanged:: 0.11.0
       * Frames now 0-based instead of 1-based
       * New :attr:`title` (list with all TITLE lines).
    .. versionchanged:: 0.19.1
       Can now read PDB files with DOS line endings
    .. versionchanged:: 0.20.0
       Strip trajectory header of trailing spaces and newlines
    .. versionchanged:: 1.0.0
       Raise user warning for CRYST1_ record with unitary values
       (cubic box with sides of 1 Å) and do not set cell dimensions.
    .. versionchanged:: 2.5.0
       Tempfactors (aka bfactors) are now read into the ts.data dictionary each
       frame.  Occupancies are also read into this dictionary.
    PDBENTNAngstromtimelengthc                     t          t          |           j        |fi | 	 |d         | _        nh# t          $ r[ ddlm} |                    | j                  5 }|                                }ddd           n# 1 swxY w Y   |j        | _        Y nw xY w|	                    dd          | _
        d}g }g }g }	 | j        | j        fi | j        | _        g }
g }t          |t          j                  rWt          |j        t$                    r=t'          |j                                                                                  |_        t          j        |d          x}| _        d}|r|                                }|dd	         d
k    r)|
                    |                                           ns|dd	         dk    r9|                    |                                t7          |          z
             n,|dd         dk    r/|dd                                                                         }n|dd	         dk    rB|                    |dd                                                                                    n|dd         dk    rB|                    |dd                                                                                    nO|dd         dk    rA|	                    |dd                                                                                    ||                                }|| _        || _        || _         |	| _!        |
s|
                    d           t7          |          t7          |
          k    rd tE          |
|          D             }n|
}|| _#        |dd         |gz   | _$        t7          |          | _%        | &                    d           dS )a  Read coordinates from *filename*.

        *filename* can be a gzipped or bzip2ed compressed PDB file.

        If the pdb file contains multiple MODEL records then it is
        read as a trajectory where the MODEL numbers correspond to
        frame numbers.
        n_atomsr   )	PDBParserNmodel_offset rbmagical   s   MODELs   CRYST   s   HEADER
   B   s   TITLE   P   s   COMPND   s   REMARKc                 4    g | ]\  }}t          ||          S  )min).0abs      d/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/MDAnalysis/coordinates/PDB.py
<listcomp>z&PDBReader.__init__.<locals>.<listcomp>c  s$    AAATQs1ayyAAA    r   )'superr   __init__r   KeyErrorMDAnalysis.topologyr   filenameparsepopr   	_Timestep
_ts_kwargsts
isinstancer   NamedStreamstreamr   r   getvalueencodeanyopen_pdbfilereadlineappendtelllenstripdecodeheadertitlecompoundremarkszip_start_offsets_stop_offsetsn_frames_read_frame)selfr0   kwargsr   ptoprC   rD   rE   rF   modelscrystspdbfilelineendoffsets	__class__s                   r)   r-   zPDBReader.__init__  s%    	(i';;F;;;		'!),DLL 	' 	' 	' 655555$$T]33  qggii                             ;DLLL	' #JJ~q99 $.AAAA  h 011 	KjOX7
 7
 	K &ho&>&>&@&@&G&G&I&IJJHO"&,x">">>$- 	: ##%%DBQBx8##gllnn----bqbX%%gllnns4yy89999bqbY&& be**,,3355bqbX%%T!B$Z--//66889999bqbY&&QrT
 0 0 2 2 9 9 ; ;<<<<bqbY&&tABBx~~//6688999)  	:, llnn
  	 MM!v;;#f++%%AAS-@-@AAAGGG%$QRR[C50Gs3   2 *BA=1B=B	BB	BBc                 Z    |                     d| j        dk               t          |fi |S )zReturns a PDBWriter for *filename*.

        Parameters
        ----------
        filename : str
            filename of the output PDB file

        Returns
        -------
        :class:`PDBWriter`

        
multiframer   )
setdefaultrJ   	PDBWriter)rL   r0   rM   s      r)   WriterzPDBReader.Writern  s7     	,(9:::,,V,,,r+   c                     |                                   t          j        | j        d          | _        d| j        _        d S )Nr   )closer   r;   r0   r<   r5   framerL   s    r)   _reopenzPDBReader._reopen~  s3     	

T]D99r+   c                 r    || j         }nt          d          | j        dz   }|                     |          S )Nz%PDBReader cannot assign to a timestepr   )r5   NotImplementedErrorr_   rK   )rL   r5   r_   s      r)   _read_next_timestepzPDBReader._read_next_timestep  sB    :BB &&MNNN 
Q&&&r+   c                 F   	 | j         |         }| j        |         }n# t          $ r	 t          dw xY wd}t	          j        | j                  }t	          j        | j                  }d}| j        	                    |           | j        
                    ||z
                                            }g }	|                                D ]}
|
dd         dv rv|	                    |
dd         |
dd         |
dd	         g           	 |
d	d
         ||<   n# t          $ r Y nw xY w	 |
d
d         ||<   d}n# t          $ r Y nw xY w|dz  }|
dd         dk    r	 t	          j        |
dd         |
dd         |
dd         |
dd         |
dd         |
dd	         gt          j                  }t	          j        |t	          j        g d                    r"t%          j        d           d| j        _        5|| j        _        C# t          $ r7 t%          j        d                    |
                     d| j        _        Y w xY w|| j        k    r/t          d                    | j        ||| j                            |	| j        _        | j        rR|                     | j        j                   | j        j        '|                     | j        j        dd                    || j        _        || j        j        d<   |r|| j        j        d<   | j        S )u  
        Read frame from PDB file.

        Notes
        -----
        When the CRYST1_ record has unitary values (cubic box with sides of
        1 Å), cell dimensions are considered fictitious. An user warning is
        raised and cell dimensions are set to
        :code:`np.zeros(6)` (see Issue #2698)


        .. versionchanged:: 1.0.0
           Raise user warning for CRYST1_ record with unitary valuse
           (cubic box with sides of 1 Å) and do not set cell dimensions.
        .. versionchanged:: 2.5.0
           When seen, `ts.data` is populated with tempfactor information at
           each frame read. If any atom has a non-parsable (i.e. non float)
           value in the tempfactor field, the entry is left as `1.0`.
        Nr   Fr   )zATOM  HETATM   &   .   6   <   r   Tr   CRYST1      !   (   /   )dtype      ?rt   rt        V@ru   ru   z]1 A^3 CRYST1 record, this is usually a placeholder. Unit cell dimensions will be set to None.z@Failed to read CRYST1 record, possibly invalid PDB file, got:
{}zInconsistency in file '{}': The number of atoms ({}) in trajectory frame {} differs from the number of atoms ({}) in the corresponding topology.
Trajectories with varying numbers of atoms are currently not supported.   	occupancy
tempfactor)rH   rI   
IndexErrorIOErrornpzerosr   onesr<   seekreadrB   
splitlinesr>   
ValueErrorarrayfloat32allclosewarningswarnr5   
dimensionsformatr0   	positionsconvert_unitsconvert_pos_from_native_posr_   data)rL   r_   startstopposrw   rx   saw_tempfactorchunktmp_bufrS   	cell_dimss               r)   rK   zPDBReader._read_frame  s   (	$'.E%e,DD 	$ 	$ 	$t#	$ HT\**	WT\**
 	5!!!""4%<007799$$&& 1	7 1	7DBQBx///RUT"R%[$r"u+FGGG%)"R%[IcNN!   D*&*2b5kJsO &*NN "   D qbqbX%%7 " 2J BK BK BK BK BK !j
! 
! 
!I& {!28,M,M,M#N#N  
7 !I  
 .2**-6**% " . . .M!6$<<  
 *.DG&&&. &F $,
 6$-eT\BB   $ 	E((6667%-,,TW-?-CDDD$-[! 	4)3DGL&ws?    0D
D#"D#'D77
EEAH=IIc                 8    | j                                          d S N)r<   r^   r`   s    r)   r^   zPDBReader.close  s    r+   r   )__name__
__module____qualname____doc__r   unitsr   r-   r[   ra   rd   rK   r^   __classcell__)rV   s   @r)   r   r      s        b bH U^FZ00E\ \ \ \ \|- - -   
' 
' 
' 
'o o ob      r+   r   c                      e Zd ZdZdddddddd	d
ddddZddgZdddZdddZdZdZ	dZ
dZdZ edd           edd           ed d          fZ ed!d!           ed"d"           ed#d#           ed$d$           ed%d&           ed'd(           ed'd&           ed)d*           ed)d+           ed,d-           ed,d.           ed/d/          fZ	 	 	 	 	 	 	 	 dNd5Zd6 Zd7 Zd8 Zd9 Zd: Zd; Zd< Zd= ZdOd>Zej        d?             Zed@ej        dAej        fdB            Z dPdCZ!dD Z"dE Z#dF Z$dG Z%dQdIZ&dJ Z'dK Z(dL Z)dM Z*dS )RrZ   u  PDB writer that implements a subset of the `PDB 3.3 standard`_ .

    PDB format as used by NAMD/CHARMM: 4-letter resnames and segID are allowed,
    altLoc is written.

    The :class:`PDBWriter` can be used to either dump a coordinate
    set to a PDB file (operating as a "single frame writer", selected with the
    constructor keyword *multiframe* = ``False``, the default) or by writing a
    PDB "movie" (multi frame mode, *multiframe* = ``True``), consisting of
    multiple models (using the MODEL_ and ENDMDL_ records).

    .. _`PDB 3.3 standard`:
       http://www.wwpdb.org/documentation/file-format-content/format33/v3.3.html
    .. _ATOM: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ATOM
    .. _COMPND: http://www.wwpdb.org/documentation/file-format-content/format33/sect2.html#COMPND
    .. _CONECT: http://www.wwpdb.org/documentation/file-format-content/format33/sect10.html#CONECT
    .. _END: http://www.wwpdb.org/documentation/file-format-content/format33/sect11.html#END
    .. _ENDMDL: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ENDMDL
    .. _HEADER: http://www.wwpdb.org/documentation/file-format-content/format33/sect2.html#HEADER
    .. _HETATM: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#HETATM
    .. _MODEL: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#MODEL
    .. _NUMMDL: http://www.wwpdb.org/documentation/file-format-content/format33/sect2.html#NUMMDL
    .. _REMARKS: http://www.wwpdb.org/documentation/file-format-content/format33/remarks.html
    .. _TITLE: http://www.wwpdb.org/documentation/file-format-content/format33/sect2.html#TITLE

    Note
    ----
    Writing bonds currently only works when writing a whole :class:`Universe`
    and if bond information is available in the topology.  (For selections
    smaller than the whole :class:`Universe`, the atom numbering in the CONECT_
    records would not match the numbering of the atoms in the new PDB file and
    therefore a :exc:`NotImplementedError` is raised.)

    The maximum frame number that can be stored in a PDB file is 9999 and it
    will wrap around (see :meth:`MODEL` for further details).

    The CRYST1_ record specifies the unit cell. This record is set to
    unitary values (cubic box with sides of 1 Å) if unit cell dimensions
    are not set (:code:`None` or :code:`np.zeros(6)`,
    see Issue #2698).

    When the :attr:`record_types` attribute is present (e.g. Universe object
    was created by loading a PDB file), ATOM_ and HETATM_ record type
    keywords are written out accordingly. Otherwise, the ATOM_ record type
    is the default output.

    The CONECT_ record is written out, if required, when the output stream
    is closed.

    See Also
    --------
    This class is identical to :class:`MultiPDBWriter` with the one
    exception that it defaults to writing single-frame PDB files as if
    `multiframe` = ``False`` was selected.


    .. versionchanged:: 0.7.5
       Initial support for multi-frame PDB files.

    .. versionchanged:: 0.7.6
       The *multiframe* keyword was added to select the writing mode. The
       writing of bond information (CONECT_ records) is now disabled by default
       but can be enabled with the *bonds* keyword.

    .. versionchanged:: 0.11.0
       Frames now 0-based instead of 1-based

    .. versionchanged:: 0.14.0
       PDB doesn't save charge information

    .. versionchanged:: 0.20.0
       Strip trajectory header of trailing spaces and newlines

    .. versionchanged:: 1.0.0
       ChainID now comes from the last character of segid, as stated in the documentation.
       An indexing issue meant it previously used the first charater (Issue #2224)

    .. versionchanged:: 2.0.0
       Add the `redindex` argument. Setting this keyword to ``True``
       (the default) preserves the behavior in earlier versions of MDAnalysis.
       The PDB writer checks for a valid chainID entry instead of using the
       last character of segid. Should a chainID not be present, or not
       conform to the PDB standard, the default value of  'X' is used.

    .. versionchanged:: 2.3.0
       Do not write unusable conect records when ag index
       is larger than 100000.
    zATOM  {serial:5d} {name:<4s}{altLoc:<1s}{resName:<4s}{chainID:1s}{resSeq:4d}{iCode:1s}   {pos[0]:8.3f}{pos[1]:8.3f}{pos[2]:8.3f}{occupancy:6.2f}{tempFactor:6.2f}      {segID:<4s}{element:>2s}{charge:2s}
zHETATM{serial:5d} {name:<4s}{altLoc:<1s}{resName:<4s}{chainID:1s}{resSeq:4d}{iCode:1s}   {pos[0]:8.3f}{pos[1]:8.3f}{pos[2]:8.3f}{occupancy:6.2f}{tempFactor:6.2f}      {segID:<4s}{element:>2s}{charge:2s}
zREMARK     {0}
zCOMPND    {0}
zHEADER    {0}
zTITLE     {0}
zMODEL     {0:>4d}
zNUMMDL    {0:5d}
zENDMDL
zEND
zrCRYST1{box[0]:9.3f}{box[1]:9.3f}{box[2]:9.3f}{ang[0]:7.2f}{ang[1]:7.2f}{ang[2]:7.2f} {spacegroup:<11s}{zvalue:4d}
z
CONECT{0}
)ATOMrf   REMARKCOMPNDHEADERTITLEMODELNUMMDLENDMDLENDrl   CONECTr   r   Nr   r   g"?g-@)r%   maxr   F)FEASZNMGMNCOBRCUTAMOALBESEPTEUNIIRRHAUGDRU)CMHEMCMBOMMCHGBBE7PMB)0QECPTDCEEAAIMNOCZOMYOMZUN91N12T83933MYBMUCLMCP6DB8DIFEFZLURRDCUCLXMMHLTIRELCPPCIVGHOECCA1PLLPDOEXC14C15F9FOANBLMr   BZGr   VNLCO1CO2PF5FE1FE2UNLconectr   r   Created by PDBWriterTc
                    || _         || _        || j        n|| _        || _        |	| _        |dk     rt          d          |x| _        | _        || _	        || _
        t          j        | j         d          | _        d| _        d| _        dS )a8  Create a new PDBWriter

        Parameters
        ----------
        filename: str
           name of output file
        start: int (optional)
           starting timestep (the first frame will have MODEL number `start` + 1
           because the PDB standard prescribes MODEL numbers starting at 1)
        step: int (optional)
           skip between subsequent timesteps
        remarks: str (optional)
           comments to annotate pdb file (added to the *TITLE* record); note that
           any remarks from the trajectory that serves as input are
           written to REMARK records with lines longer than :attr:`remark_max_length` (66
           characters) being wrapped.
        convert_units: bool (optional)
           units are converted to the MDAnalysis base format; [``True``]
        bonds : {"conect", "all", None} (optional)
           If set to "conect", then only write those bonds that were already
           defined in an input PDB file as PDB CONECT_ record. If set to "all",
           write all bonds (including guessed ones) to the file. ``None`` does
           not write any bonds. The default is "conect".
        multiframe: bool (optional)
           ``False``: write a single frame to the file; ``True``: create a
           multi frame PDB file in which frames are written as MODEL_ ... ENDMDL_
           records. If ``None``, then the class default is chosen.    [``None``]
        reindex: bool (optional)
            If ``True`` (default), the atom serial is set to be consecutive
            numbers starting at 1. Else, use the atom id.

        Nr   z 'Start' must be a positive valuewtF)r0   r   rX   _multiframebonds_reindexr   r   frames_writtensteprF   r   r;   rR   has_ENDfirst_frame_done)
rL   r0   r   r   r   r   rF   r   rX   reindexs
             r)   r-   zPDBWriter.__init__  s    d !*)1DOOz 	 
199?@@@+00
T(	|DM488 %r+   c                    t          | d          rj| j        c| j        s)|                                  |                                  nt
                              d           | j                                         d| _        dS )z
        Close PDB file and write CONECT and END record


        .. versionchanged:: 2.0.0
           CONECT_ record written just before END_ record
        rR   NzHEND record has already been written before the final closing of the file)hasattrrR   r   _write_pdb_bondsr   loggerwarningr^   r`   s    r)   r^   zPDBWriter.close  s     4## 		!(@< %%'''



<   L   r+   c                     | j         r;|                     d                    | j        | j        | j                             d S |                     d                    | j        | j                             d S )Nz/MDANALYSIS FRAMES FROM {0:d}, STEP {1:d}: {2!s}zMDANALYSIS FRAME {0:d}: {1!s})r   r   r   r   r   rF   r`   s    r)   _write_pdb_titlezPDBWriter._write_pdb_title.  s     		JJ6$*di>>    
 JJ6$*dl33    r+   c                    | j         du rdS d| _         | j        j        }|                     |j                   |                                  |                     |j                   	 g }t          j        |j        j	                  D ]/}|
                    t          j        || j                             0 | j        |  n# t          $ r Y nw xY w|j        j        j        |                     t'          j        g d                     |                     d           |                     d           |                     d           |                     d           |                     d           |                     d	           t+          j        d
           dS |                     |                     |j        j                             dS )u
  
        Write PDB header.

        The HEADER_ record is set to :code: `trajectory.header`.
        The TITLE_ record explicitly mentions MDAnalysis and contains
        information about trajectory frame(s).
        The COMPND_ record is set to :code:`trajectory.compound`.
        The REMARKS_ records are set to :code:`u.trajectory.remarks`
        The CRYST1_ record specifies the unit cell. This record is set to
        unitary values (cubic box with sides of 1 Å) if unit cell dimensions
        are not set.

        .. versionchanged: 1.0.0
           Fix writing of PDB file without unit cell dimensions (Issue #2679).
           If cell dimensions are not found, unitary values (cubic box with
           sides of 1 Å) are used (PDB standard for CRYST1_).
        TNrs   z6285 UNITARY VALUES FOR THE UNIT CELL AUTOMATICALLY SETz9285 BY MDANALYSIS PDBWRITER BECAUSE UNIT CELL INFORMATIONz285 WAS MISSING.z.285 PROTEIN DATA BANK CONVENTIONS REQUIRE THATz0285 CRYST1 RECORD IS INCLUDED, BUT THE VALUES ONz 285 THIS RECORD ARE MEANINGLESS.zDUnit cell dimensions not found. CRYST1 record set to unitary values.)r   objuniverser   
trajectoryr  r   r   
asiterablerF   extendtextwrapwrapremark_max_lengthr   AttributeErrorr5   r   rl   r{   r   r   r   convert_dimensions_to_unitcell)rL   urF   rS   s       r)   _write_pdb_headerzPDBWriter._write_pdb_header:  s   &  D((F $HAL!!!AL!!!		 G(<== L Lx}T43IJJKKKKDK!!! 	 	 	D	 <?%- KK!B!B!BCCDDD
 KKH   KKK   KK*+++KKHIIIKKJKKKKK:;;;M7    
 KK;;ALOLLMMMMMs   (AC 
CCc                 H   | j         j        }|j        }|                     | j        |          rdS | j        dk    r+|                     dd           |                                  n|                                  	 t          j	        | j
                   nU# t          $ r!}|j        t          j        k    rn Y d}~n/d}~wt          $ r t          | j
        t                     rn Y nw xY wt#          d                    | j        d         | j        d                             )	a*  Check if the coordinate values fall within the range allowed for PDB files.

        Deletes the output file if this is the first frame or if frames have
        already been written (in multi-frame mode) adds a REMARK instead of the
        coordinates and closes the file.

        Raises
        ------
        ValueError
            if the coordinates fail the check.

        .. versionchanged: 1.0.0
            Check if :attr:`filename` is `StringIO` when attempting to remove
            a PDB file with invalid coordinates (Issue #2512)
        Tr   z"Incomplete multi-frame trajectory.zJCoordinates for the current frame cannot be represented in the PDB format.NzfPDB files must have coordinate values between {0:.3f} and {1:.3f} Angstroem: file writing was aborted.r%   r   )r  atomsr   has_valid_coordinatespdb_coor_limitsr   r   r^   osremover0   OSErrorerrnoENOENT	TypeErrorr6   r   r   r   )rL   r  coorerrs       r)   _check_pdb_coordinatesz PDBWriter._check_pdb_coordinates|  sO      %%d&:DAA 	4
 ""KK41  
 JJLLLLJJLLL	$-((((   9,, DDDD    dmX66  D v$U+T-A%-H 
 
 	
s   <B 
C( B<<)C('C(c                   	
 | j         dS t          | d          r!| j        rt          | j        j        d          sdS t	          t          j        d | j        j        D                        }| j        rPd	d t          | j        j        j
        d          D             
t          j        | j        j        j
                  }n@d		d
 | j        j        j        D             
t          j        | j        j        j                  }| j         dk    r	fd|D             }n)| j         dk    r	fd|D             }nt          d          t          j        t"                    |D ]s\  }}|
v r|
v s
|         dk    s
|         dk    rt%          j        d            dS |                             |           |                             |           t
fd|D             }|D ]}|                     |           dS )zWrites out all the bond recordsNr  r   c              3   $   K   | ]}|j         V  d S r   )r   )r&   r'   s     r)   	<genexpr>z-PDBWriter._write_pdb_bonds.<locals>.<genexpr>  s$      'H'HA'H'H'H'H'H'Hr+   indexc                     i | ]\  }}||	S r$   r$   )r&   ir#  s      r)   
<dictcomp>z.PDBWriter._write_pdb_bonds.<locals>.<dictcomp>  s.       Au q  r+   r   )r   idc                     i | ]}||S r$   r$   )r&   id_s     r)   r&  z.PDBWriter._write_pdb_bonds.<locals>.<dictcomp>  s    >>>CsC>>>r+   r   c              3   ~   K   | ]7}|j         	t          |d                    t          |d                   fV  8dS r   r   N)
is_guessedgetattrr&   bondindex_attributes     r)   r"  z-PDBWriter._write_pdb_bonds.<locals>.<genexpr>  se        
 DG_55DG_55     r+   allc              3   p   K   | ]0}t          |d                    t          |d                   fV  1dS r+  )r-  r.  s     r)   r"  z-PDBWriter._write_pdb_bonds.<locals>.<genexpr>  s]        
  DG_55DG_55     r+   z.bonds has to be either None, 'conect' or 'all'i zBAtom with index >=100000 cannot write bonds to PDB CONECT records.c              3   v   K   | ]3}|v |         gt          fd |         D                       z   V  4dS )c                      g | ]
}|         S r$   r$   )r&   atmappings     r)   r*   z8PDBWriter._write_pdb_bonds.<locals>.<genexpr>.<listcomp>  s    "@"@"@272;"@"@"@r+   N)sorted)r&   r'   conr6  s     r)   r"  z-PDBWriter._write_pdb_bonds.<locals>.<genexpr>  sa       
 
Cxx QZL6"@"@"@"@Q"@"@"@AAAxxx
 
r+   )r   r   r  r  set	itertoolschainr  r   	enumerateindicesr{   sortidsr   collectionsdefaultdictlistr   r   r>   r   )rL   bondsetr  r   a1a2r   cr8  r0  r6  s           @@@r)   r  zPDBWriter._write_pdb_bonds  s   :F e$$	8	 48,g66	
 Fio'H'H'H'H'HIJJ= 
	0%O  )$(.*@ J J J  G GDHN233EE"O>>48>+=>>>GGDHN.//E:!!   
 $  EE Z5     
 $  EE MNNN%d++ 
	 
	FB'MMbGmmr{f$$v(=(=3   GNN2GNN2
 
 
 
 

 
 
  	 	AKKNNNN	 	r+   c                     t          |t                    rt          d          t          |j                  dk    rt          d          || _        |j        j        j	        | _	        dS )a  Method to initialize important attributes in writer from a AtomGroup or Universe *obj*.

        Attributes initialized/updated:

        * :attr:`PDBWriter.obj` (the entity that provides topology information *and*
          coordinates, either a :class:`~MDAnalysis.core.groups.AtomGroup` or a whole
          :class:`~MDAnalysis.core.universe.Universe`)
        * :attr:`PDBWriter.trajectory` (the underlying trajectory
          :class:`~MDAnalysis.coordinates.base.Reader`)
        * :attr:`PDBWriter.timestep` (the underlying trajectory
          :class:`~MDAnalysis.coordinates.timestep.Timestep`)

        Before calling :meth:`_write_next_frame` this method **must** be
        called at least once to enable extracting topology information from the
        current frame.
        zPDBWriter cannot write Timestep objects directly, since they lack topology information (atom names and types) required in PDB filesr   zCannot write empty AtomGroupN)
r6   r
   r  r@   r  ry   r  r  r	  r5   rL   r  s     r)   _update_framezPDBWriter._update_frame  sm    " c8$$ 	>  
 sy>>Q;<<< ,),r+   c                     |                      |           |                                  |                     | j        | j                   dS )a6  Write object *obj* at current trajectory frame to file.

        *obj* can be a selection (i.e. a
        :class:`~MDAnalysis.core.groups.AtomGroup`) or a whole
        :class:`~MDAnalysis.core.universe.Universe`.

        The last letter of the :attr:`~MDAnalysis.core.groups.Atom.segid` is
        used as the PDB chainID (but see :meth:`~PDBWriter.ATOM` for
        details).

        Parameters
        ----------
        obj
            The :class:`~MDAnalysis.core.groups.AtomGroup` or
            :class:`~MDAnalysis.core.universe.Universe` to write.
        rX   N)rI  r  _write_next_framer5   r   rH  s     r)   writezPDBWriter.write  sP    $ 	3    	tw43CDDDDDr+   c                 v   |                      |           |                                  | j        | j        }}|j        j        }|s|j        dk    r|j        }t          |t          |          |          D ]&}||          | 
                    | j        d           '|                                  ||          dS )a  Write all timesteps associated with *obj* to the PDB file.

        *obj* can be a :class:`~MDAnalysis.core.groups.AtomGroup`
        or a :class:`~MDAnalysis.core.universe.Universe`.

        The method writes the frames from the one specified as *start* until
        the end, using a step of *step* (*start* and *step* are set in the
        constructor). Thus, if *u* is a Universe then ::

           u.trajectory[-2]
           pdb = PDBWriter("out.pdb", u.atoms.n_atoms)
           pdb.write_all_timesteps(u)

        will write a PDB trajectory containing the last 2 frames and ::

           pdb = PDBWriter("out.pdb", u.atoms.n_atoms, start=12, step=2)
           pdb.write_all_timesteps(u)

        will be writing frames 12, 14, 16, ...


        .. versionchanged:: 0.11.0
           Frames now 0-based instead of 1-based

        .. versionchanged:: 2.0.0
           CONECT_ record moved to :meth:`close`
        r   TrK  N)rI  r  r   r   r  r	  rJ   r_   ranger@   rL  r5   r^   )rL   r  r   r   trajframenumbers         r)   write_all_timestepszPDBWriter.write_all_timesteps2  s    : 	3   j$)t|&
  	**JE D		488 	= 	=K""47t"<<<< 	

 	Ur+   c                     |)	 | j         }n # t          $ r d}t          |          dw xY w|                                   | j        |fi | dS )a  write a new timestep to the PDB file

        :Keywords:
          *ts*
             :class:`timestep.Timestep` object containing coordinates to be written to trajectory file;
             if ``None`` then :attr:`PDBWriter.ts`` is tried.
          *multiframe*
             ``False``: write a single frame (default); ``True`` behave as a trajectory writer

        .. Note::

           Before using this method with another :class:`timestep.Timestep` in the *ts*
           argument, :meth:`PDBWriter._update_frame` *must* be called
           with the :class:`~MDAnalysis.core.groups.AtomGroup.Universe` as
           its argument so that topology information can be gathered.


        .. versionchanged:: 1.0.0
           Renamed from `write_next_timestep` to `_write_next_frame`.
        Nz9PBDWriter: no coordinate data to write to trajectory file)r5   r  r   r  _write_timestep)rL   r5   rM   errmsgs       r)   rL  zPDBWriter._write_next_framee  s    * :4W! 4 4 4&  "&))t34 	##%%%R**6*****s    )c                    |dk    rdS t          |          dk    r
|dd         S t          |          dk    rd                    |          S ||k    s\|dd         | j        v sK|dk    sE|| j        v r|dd         dk    s.|| j        v r|dd         d	k    st          ||          | j        v r,t          ||          | j        vrd
                    |          S d                    |          S )a  Deduce how the atom name should be aligned.

        Atom name format can be deduced from the atom type, yet atom type is
        not always available. This function uses the atom name and residue name
        to deduce how the atom name should be formatted. The rules in use got
        inferred from an analysis of the PDB. See gist at
        <https://gist.github.com/jbarnoud/37a524330f29b5b7b096> for more
        details.
        r      Nr   z {}  r   UNKHGCLz{:<4}z {:<3})r@   r   ions
special_hg
special_clPairinclude_pairsexclude_pairs)rL   atomnameresnames      r)   _deduce_PDB_atom_namezPDBWriter._deduce_PDB_atom_name  s    r>>2x==ABQB<]]a>>(+++x|ty((5  4?**x|t/C/C4?**x|t/C/CGX&&$*<<<7H%%T-???>>(+++x(((r+   chargesreturnc                    t          j        | j        t           j                  st	          d          |                     t                    }d||dk    <   t          j        | dk               d         D ]:}| |         dk     rd}t	          |          t          | |                    d||<   ;t          j        | dk              d         D ]-}| |         dk    rd}t	          |          | |          d	||<   .|S )
a  Format formal charges to match PDB requirements.

        Formal charge entry is set to empty if charge is 0, otherwise the
        charge is set to a two character ```<charge value><charge sign>``
        entry, e.g. ``1+`` or ``2-``.

        This method also verifies that formal charges can adhere to the PDB
        format (i.e. charge cannot be > 9 or < -9).

        Parameters
        ----------
        charges: np.ndarray
            NumPy array of integers representing the formal charges of
            the atoms being written.

        Returns
        -------
        np.ndarray
            NumPy array of dtype object with strings representing the
            formal charges of the atoms being written.
        z,formal charges array should be of `int` typer   r   iz3formal charge < -9 is not supported by PDB standard-	   z2formal charge > 9 is not supported by PDB standard+)	r{   
issubdtyperr   integerr   astypeobjectwhereabs)rd  
outchargesr%  rU  s       r)   _format_PDB_chargeszPDBWriter._format_PDB_charges  s   . }W]BJ77 	MKLLL^^F++
&(
:?#'A+&&q) 	2 	2AqzBN ((("71:111JqMM'A+&&q) 	- 	-AqzA~~M (((&qz,,,JqMMr+   c                 "     j         j        j        } j        r                     |d          }|r                      j        dz               fd} |dd          } |dd          } |d	d          } |d
d          } |dd          }	 |dd          }
 |dd          } |dd          } |dd          } |dd          } |dd          }                      |dd                    }d } ||	d          }	 j        s&	 j	        }nA# t          $ r t          d          w xY wt          j        t                              dz   }t          t                              D ]o}i }t!          j        ||         d          |d<                        ||         ||                   |d<   ||         dd         |d<   ||         dd          |d!<   t!          j        |
|         d           |d"<   ||         dd         |d#<   ||         |d$<   ||         |d%<   ||         |d&<   ||         dd          |d'<   |	|         |d(<   ||         dd)                                         |d*<   ||         |d+<   	  j                              j        ||                  j        d.i |           G# t0          $ r d,||          d-}t3          |          dw xY w|r                                   xj        dz  c_        dS )/a   Write a new timestep *ts* to file

        Does unit conversion if necessary.

        By setting *multiframe* = ``True``, MODEL_ ... ENDMDL_ records are
        written to represent trajectory frames in a multi-model PDB file. (At
        the moment we do *not* write the NUMMDL_ record.)

        The *multiframe* = ``False`` keyword signals that the
        :class:`PDBWriter` is in single frame mode and no MODEL_
        records are written.

        .. versionchanged:: 0.7.6
           The *multiframe* keyword was added, which completely determines if
           MODEL_ records are written. (Previously, this was decided based on
           the underlying trajectory and only if ``len(traj) > 1`` would
           MODEL records have been written.)

        .. versionchanged:: 1.0.0
           ChainID now comes from the last character of segid, as stated in
           the documentation. An indexing issue meant it previously used the
           first charater (Issue #2224)

        .. versionchanged:: 2.0.0
           When only :attr:`record_types` attribute is present, instead of
           using ATOM_ for both ATOM_ and HETATM_, HETATM_ record
           types are properly written out (Issue #1753).
           Writing now only uses the contents of the elements attribute
           instead of guessing by default. If the elements are missing,
           empty records are written out (Issue #2423).
           Atoms are now checked for a valid chainID instead of being
           overwritten by the last letter of the `segid` (Issue #3144).

        F)inplacer   c                     	 t          |           S # t          $ r[ j        dk    r(t          j        d                    | |                     t          j        |gt                    z            cY S w xY w)zTry and pull info off atoms, else fake it

            attrname - the field to pull of AtomGroup (plural!)
            default - default value in case attrname not found
            r   z?Found no information for attr: '{}' Using default value of '{}')	r-  r  r   r   r   r   r{   r   r@   )attrnamedefaultr  rL   s     r)   get_attrz+PDBWriter._write_timestep.<locals>.get_attr  s    	8uh///! 8 8 8&!++M!6(G44  
 x	CJJ 6777778s    A"A87A8altLocs resnamesrX  icodessegidschainIDsr   residsoccupanciesrt   tempfactorsg        namesXelementsrecord_typesr   formalchargesr   c                    d}d}d}t          |           D ]I\  }}|dk    rd}|| |<   t          |          dk    rd}|| |<   .|                                sd}|| |<   J|r't          j        d                    |                     |r't          j        d                    |                     |r't          j        d                    |                     | S )zValidate each atom's chainID

            chainids - np array of chainIDs
            default - default value in case chainID is considered invalid
            Fr   Tr   zNFound chainIDs with invalid length. Corresponding atoms will use value of '{}'zVFound chainIDs using unnaccepted character. Corresponding atoms will use value of '{}'zBFound missing chainIDs. Corresponding atoms will use value of '{}')r<  r@   isalnumr   r   r   )chainidsrv  invalid_length_idsinvalid_char_idsmissing_idsr%  chainids          r)   validate_chainidsz4PDBWriter._write_timestep.<locals>.validate_chainids  s    "'$K'11 	* 	*
7b=="&K")HQKK\\A%%)-&")HQKK ** *'+$")HQK! vg  
   vg  
  vg  
 Or+   zUThe "id" topology attribute is not set. Either set the attribute or use reindex=True.r   serialnameNaltLocrW  resNameresSeqiCoder   rw   
tempFactorsegIDchainIDr   elementchargezFound z? for the record type, but only allowed types are ATOM or HETATMr$   )r  r  r   r   convert_pos_to_nativer   r   rq  r   r?  r  r   r{   aranger@   rO  r   ltruncate_intrc  upperrR   rM  fmtr   r.   r   r   )rL   r5   rX   r   rw  altlocsrz  r{  r|  r  r~  r  r  	atomnamesr  r  formal_chargesr  atom_idsr%  valsrU  r  s   `                     @r)   rT  zPDBWriter._write_timestep  s   F o 	A,,S%,@@C 	0JJt*Q.///	8 	8 	8 	8 	8 	8" (9c**8J..(C(((C((8J++(A&&h}c22h}c22HWc**	8J,,x7711((?A2N2NOO'	 '	 '	R %$Xs33 } 		1 9!   !D   yU,,q0Hs5zz"" 	3 	3AD!/Q DN  55!hqk DL %QZ^DN&qk"1"oDO!/q	1==DN"1IbqbMDMa&DK +AD!,QD"1IbqbMDM&qkDO&qk"1"o3355DO+A.DN3""#C48LO#<#C#K#Kd#K#KLLLL 3 3 3=\!_ = = =  !((d23  	KKMMMq s   D D56J??'K&c                     t          |d          sdS |j                                        }| j                            | j        d                             |                     dS )zWrite HEADER_ record.

        .. versionchanged:: 0.20.0
            Strip `trajectory.header` since it can be modified by the user and should be
            sanitized (Issue #2324)
        rC   Nr   )r   rC   rA   rR   rM  r  r   )rL   r	  rC   s      r)   r   zPDBWriter.HEADERp  s`     z8,, 	F"((**48H-44V<<=====r+   c                     d                     |          }| j                            | j        d                             |                     dS )zWrite TITLE_ record.ry  r   NjoinrR   rM  r  r   )rL   rD   rS   s      r)   r   zPDBWriter.TITLE|  sB    xx48G,33D99:::::r+   c                     |D ]:}| j                             | j        d                             |                     ;dS )zWrite generic REMARKS_ record (without number).

        Each string provided in *remarks* is written as a separate REMARKS_
        record.

        r   NrR   rM  r  r   )rL   rF   remarks      r)   r   zPDBWriter.REMARK  sO      	B 	BFLtx188@@AAAA	B 	Br+   c                     t          |d          sd S |j        }|D ]:}| j                            | j        d                             |                     ;d S )NrE   r   )r   rE   rR   rM  r  r   )rL   r	  rE   rF  s       r)   r   zPDBWriter.COMPND  sh    z:.. 	F& 	= 	=ALtx188;;<<<<	= 	=r+   P 1c                     | j                             | j        d                             |dd         |dd         ||                     dS )zWrite CRYST1_ record.rl   Nrv   )boxang
spacegroupzvaluer  )rL   r   r  r  s       r)   rl   zPDBWriter.CRYST1  sa    HX%%rrNqrrN%	 &  	
 	
 	
 	
 	
r+   c           	          | j                             | j        d                             t	          t          |          dd                                        dS )aW  Write the MODEL_ record.

        .. note::

           The maximum MODEL number is limited to 9999 in the PDB
           standard (i.e., 4 digits). If frame numbers are larger than
           9999, they will wrap around, i.e., 9998, 9999, 0, 1, 2, ...

        .. versionchanged:: 0.19.0
           Maximum model number is enforced.

        r   N)rR   rM  r  r   intstr)rL   modelnumbers     r)   r   zPDBWriter.MODEL  sY     	HW$$S[)9)9"##)>%?%?@@	
 	
 	
 	
 	
r+   c                 l    | j         s%| j                            | j        d                    d| _         dS )a%  Write END_ record.

        Only a single END record is written. Calling END multiple times has no
        effect. Because :meth:`~PDBWriter.close` also calls this
        method right before closing the file it is recommended to *not* call
        :meth:`~PDBWriter.END` explicitly.

        r   TN)r   rR   rM  r  r`   s    r)   r   zPDBWriter.END  s5     | 	0Ltx///r+   c                 P    | j                             | j        d                    dS )zWrite the ENDMDL_ record.r   N)rR   rM  r  r`   s    r)   r   zPDBWriter.ENDMDL  s%    48H-.....r+   c                     d |D             }d                     |          }| j                            | j        d                             |                     dS )zWrite CONECT_ record.c                 8    g | ]}d                      |          S )z{0:5d})r   )r&   entrys     r)   r*   z$PDBWriter.CONECT.<locals>.<listcomp>  s$    ===U(//%((===r+   r   r   Nr  )rL   r   s     r)   r   zPDBWriter.CONECT  sU    ==f===48H-44V<<=====r+   )r   Nr   r   r   TNTr   )F)r  r   )+r   r   r   r   r  r   r   r  r  rX   r[  r\  r]  r^  r_  r`  r-   r^   r  r  r  r  rI  rM  rR  rL  	functoolscacherc  staticmethodr{   ndarrayrq  rT  r   r   r   r   rl   r   r   r   r   r$   r+   r)   rZ   rZ     s]       W WvKK
 %##"&&-  5 C8 U^FZ00E'	::O JD4 CJJ@ T%''eT):):DD<N<NOM 	UEUEUEUEUDUDUDUEUEUEUEUEM$ &D& D& D& D&L  (
 
 
@N @N @ND8
 8
 8
tA A AF- - ->E E E41 1 1f+ + + +B _) ) _)6 &RZ &BJ & & & \&Pc! c! c! c!J
> 
> 
>; ; ;
B B B= = =	
 	
 	
 	

 
 
"  / / /> > > > >r+   rZ   c                       e Zd ZdZdZdS )ExtendedPDBReadera.  PDBReader that reads a PDB-formatted file with five-digit residue numbers.

    This reader does not conform to the `PDB 3.3 standard`_ because it allows
    five-digit residue numbers that may take up columns 23 to 27 (inclusive)
    instead of being confined to 23-26 (with column 27 being reserved for the
    insertion code in the PDB standard). PDB files in this format are written
    by popular programs such as VMD_.

    See Also
    --------
    :class:`PDBReader`


    .. _VMD: http://www.ks.uiuc.edu/Research/vmd/

    .. versionadded:: 0.8
    XPDBN)r   r   r   r   r   r$   r+   r)   r  r    s         $ FFFr+   r  c                   "    e Zd ZdZddgZdZdZdS )MultiPDBWriteraY  PDB writer that implements a subset of the `PDB 3.3 standard`_ .

    PDB format as used by NAMD/CHARMM: 4-letter resnames and segID, altLoc
    is written.

    By default, :class:`MultiPDBWriter` writes a PDB "movie" (multi frame mode,
    *multiframe* = ``True``), consisting of multiple models (using the MODEL_
    and ENDMDL_ records).


    .. _MODEL: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#MODEL
    .. _ENDMDL: http://www.wwpdb.org/documentation/file-format-content/format33/sect9.html#ENDMDL
    .. _CONECT: http://www.wwpdb.org/documentation/file-format-content/format33/sect10.html#CONECT


    See Also
    --------
    This class is identical to :class:`PDBWriter` with the one
    exception that it defaults to writing multi-frame PDB files instead of
    single frames.


    .. versionadded:: 0.7.6

    r   r   TFN)r   r   r   r   r   rX   singleframer$   r+   r)   r  r    s-         4 U^FJKKKr+   r  )"r   ior   r   r  r  r:  r  r   loggingr@  numpyr{   r  libr   lib.utilr   r   r	   timestepr
   
exceptionsr   	getLoggerr  
namedtupler^  
ReaderBaser   
WriterBaserZ   r  r  r$   r+   r)   <module>r     s  2u ul !               				                           + + + + + +             $ $ $ $ $ $ 
	7	8	8 {fn55\ \ \ \ \ \ \ \~
~> ~> ~> ~> ~> ~> ~> ~>B    	   ,    Y     r+   