B
    b:                 @   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
 Z
dd ZG dd deZG dd deZG dd de	ZG dd deZdd Zdd Zedkrd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.
    )Seq)	SeqRecord   )_clean)_get_seq_string)SequenceIterator)SequenceWriterc             c   s   x.| D ]"}|d dkr|dd   }P qW dS g }x\| D ]T}|d dkr|d|ddddfV  g }|dd   }q:||   q:W |d|ddddfV  dS )a  Iterate over Fasta records as string tuples.

    Arguments:
     - handle - input stream opened in text mode

    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   >r   N  )rstripjoinreplaceappend)handlelinetitlelines r   0lib/python3.7/site-packages/Bio/SeqIO/FastaIO.pySimpleFastaParser   s    

 r   c             c   s   d}x~t | D ]r\}}|d dkrP|d dkr>td| d|dd  }q|d dkrrtd	| d
| d|| fV  qW |dkrn2|d dkrtd| dn|d dkstddS )a  Iterate over no-wrapping Fasta records as string tuples.

    Arguments:
     - handle - input stream opened in text mode

    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	   ziExpected FASTA record starting with '>' character. Perhaps this file is using FASTA line wrapping? Got: ''r   NzoTwo '>' FASTA lines in a row. Missing sequence line if this is strict two-line-per-record FASTA format. Have '>z' and 'zjMissing 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!)	enumerate
ValueErrorr   stripAssertionError)r   idxr   r   r   r   r   FastaTwoLineParserG   s"    $r    c                   s2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
FastaIteratorzParser for Fasta files.Nc                s,   |dk	rt d|| _t j|ddd dS )aN  Iterate over Fasta records as SeqRecord objects.

        Arguments:
         - source - input stream opened in text mode, or a path to a file
         - alphabet - optional alphabet, not used. Leave as None.
         - 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

        Nz,The alphabet argument is no longer supportedtZFasta)modefmt)r   	title2idssuper__init__)selfsourceZalphabetr%   )	__class__r   r   r'      s    (zFastaIterator.__init__c             C   s   |  |}|S )z9Start parsing the file, and return a SeqRecord generator.)iterate)r(   r   recordsr   r   r   parse   s    
zFastaIterator.parsec       	   	   c   s   | j }|rFxt|D ],\}}||\}}}tt||||dV  qW njxht|D ]\\}}y|ddd }W n( tk
r   |rtt|d}Y nX tt||||dV  qPW dS )z.Parse the file and generate SeqRecord objects.)idnamedescriptionNr   r   r
   )r%   r   r   r   split
IndexErrorr   repr)	r(   r   r%   r   sequencer.   r/   Zdescr
first_wordr   r   r   r+      s    
zFastaIterator.iterate)NN)__name__
__module____qualname____doc__r'   r-   r+   __classcell__r   r   )r*   r   r!      s   -r!   c                   s0   e Zd ZdZ fddZdd Zdd Z  ZS )FastaTwoLineIteratorz9Parser for Fasta files with exactly two lines per record.c                s   t  j|ddd dS )a  Iterate over two-line Fasta records (as SeqRecord objects).

        Arguments:
         - source - input stream opened in text mode, or a path to a file

        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"   ZFASTA)r#   r$   N)r&   r'   )r(   r)   )r*   r   r   r'      s    zFastaTwoLineIterator.__init__c             C   s   |  |}|S )z9Start parsing the file, and return a SeqRecord generator.)r+   )r(   r   r,   r   r   r   r-      s    
zFastaTwoLineIterator.parsec          	   c   sn   xht |D ]\\}}y|ddd }W n( tk
rN   |rFtt|d}Y nX tt||||dV  q
W dS )z.Parse the file and generate SeqRecord objects.Nr   r   r
   )r.   r/   r0   )r    r1   r2   r   r3   r   r   )r(   r   r   r4   r5   r   r   r   r+      s    
zFastaTwoLineIterator.iterate)r6   r7   r8   r9   r'   r-   r+   r:   r   r   )r*   r   r;      s   r;   c                   s*   e Zd ZdZd fdd	Zdd Z  Z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                s,   t  | |r|dk rt|| _|| _dS )a  Create a Fasta writer (OBSOLETE).

        Arguments:
         - target - Output stream opened in text mode, or a path to a file.
         - 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()

        r   N)r&   r'   r   wraprecord2title)r(   targetr>   r?   )r*   r   r   r'      s    "zFastaWriter.__init__c             C   s  | j r| |  |}nL| |j}| |j}|rN|ddd |krN|}n|r`d||f }n|}d|ksptd|ks|t| jd|  t|}d|kstd|kst| j	rxJt
dt|| j	D ]"}| j|||| j	  d  qW n| j|d  dS )z(Write a single Fasta record to the file.Nr   r   z%s %s
r   z>%s
)r?   Zcleanr.   r0   r1   r   r   writer   r>   rangelen)r(   recordr   r.   r0   datair   r   r   write_record&  s&    $zFastaWriter.write_record)r=   N)r6   r7   r8   r9   r'   rH   r:   r   r   )r*   r   r<      s   )r<   c                   s"   e Zd ZdZd fdd	Z  ZS )FastaTwoLineWritera_  Class 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.

    Please use the ``as_fasta_2line`` function instead, or the top level
    ``Bio.SeqIO.write()`` function instead using ``format="fasta"``.
    Nc                s   t  j|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()

        N)r>   r?   )r&   r'   )r(   r   r?   )r*   r   r   r'   P  s    zFastaTwoLineWriter.__init__)N)r6   r7   r8   r9   r'   r:   r   r   )r*   r   rI   E  s   	rI   c             C   s   t | j}t | j}|r2|ddd |kr2|}n|rDd||f }n|}d|ksTtd|ks`td| g}t| }d|ks~td|kstx2tdt|dD ]}||||d  d  qW d		|S )
zTurn a SeqRecord into a FASTA formatted string.

    This is used internally by the SeqRecord's .format("fasta")
    method and by the SeqIO.write(..., ..., "fasta") function.
    Nr   r   z%s %srA   r   z>%s
r=   r
   )
r   r.   r0   r1   r   r   rC   rD   r   r   )rE   r.   r0   r   r   rF   rG   r   r   r   as_fastar  s     


rJ   c             C   s   t | j}t | j}|r2|ddd |kr2|}n|rDd||f }n|}d|ksTtd|ks`tt| }d|ksttd|kstd||f S )zTurn a SeqRecord into a two-line FASTA formatted 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 %srA   r   z>%s
%s
)r   r.   r0   r1   r   r   )rE   r.   r0   r   rF   r   r   r   as_fasta_2line  s    

rK   __main__)run_doctest)verboseN)r9   ZBio.Seqr   ZBio.SeqRecordr   Z
Interfacesr   r   r   r   r   r    r!   r;   r<   rI   rJ   rK   r6   Z
Bio._utilsrM   r   r   r   r   <module>   s"   /BI$O-