
:>"^O                 @   s  d  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 d d l m Z d d	 l m Z d
 d   Z d d   Z d d   Z d  Z d! Z d" Z d d   Z d d   Z e d k rd d l m Z e d d  d S)#zABio.SeqIO support for accessing sequences in PDB and mmCIF files.    N)BiopythonParserWarning)StringIO)generic_protein)protein_letters_3to1)	as_handle)Seq)	SeqRecordc             #   s  d d l  m   f d d     | d } xqt | j j    D]Z\ } }  f d d   | j   D } | sv qB g  } d d   | D } xr t | d d   D]Z \ } }	 | | d	 |	 d	 k r | | d	 |	 k r | j | d	 |	 | | d	 f  q W| rg  }
 d } x | D] \ } } } | | k r| | d	 } |
 j   f d
 d   | | |  D  | } |
 j d |  qt	 j
 d t  |
 j   f d d   | | |  D  PqW|
 j   f d d   | | d  D  n   f d d   | D }
 d |  | f } t t d j |
  t  d | d | } | j | j d <| j | j d <t | d  | j d <t | d  | j d <| VqB Wd S)a^  Return SeqRecords from Structure objects.

    Base function for sequence parsers that read structures Bio.PDB parsers.

    Once a parser from Bio.PDB has been used to load a structure into a
    Bio.PDB.Structure.Structure object, there is no difference in how the
    sequence parser interprets the residue sequence. The functions in this
    module may be used by SeqIO modules wishing to parse sequences from lists
    of residues.

    Calling funtions must pass a Bio.PDB.Structure.Structure object.


    See Bio.SeqIO.PdbIO.PdbAtomIterator and Bio.SeqIO.PdbIO.CifAtomIterator for
    details.
    r   )seq1c                s     |  j  d t S)zzReturn a residue's type as a one-letter code.

        Non-standard residues (e.g. CSD, ANP) are returned as 'X'.
        
custom_map)resnamer   )Zresidue)r	    4/tmp/pip-build-ww9dw3qa/biopython/Bio/SeqIO/PdbIO.pyrestype*   s    zAtomIterator.<locals>.restypec                s:   g  |  ]0 }   | j    j   d  t d k r |  q S)r
   X)Zget_resnameupperr   ).0res)r	   r   r   
<listcomp>5   s   	z AtomIterator.<locals>.<listcomp>c             S   s   g  |  ] } | j  d   q S)   )id)r   rr   r   r   r   >   s   	 Nr   c             3   s   |  ] }   |  Vq d  S)Nr   )r   x)r   r   r   	<genexpr>I   s    zAtomIterator.<locals>.<genexpr>r   z*Ignoring out-of-order residues after a gapc             3   s   |  ] }   |  Vq d  S)Nr   )r   r   )r   r   r   r   S   s    c             3   s   |  ] }   |  Vq d  S)Nr   )r   r   )r   r   r   r   W   s    c                s   g  |  ] }   |   q Sr   r   )r   r   )r   r   r   r   Z   s   	 z%s:%s r   descriptionmodelchainstartendr   )Bio.SeqUtilsr	   sortedZ
child_dictitemsZget_unpacked_list	enumerateappendextendwarningswarnr   r   r   joinr   r   annotationsint)pdb_idstructr   chn_idr   residuesZgapsZrnumbersiZrnumZres_outZprev_idxZpregapZpostgapZgapsizeZ	record_idrecordr   )r   r	   r   AtomIterator   sJ    
"#,&**-'r1   c             #   s~  d d l  m   d } t j t  } t j t  } t |  d  4}  x|  D]} d } | d d  j   } | d k r | d }   f d	 d
   | d d  j   D } | | j |  qM | d k rM | d d  } | d } | d d  j   }	 | d d  j   }
 | d d  j   } | | j	 d | d |	 d |
 d | i  qM W| rit
 d   xt | j    D] \ } } t t d j |  t   } d | i | _ | | k ra| | d } d | d | f | _ | _ d | d | d | d f | _ xX | | D]@ } | j j d | d | d f d | d | d f g  qWn	 | | _ | Vq|WWd QRXd S)a  Return SeqRecord objects for each chain in a PDB file.

    The sequences are derived from the SEQRES lines in the
    PDB file header, not the atoms of the 3D structure.

    Specifically, these PDB records are handled: DBREF, SEQADV, SEQRES, MODRES

    See: http://www.wwpdb.org/documentation/format23/sect3.html

    This gets called internally via Bio.SeqIO for the SEQRES based interpretation
    of the PDB file format:

    >>> from Bio import SeqIO
    >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-seqres"):
    ...     print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...     print(record.dbxrefs)
    ...
    Record id 1A8O:A, chain A
    ['UNP:P12497', 'UNP:POL_HV1N5']

    Equivalently,

    >>> with open("PDB/1A8O.pdb") as handle:
    ...     for record in PdbSeqresIterator(handle):
    ...         print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...         print(record.dbxrefs)
    ...
    Record id 1A8O:A, chain A
    ['UNP:P12497', 'UNP:POL_HV1N5']

    Note the chain is recorded in the annotations dictionary, and any PDB DBREF
    lines are recorded in the database cross-references list.
    r   )r	   TrUF   ZSEQRES   c                s"   g  |  ] }   | d  t   q S)r
   )r   )r   r   )r	   r   r   r      s   	z%PdbSeqresIterator.<locals>.<listcomp>   NZDBREF             !   )   *   6   r+   databasedb_acc
