
:>"^/8                 @   s&  d  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 m Z d	 d
   Z d d   Z e d d d  Z e d d  Z Gd d   d e  Z Gd d   d e  Z d d   Z d d   Z e d k r"d d l m Z e d d  d S)zBio.SeqIO support for the "fasta" (aka FastA or Pearson) file format.

You are expected to use this module via the Bio.SeqIO functions.
    )print_function)	as_handle)single_letter_alphabet)Seq)	SeqRecord)SequentialSequenceWriter)_clean_get_seq_stringc             c   s  x[ |  D]O } | d d k r7 | d d  j    } Pq t | d t  r t d   q Wd Sg  } x| |  D]t } | d d k r | d j |  j d d  j d d  f Vg  } | d d  j    } qk | j | j     qk W| d j |  j d d  j d d  f Vd S)	a~  Iterate over Fasta records as string tuples.

    For each record a tuple of two strings is returned, the FASTA title
    line (without the leading '>' character), and the sequence (with any
    whitespace removed). The title line is not divided up into an
    identifier (the first word) and comment or description.

    >>> with open("Fasta/dups.fasta") as handle:
    ...     for values in SimpleFastaParser(handle):
    ...         print(values)
    ...
    ('alpha', 'ACGTA')
    ('beta', 'CGTC')
    ('gamma', 'CCGCC')
    ('alpha (again - this is a duplicate entry to test the indexing code)', 'ACGTA')
    ('delta', 'CGCGC')

    r   >   Nz,Is this handle in binary mode not text mode?  )rstrip
isinstanceint
ValueErrorjoinreplaceappend)handlelinetitlelines r   6/tmp/pip-build-ww9dw3qa/biopython/Bio/SeqIO/FastaIO.pySimpleFastaParser   s     ,r   c             c   s  d
 } x t  |   D] \ } } | d d k rm | d d k rT t d j |    | d d  j   } q | d d k r t d j | |    | | j   f Vq W| d k r nD | d d k r t d j |    n | d d k s t d	   d S)a  Iterate over no-wrapping Fasta records as string tuples.

    Functionally the same as SimpleFastaParser but with a strict
    interpretation of the FASTA format as exactly two lines per
    record, the greater-than-sign identifier with description,
    and the sequence with no line wrapping.

    Any line wrapping will raise an exception, as will excess blank
    lines (other than the special case of a zero-length sequence
    as the second line of a record).

    Examples
    --------
    This file uses two lines per FASTA record:

    >>> with open("Fasta/aster_no_wrap.pro") as handle:
    ...     for title, seq in FastaTwoLineParser(handle):
    ...         print("%s = %s..." % (title, seq[:3]))
    ...
    gi|3298468|dbj|BAA31520.1| SAMIPF = GGH...

    This equivalent file uses line wrapping:

    >>> with open("Fasta/aster.pro") as handle:
    ...     for title, seq in FastaTwoLineParser(handle):
    ...         print("%s = %s..." % (title, seq[:3]))
    ...
    Traceback (most recent call last):
       ...
    ValueError: Expected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: 'MTFGLVYTVYATAIDPKKGSLGTIAPIAIGFIVGANI'

    r      r   r
   zlExpected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: '{}'Nz{Two '>' FASTA lines in a row. Missing sequence line if this is strict two-line-per-record FASTA format. Have '>{}' and '{}'zmMissing sequence line at end of file if this is strict two-line-per-record FASTA format. Have title line '{}'z+line[0] == '>' ; this should be impossible!r   )	enumerater   formatr   stripAssertionError)r   idxr   r   r   r   r   FastaTwoLineParserK   s(    !r$   Nc       	      c   s  t  |  d   }  | rs x t |   D]G \ } } | |  \ } } } t t | |  d | d | d | Vq% Wn x t |   D] \ } } y | j d d  d } Wn1 t k
 r | s t t |    d } Yn Xt t | |  d | d | d | Vq WWd QRXd S)	a  Iterate over Fasta records as SeqRecord objects.

    Arguments:
     - handle - input file
     - alphabet - optional alphabet
     - title2ids - A function that, when given the title of the FASTA
       file (without the beginning >), will return the id, name and
       description (in that order) for the record as a tuple of strings.
       If this is not given, then the entire title line will be used
       as the description, and the first word as the id and name.

    By default this will act like calling Bio.SeqIO.parse(handle, "fasta")
    with no custom handling of the title lines:

    >>> with open("Fasta/dups.fasta") as handle:
    ...     for record in FastaIterator(handle):
    ...         print(record.id)
    ...
    alpha
    beta
    gamma
    alpha
    delta

    However, you can supply a title2ids function to alter this:

    >>> def take_upper(title):
    ...     return title.split(None, 1)[0].upper(), "", title
    >>> with open("Fasta/dups.fasta") as handle:
    ...     for record in FastaIterator(handle, title2ids=take_upper):
    ...         print(record.id)
    ...
    ALPHA
    BETA
    GAMMA
    ALPHA
    DELTA

    rUidnamedescriptionNr   r   r   )r   r   r   r   split