db_id_codezEmpty file.r   r   z%s:%sz%s:%s %s)r    r	   collectionsdefaultdictlistr   stripsplitr%   r$   
ValueErrorr!   r"   r   r   r(   r   r)   r   namer   dbxrefs)handleemptychainsmetadatalineZrec_namer-   r.   r+   r>   r?   r@   r0   mmelemr   )r	   r   PdbSeqresIteratorm   sT    #	



	#	rP   c          
   c   s   d d l  m } t |  d  w }  |   j d |   } | j d } | s` t j d t  d } x/ t | |  D] } | j	 j
 | j  | Vqp WWd QRXd S)a  Return SeqRecord objects for each chain in a PDB file.

    The sequences are derived from the 3D structure (ATOM records), not the
    SEQRES lines in the PDB file header.

    Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM entries
    are converted to "X" in the sequence.

    In addition to information from the PDB header (which is the same for all
    records), the following chain specific information is placed in the
    annotation:

    record.annotations["residues"] = List of residue ID strings
    record.annotations["chain"] = Chain ID (typically A, B ,...)
    record.annotations["model"] = Model ID (typically zero)

    Where amino acids are missing from the structure, as indicated by residue
    numbering, the sequence is filled in with 'X' characters to match the size
    of the missing region, and  None is included as the corresponding entry in
    the list record.annotations["residues"].

    This function uses the Bio.PDB module to do most of the hard work. The
    annotation information could be improved but this extra parsing should be
    done in parse_pdb_header, not this module.

    This gets called internally via Bio.SeqIO for the atom based interpretation
    of the PDB file format:

    >>> from Bio import SeqIO
    >>> for record in SeqIO.parse("PDB/1A8O.pdb", "pdb-atom"):
    ...     print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...
    Record id 1A8O:A, chain A

    Equivalently,

    >>> with open("PDB/1A8O.pdb") as handle:
    ...     for record in PdbAtomIterator(handle):
    ...         print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...
    Record id 1A8O:A, chain A

    r   )	PDBParserr2   NZidcodez0'HEADER' line not found; can't determine PDB ID.z????)ZBio.PDBrQ   r   get_structureheaderr&   r'   r   r1   r)   update)rI   rQ   r,   r+   r0   r   r   r   PdbAtomIterator   s    /rU   _pdbx_poly_seq_scheme.asym_id_pdbx_poly_seq_scheme.mon_id_struct_ref.id_struct_ref.db_name_struct_ref.db_code_struct_ref.pdbx_db_accession_struct_ref_seq.ref_id _struct_ref_seq.pdbx_PDB_id_code_struct_ref_seq.pdbx_strand_idc             c   s  d d l  m } d d l m } t |  d  }  t j t  } t j t  } | |   } xS t t	 t
 D]C } | | k r g  | | <qk t | | t  sk | | g | | <qk WxH t | d | d  D]/ \ } } | | d t }	 | | j |	  q Wi  }
 x[ t | d | d	 | d
 | d  D]4 } | \ } } } } d | d | d | i |
 | <q)Wxk t | d | d | d  D]K } | \ } } } |
 | } | | j d | i  | | d j |  qWxt | j    D] \ } } t t d j |  t   } d | i | _ | | k r| | d } d | d | f | _ | _ d | d | d | d f | _ xX | | D]@ } | j j d | d | d f d | d | d f g  qWn	 | | _ | VqWWd QRXd S)a  Return SeqRecord objects for each chain in an mmCIF file.

    The sequences are derived from the _entity_poly_seq entries in the mmCIF
    file, not the atoms of the 3D structure.

    Specifically, these mmCIF records are handled: _pdbx_poly_seq_scheme and
    _struct_ref_seq. The _pdbx_poly_seq records contain sequence information,
    and the _struct_ref_seq records contain database cross-references.

    See:
    http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v40.dic/Categories/pdbx_poly_seq_scheme.html
    and
    http://mmcif.wwpdb.org/dictionaries/mmcif_pdbx_v50.dic/Categories/struct_ref_seq.html

    This gets called internally via Bio.SeqIO for the sequence-based
    interpretation of the mmCIF file format:

    >>> from Bio import SeqIO
    >>> for record in SeqIO.parse("PDB/1A8O.cif", "cif-seqres"):
    ...     print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...     print(record.dbxrefs)
    ...
    Record id 1A8O:A, chain A
    ['UNP:P12497', 'UNP:POL_HV1N5']

    Equivalently,

    >>> with open("PDB/1A8O.cif") as handle:
    ...     for record in CifSeqresIterator(handle):
    ...         print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...         print(record.dbxrefs)
    ...
    Record id 1A8O:A, chain A
    ['UNP:P12497', 'UNP:POL_HV1N5']

    Note the chain is recorded in the annotations dictionary, and any mmCIF
    _struct_ref_seq entries are recorded in the database cross-references list.
    r   )r	   )
MMCIF2Dictr2   z_pdbx_poly_seq_scheme.asym_idz_pdbx_poly_seq_scheme.mon_idr
   z_struct_ref.idz_struct_ref.db_namez_struct_ref.db_codez_struct_ref.pdbx_db_accessionr>   r@   r?   z_struct_ref_seq.ref_idz _struct_ref_seq.pdbx_PDB_id_codez_struct_ref_seq.pdbx_strand_idr+   r   r   r   z%s:%sz%s:%s %sNr   )r    r	   Bio.PDB.MMCIF2Dictr_   r   rA   rB   rC   PDBX_POLY_SEQ_SCHEME_FIELDSSTRUCT_REF_SEQ_FIELDSSTRUCT_REF_FIELDS
isinstancezipr   r$   rT   r!   r"   r   r   r(   r   r)   r   rG   r   rH   r%   )rI   r	   r_   rK   rL   recordsfieldZasym_idZmon_idZ	mon_id_1lZstruct_refsfieldsZref_idZdb_nameZdb_coder?   r+   Zchain_idZ
struct_refr-   r.   r0   rN   rO   r   r   r   CifSeqresIteratorF  sf    (
	#	ri   c          
   c   s  d d l  m } d d l m } t   } t |  d   }  t j |  |  Wd QRX| j   sj t	 d   | j
 d  | |  } d | k r | d } t | t  r | d } n t j d t  d	 } | j
 d  |   j | |  } x t | |  D] } | Vq Wd S)
a  Return SeqRecord objects for each chain in a PDB file.

    The sequences are derived from the 3D structure (ATOM records), not the
    SEQRES lines in the PDB file header.

    Unrecognised three letter amino acid codes (e.g. "CSD") from HETATM entries
    are converted to "X" in the sequence.

    In addition to information from the PDB header (which is the same for all
    records), the following chain specific information is placed in the
    annotation:

    record.annotations["residues"] = List of residue ID strings
    record.annotations["chain"] = Chain ID (typically A, B ,...)
    record.annotations["model"] = Model ID (typically zero)

    Where amino acids are missing from the structure, as indicated by residue
    numbering, the sequence is filled in with 'X' characters to match the size
    of the missing region, and  None is included as the corresponding entry in
    the list record.annotations["residues"].

    This function uses the Bio.PDB module to do most of the hard work. The
    annotation information could be improved but this extra parsing should be
    done in parse_pdb_header, not this module.

    This gets called internally via Bio.SeqIO for the atom based interpretation
    of the PDB file format:

    >>> from Bio import SeqIO
    >>> for record in SeqIO.parse("PDB/1A8O.cif", "cif-atom"):
    ...     print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...
    Record id 1A8O:A, chain A

    Equivalently,

    >>> with open("PDB/1A8O.cif") as handle:
    ...     for record in CifAtomIterator(handle):
    ...         print("Record id %s, chain %s" % (record.id, record.annotations["chain"]))
    ...
    Record id 1A8O:A, chain A

    r   )MMCIFParser)r_   r2   NzEmpty file.z	_entry.idz=Could not find the '_entry.id' field; can't determine PDB ID.z????)ZBio.PDB.MMCIFParserrj   r`   r_   r   r   shutilcopyfileobjgetvaluerF   seekrd   rC   r&   r'   r   rR   r1   )rI   rj   r_   bufferZ
mmcif_dictr+   r,   r0   r   r   r   CifAtomIterator  s*    /	
rp   __main__)run_doctestverbose)rV   rW   )rX   rY   rZ   r[   )r\   r]   r^   )__doc__rA   rk   r&   ZBior   Z	Bio._py3kr   ZBio.Alphabetr   ZBio.Data.SCOPDatar   ZBio.Filer   ZBio.Seqr   ZBio.SeqRecordr   r1   rP   rU   ra   rc   rb   ri   rp   __name__Z
Bio._utilsrr   r   r   r   r   <module>   s6   VG      xQ