IndexErrorr"   repr)	r   alphabetZ	title2idsr   sequencer&   r'   descr
first_wordr   r   r   FastaIterator   s"    (*r0   c             c   s   t  |  d   }  x t |   D] \ } } y | j d d  d } Wn1 t k
 rx | sn t t |    d } Yn Xt t | |  d | d | d | Vq WWd QRXd S)	at  Iterate over two-line Fasta records (as SeqRecord objects).

    Arguments:
     - handle - input file
     - alphabet - optional alphabet

    This uses a strict interpretation of the FASTA as requiring
    exactly two lines per record (no line wrapping).

    Only the default title to ID/name/description parsing offered
    by the relaxed FASTA parser is offered.
    r%   Nr   r   r   r&   r'   r(   )r   r$   r)   r*   r"   r+   r   r   )r   r,   r   r-   r/   r   r   r   FastaTwoLineIterator   s    r1   c               @   s4   e  Z d  Z d Z d d d d  Z d d   Z d S)FastaWriterzClass to write Fasta format files (OBSOLETE).

    Please use the ``as_fasta`` function instead, or the top level
    ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
    <   Nc             C   sG   t  j |  |  d |  _ | r1 | d k  r1 t  | |  _ | |  _ d S)a'  Create a Fasta writer (OBSOLETE).

        Arguments:
         - handle - Handle to an output file, e.g. as returned
           by open(filename, "w")
         - wrap -   Optional line length used to wrap sequence lines.
           Defaults to wrapping the sequence at 60 characters
           Use zero (or None) for no wrapping, giving a single
           long line for the sequence.
         - record2title - Optional function to return the text to be
           used for the title line of each record.  By default
           a combination of the record.id and record.description
           is used.  If the record.description starts with the
           record.id, then just the record.description is used.

        You can either use::

            handle = open(filename, "w")
            writer = FastaWriter(handle)
            writer.write_file(myRecords)
            handle.close()

        Or, follow the sequential file writer system, for example::

            handle = open(filename, "w")
            writer = FastaWriter(handle)
            writer.write_header() # does nothing for Fasta files
            ...
            Multiple writer.write_record() and/or writer.write_records() calls
            ...
            writer.write_footer() # does nothing for Fasta files
            handle.close()

        Nr   )r   __init__wrapr   record2title)selfr   r5   r6   r   r   r   r4      s    #		zFastaWriter.__init__c             C   s  |  j  s t  |  j s t  d |  _ |  j rL |  j |  j |   } nn |  j | j  } |  j | j  } | r | j d d  d | k r | } n | r d | | f } n | } d | k s t  d | k s t  |  j	 j
 d |  |  j |  } d | k st  d | k s%t  |  j r|x_ t d t |  |  j  D]+ } |  j	 j
 | | | |  j  d  qJWn |  j	 j
 | d  d S)	z(Write a single Fasta record to the file.TNr   r   z%s %s
r   z>%s
)Z_header_writtenr"   Z_footer_writtenZ_record_writtenr6   cleanr&   r(   r)   r   writer	   r5   rangelen)r7   recordr   r&   r(   datair   r   r   write_record  s,    		"		",zFastaWriter.write_record)__name__
__module____qualname____doc__r4   r@   r   r   r   r   r2      s   +r2   c                   s+   e  Z d  Z d Z d   f d d  Z   S)FastaTwoLineWriterzClass to write 2-line per record Fasta format files (OBSOLETE).

    This means we write the sequence information  without line
    wrapping, and will always write a blank line for an empty
    sequence.
    Nc                s&   t  t |   j | d d d | d S)aO  Create a 2-line per record Fasta writer (OBSOLETE).

        Arguments:
         - handle - Handle to an output file, e.g. as returned
           by open(filename, "w")
         - record2title - Optional function to return the text to be
           used for the title line of each record.  By default
           a combination of the record.id and record.description
           is used.  If the record.description starts with the
           record.id, then just the record.description is used.

        You can either use::

            handle = open(filename, "w")
            writer = FastaWriter(handle)
            writer.write_file(myRecords)
            handle.close()

        Or, follow the sequential file writer system, for example::

            handle = open(filename, "w")
            writer = FastaWriter(handle)
            writer.write_header() # does nothing for Fasta files
            ...
            Multiple writer.write_record() and/or writer.write_records() calls
            ...
            writer.write_footer() # does nothing for Fasta files
            handle.close()

        r5   Nr6   )superrE   r4   )r7   r   r6   )	__class__r   r   r4   C  s    zFastaTwoLineWriter.__init__)rA   rB   rC   rD   r4   r   r   )rG   r   rE   ;  s   rE   c             C   s  t  |  j  } t  |  j  } | rI | j d d  d | k rI | } n | rb d | | f } n | } d | k sz t  d | k s t  d | g } t |   } d | k s t  d | k s t  x? t d t |  d  D]% } | j | | | d  d  q Wd	 j	 |  S)
zTurn a SeqRecord into a FASTA formated string.

    This is used internally by the SeqRecord's .format("fasta")
    method and by the SeqIO.write(..., ..., "fasta") function.
    Nr   r   z%s %sr8   r   z>%s
r3   r   )
r   r&   r(   r)   r"   r	   r;   r<   r   r   )r=   r&   r(   r   r   r>   r?   r   r   r   as_fastag  s     "	#rH   c             C   s   t  |  j  } t  |  j  } | rI | j d d  d | k rI | } n | rb d | | f } n | } d | k sz t  d | k s t  t |   } d | k s t  d | k s t  d | | f S)zTurn a SeqRecord into a two-line FASTA formated string.

    This is used internally by the SeqRecord's .format("fasta-2line")
    method and by the SeqIO.write(..., ..., "fasta-2line") function.
    Nr   r   z%s %sr8   r   z>%s
%s
)r   r&   r(   r)   r"   r	   )r=   r&   r(   r   r>   r   r   r   as_fasta_2line  s    "	rI   __main__)run_doctestverbose)rD   
__future__r   ZBio.Filer   ZBio.Alphabetr   ZBio.Seqr   ZBio.SeqRecordr   ZBio.SeqIO.Interfacesr   r   r	   r   r$   r0   r1   r2   rE   rH   rI   rA   Z
Bio._utilsrK   r   r   r   r   <module>   s$   0??U,