o
    RŀgZ                    @   s  U d Z ddlZddlZddlZddlZddlZddlZddlZddlm	Z	 ddlm
Z
 ddlmZ zddlZW n eyI   ddlmZ eddw 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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" e#dg dZ$G dd dZ%G dd dZ&G dd de	Z'G dd de'e(Z)G dd  d e'Z*G d!d" d"ej+Z+G d#d$ d$ej,Z,d%Z-i Z.e/e0ej1f e2d&< d'e0d(ej1fd)d*Z3d+d, Z4d-d. Z5d/d0 Z6e7d1krdd2l8m9Z9 e9  dS dS )3zCode for dealing with sequence alignments.

One of the most important things in this module is the MultipleSeqAlignment
class, used in the Bio.AlignIO module.

    N)ABC)abstractmethod)zip_longest)MissingPythonDependencyErrorzLPlease install NumPy if you want to use Bio.Align. See http://www.numpy.org/)BiopythonDeprecationWarning)
_aligncore)_codonaligner)_pairwisealigner)substitution_matrices)
CodonTable)
MutableSeqreverse_complement)Seq)	translate)UndefinedSequenceError)_RestrictedDict)	SeqRecordAlignmentCounts)gaps
identities
mismatchesc                   @   s   e Zd ZdZ	d-ddZdd Zdd Zeeed	d
Zd.ddZ	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zd/ddZd d! Zd"d# Zd$d% Zd0d'd(Zed)d* Zed+d, ZdS )1MultipleSeqAlignmentaf  Represents a classical multiple sequence alignment (MSA).

    By this we mean a collection of sequences (usually shown as rows) which
    are all the same length (usually with gap characters for insertions or
    padding). The data can then be regarded as a matrix of letters, with well
    defined columns.

    You would typically create an MSA by loading an alignment file with the
    AlignIO module:

    >>> from Bio import AlignIO
    >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal")
    >>> print(align)
    Alignment with 7 rows and 156 columns
    TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
    TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
    TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191
    TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191
    TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
    TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
    TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191

    In some respects you can treat these objects as lists of SeqRecord objects,
    each representing a row of the alignment. Iterating over an alignment gives
    the SeqRecord object for each row:

    >>> len(align)
    7
    >>> for record in align:
    ...     print("%s %i" % (record.id, len(record)))
    ...
    gi|6273285|gb|AF191659.1|AF191 156
    gi|6273284|gb|AF191658.1|AF191 156
    gi|6273287|gb|AF191661.1|AF191 156
    gi|6273286|gb|AF191660.1|AF191 156
    gi|6273290|gb|AF191664.1|AF191 156
    gi|6273289|gb|AF191663.1|AF191 156
    gi|6273291|gb|AF191665.1|AF191 156

    You can also access individual rows as SeqRecord objects via their index:

    >>> print(align[0].id)
    gi|6273285|gb|AF191659.1|AF191
    >>> print(align[-1].id)
    gi|6273291|gb|AF191665.1|AF191

    And extract columns as strings:

    >>> print(align[:, 1])
    AAAAAAA

    Or, take just the first ten columns as a sub-alignment:

    >>> print(align[:, :10])
    Alignment with 7 rows and 10 columns
    TATACATTAA gi|6273285|gb|AF191659.1|AF191
    TATACATTAA gi|6273284|gb|AF191658.1|AF191
    TATACATTAA gi|6273287|gb|AF191661.1|AF191
    TATACATAAA gi|6273286|gb|AF191660.1|AF191
    TATACATTAA gi|6273290|gb|AF191664.1|AF191
    TATACATTAA gi|6273289|gb|AF191663.1|AF191
    TATACATTAA gi|6273291|gb|AF191665.1|AF191

    Combining this alignment slicing with alignment addition allows you to
    remove a section of the alignment. For example, taking just the first
    and last ten columns:

    >>> print(align[:, :10] + align[:, -10:])
    Alignment with 7 rows and 20 columns
    TATACATTAAGTGTACCAGA gi|6273285|gb|AF191659.1|AF191
    TATACATTAAGTGTACCAGA gi|6273284|gb|AF191658.1|AF191
    TATACATTAAGTGTACCAGA gi|6273287|gb|AF191661.1|AF191
    TATACATAAAGTGTACCAGA gi|6273286|gb|AF191660.1|AF191
    TATACATTAAGTGTACCAGA gi|6273290|gb|AF191664.1|AF191
    TATACATTAAGTATACCAGA gi|6273289|gb|AF191663.1|AF191
    TATACATTAAGTGTACCAGA gi|6273291|gb|AF191665.1|AF191

    Note - This object does NOT attempt to model the kind of alignments used
    in next generation sequencing with multiple sequencing reads which are
    much shorter than the alignment, and where there is usually a consensus or
    reference sequence with special status.
    Nc                 C   s`   |durt dg | _|r| | |du ri }n	t|ts"td|| _|du r+i }|| _dS )af  Initialize a new MultipleSeqAlignment object.

        Arguments:
         - records - A list (or iterator) of SeqRecord objects, whose
                     sequences are all the same length.  This may be an empty
                     list.
         - alphabet - For backward compatibility only; its value should always
                      be None.
         - annotations - Information about the whole alignment (dictionary).
         - column_annotations - Per column annotation (restricted dictionary).
                      This holds Python sequences (lists, strings, tuples)
                      whose length matches the number of columns. A typical
                      use would be a secondary structure consensus string.

        You would normally load a MSA from a file using Bio.AlignIO, but you
        can do this from a list of SeqRecord objects too:

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c],
        ...                              annotations={"tool": "demo"},
        ...                              column_annotations={"stats": "CCCXCCC"})
        >>> print(align)
        Alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        >>> align.annotations
        {'tool': 'demo'}
        >>> align.column_annotations
        {'stats': 'CCCXCCC'}
        Nz,The alphabet argument is no longer supportedz%annotations argument should be a dict)
ValueError_recordsextend
isinstancedict	TypeErrorannotationscolumn_annotations)selfrecordsalphabetr   r     r$   F/var/www/html/myenv/lib/python3.10/site-packages/Bio/Align/__init__.py__init__   s   '


zMultipleSeqAlignment.__init__c                 C   sT   t |ts	tdt| r|  }t|d| _| j| d S d | _|r(tdd S )Nz?The per-column-annotations should be a (restricted) dictionary.lengthz5Can't set per-column-annotations without an alignment)	r   r   r   lenget_alignment_lengthr   _per_col_annotationsupdater   )r!   valueexpected_lengthr$   r$   r%   _set_per_column_annotations   s   
z0MultipleSeqAlignment._set_per_column_annotationsc                 C   s2   | j d u rt| r|  }nd}t|d| _ | j S )Nr   r'   )r+   r)   r*   r   )r!   r.   r$   r$   r%   _get_per_column_annotations   s   

z0MultipleSeqAlignment._get_per_column_annotationsz5Dictionary of per-letter-annotation for the sequence.)fgetfsetdoc2   c                 C   s   |j jjdkr+t|j |kr|j  d|j S d|j d|d  |j dd |jf S t|j |kr;|j  d|j S d|j d|d  |j dd |jf S )zReturn a truncated string representation of a SeqRecord (PRIVATE).

        This is a PRIVATE function used by the __str__ method.
        CodonSeq z
%s...%s %sN      )seq	__class____name__r)   id)r!   recordr(   r$   r$   r%   	_str_line   s   zMultipleSeqAlignment._str_linec                    s   t  j}d|  f g}|dkr | fdd jD  n!| fdd jdd D  |d |  jd	  d
|S )aq  Return a multi-line string summary of the alignment.

        This output is intended to be readable, but large alignments are
        shown truncated.  A maximum of 20 rows (sequences) and 50 columns
        are shown, with the record identifiers.  This should fit nicely on a
        single screen. e.g.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha")
        >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta")
        >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> print(align)
        Alignment with 3 rows and 12 columns
        ACTGCTAGCTAG Alpha
        ACT-CTAGCTAG Beta
        ACTGCTAGATAG Gamma

        See also the alignment's format method.
        z%Alignment with %i rows and %i columns   c                 3       | ]}  |V  qd S Nr?   .0recr!   r$   r%   	<genexpr>(      z/MultipleSeqAlignment.__str__.<locals>.<genexpr>c                 3   rA   rB   rC   rD   rG   r$   r%   rH   *  rI   N   z...
)r)   r   r*   r   appendr?   join)r!   rowslinesr$   rG   r%   __str__  s   

"

zMultipleSeqAlignment.__str__c                 C   s    d| j t| j|  t| f S )a  Return a representation of the object for debugging.

        The representation cannot be used with eval() to recreate the object,
        which is usually possible with simple python objects.  For example:

        <Bio.Align.MultipleSeqAlignment instance (2 records of length 14)
        at a3c184c>

        The hex string is the memory address of the object, see help(id).
        This provides a simple way to visually distinguish alignments of
        the same size.
        z-<%s instance (%i records of length %i) at %x>)r;   r)   r   r*   r=   rG   r$   r$   r%   __repr__/  s   zMultipleSeqAlignment.__repr__c                 C   sB   |rddl m} ddlm} | }|| g|| | S t| S )a2  Return the alignment as a string in the specified file format.

        The format should be a lower case string supported as an output
        format by Bio.AlignIO (such as "fasta", "clustal", "phylip",
        "stockholm", etc), which is used to turn the alignment into a
        string.

        e.g.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha", description="")
        >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta", description="")
        >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma", description="")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> print(format(align, "fasta"))
        >Alpha
        ACTGCTAGCTAG
        >Beta
        ACT-CTAGCTAG
        >Gamma
        ACTGCTAGATAG
        <BLANKLINE>
        >>> print(format(align, "phylip"))
         3 12
        Alpha      ACTGCTAGCT AG
        Beta       ACT-CTAGCT AG
        Gamma      ACTGCTAGAT AG
        <BLANKLINE>
        r   )StringIO)AlignIO)iorS   BiorT   writegetvaluestr)r!   format_specrS   rT   handler$   r$   r%   
__format__I  s    zMultipleSeqAlignment.__format__c                 C   
   t | jS )a  Iterate over alignment rows as SeqRecord objects.

        e.g.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha")
        >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta")
        >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> for record in align:
        ...    print(record.id)
        ...    print(record.seq)
        ...
        Alpha
        ACTGCTAGCTAG
        Beta
        ACT-CTAGCTAG
        Gamma
        ACTGCTAGATAG
        )iterr   rG   r$   r$   r%   __iter__u  s   
zMultipleSeqAlignment.__iter__c                 C   r]   )a  Return the number of sequences in the alignment.

        Use len(alignment) to get the number of sequences (i.e. the number of
        rows), and alignment.get_alignment_length() to get the length of the
        longest sequence (i.e. the number of columns).

        This is easy to remember if you think of the alignment as being like a
        list of SeqRecord objects.
        )r)   r   rG   r$   r$   r%   __len__  s   

zMultipleSeqAlignment.__len__c                 C   s,   d}| j D ]}t|j|krt|j}q|S )a1  Return the maximum length of the alignment.

        All objects in the alignment should (hopefully) have the same
        length. This function will go through and find this length
        by finding the maximum length of sequences in the alignment.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("ACTGCTAGCTAG"), id="Alpha")
        >>> b = SeqRecord(Seq("ACT-CTAGCTAG"), id="Beta")
        >>> c = SeqRecord(Seq("ACTGCTAGATAG"), id="Gamma")
        >>> align = MultipleSeqAlignment([a, b, c])
        >>> align.get_alignment_length()
        12

        If you want to know the number of sequences in the alignment,
        use len(align) instead:

        >>> len(align)
        3

        r   )r   r)   r:   )r!   
max_lengthr>   r$   r$   r%   r*     s   

z)MultipleSeqAlignment.get_alignment_lengthc                 C   sp   t | r	|  }n"t|}zt|}W n
 ty   Y dS w t |}| || i | _|D ]}| || q-dS )a"  Add more SeqRecord objects to the alignment as rows.

        They must all have the same length as the original alignment. For
        example,

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma")
        >>> d = SeqRecord(Seq("AAAACGT"), id="Delta")
        >>> e = SeqRecord(Seq("AAA-GGT"), id="Epsilon")

        First we create a small alignment (three rows):

        >>> align = MultipleSeqAlignment([a, b, c])
        >>> print(align)
        Alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        Now we can extend this alignment with another two rows:

        >>> align.extend([d, e])
        >>> print(align)
        Alignment with 5 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma
        AAAACGT Delta
        AAA-GGT Epsilon

        Because the alignment object allows iteration over the rows as
        SeqRecords, you can use the extend method with a second alignment
        (provided its sequences have the same length as the original alignment).
        N)r)   r*   r^   nextStopIteration_appendr    )r!   r"   r.   rF   r$   r$   r%   r     s   '
zMultipleSeqAlignment.extendc                 C   s(   | j r| ||   dS | | dS )a7  Add one more SeqRecord object to the alignment as a new row.

        This must have the same length as the original alignment (unless this is
        the first record).

        >>> from Bio import AlignIO
        >>> align = AlignIO.read("Clustalw/opuntia.aln", "clustal")
        >>> print(align)
        Alignment with 7 rows and 156 columns
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191
        TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191
        >>> len(align)
        7

        We'll now construct a dummy record to append as an example:

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> dummy = SeqRecord(Seq("N"*156), id="dummy")

        Now append this to the alignment,

        >>> align.append(dummy)
        >>> print(align)
        Alignment with 8 rows and 156 columns
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273285|gb|AF191659.1|AF191
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273284|gb|AF191658.1|AF191
        TATACATTAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273287|gb|AF191661.1|AF191
        TATACATAAAAGAAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273286|gb|AF191660.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273290|gb|AF191664.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273289|gb|AF191663.1|AF191
        TATACATTAAAGGAGGGGGATGCGGATAAATGGAAAGGCGAAAG...AGA gi|6273291|gb|AF191665.1|AF191
        NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN...NNN dummy
        >>> len(align)
        8

        N)r   rd   r*   )r!   r>   r$   r$   r%   rM     s   +zMultipleSeqAlignment.appendc                 C   s>   t |ts	td|durt||krtd| j| dS )z'Validate and append a record (PRIVATE).z&New sequence is not a SeqRecord objectNz%Sequences must all be the same length)r   r   r   r)   r   r   rM   )r!   r>   r.   r$   r$   r%   rd   &  s
   
zMultipleSeqAlignment._appendc                 C   s   t |tstt| t|krtddd t| |D }i }| j D ]\}}||jv r8|j| |kr8|||< q$i }| j D ]\}}||jv rR||j|  ||< q@t|||dS )a|
  Combine two alignments with the same number of rows by adding them.

        If you have two multiple sequence alignments (MSAs), there are two ways to think
        about adding them - by row or by column. Using the extend method adds by row.
        Using the addition operator adds by column. For example,

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a1 = SeqRecord(Seq("AAAAC"), id="Alpha")
        >>> b1 = SeqRecord(Seq("AAA-C"), id="Beta")
        >>> c1 = SeqRecord(Seq("AAAAG"), id="Gamma")
        >>> a2 = SeqRecord(Seq("GT"), id="Alpha")
        >>> b2 = SeqRecord(Seq("GT"), id="Beta")
        >>> c2 = SeqRecord(Seq("GT"), id="Gamma")
        >>> left = MultipleSeqAlignment([a1, b1, c1],
        ...                             annotations={"tool": "demo", "name": "start"},
        ...                             column_annotations={"stats": "CCCXC"})
        >>> right = MultipleSeqAlignment([a2, b2, c2],
        ...                             annotations={"tool": "demo", "name": "end"},
        ...                             column_annotations={"stats": "CC"})

        Now, let's look at these two alignments:

        >>> print(left)
        Alignment with 3 rows and 5 columns
        AAAAC Alpha
        AAA-C Beta
        AAAAG Gamma
        >>> print(right)
        Alignment with 3 rows and 2 columns
        GT Alpha
        GT Beta
        GT Gamma

        And add them:

        >>> combined = left + right
        >>> print(combined)
        Alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAA-CGT Beta
        AAAAGGT Gamma

        For this to work, both alignments must have the same number of records (here
        they both have 3 rows):

        >>> len(left)
        3
        >>> len(right)
        3
        >>> len(combined)
        3

        The individual rows are SeqRecord objects, and these can be added together. Refer
        to the SeqRecord documentation for details of how the annotation is handled. This
        example is a special case in that both original alignments shared the same names,
        meaning when the rows are added they also get the same name.

        Any common annotations are preserved, but differing annotation is lost. This is
        the same behaviour used in the SeqRecord annotations and is designed to prevent
        accidental propagation of inappropriate values:

        >>> combined.annotations
        {'tool': 'demo'}

        Similarly any common per-column-annotations are combined:

        >>> combined.column_annotations
        {'stats': 'CCCXCCC'}

        TWhen adding two alignments they must have the same length (i.e. same number of rows)c                 s   s    | ]	\}}|| V  qd S rB   r$   )rE   leftrightr$   r$   r%   rH     s    z/MultipleSeqAlignment.__add__.<locals>.<genexpr>)r   r    )	r   r   NotImplementedErrorr)   r   zipr   itemsr    )r!   othermergedr   kvr    r$   r$   r%   __add__6  s(   
I
zMultipleSeqAlignment.__add__c                    s  t |tr
| j| S t |tr2t| j| }| jr0t|t| kr0| j D ]	\}}||j|< q&|S t|dkr<td|\} t |trL| j|   S t  tr`d	 fdd| j| D S t fdd| j| D }| jrt|t| kr| j D ]\}}|  |j|< q~|S )a  Access part of the alignment.

        Depending on the indices, you can get a SeqRecord object
        (representing a single row), a Seq object (for a single column),
        a string (for a single character) or another alignment
        (representing some part or all of the alignment).

        align[r,c] gives a single character as a string
        align[r] gives a row as a SeqRecord
        align[r,:] gives a row as a SeqRecord
        align[:,c] gives a column as a Seq

        align[:] and align[:,:] give a copy of the alignment

        Anything else gives a sub alignment, e.g.
        align[0:2] or align[0:2,:] uses only row 0 and 1
        align[:,1:3] uses only columns 1 and 2
        align[0:2,1:3] uses only rows 0 & 1 and only cols 1 & 2

        We'll use the following example alignment here for illustration:

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> a = SeqRecord(Seq("AAAACGT"), id="Alpha")
        >>> b = SeqRecord(Seq("AAA-CGT"), id="Beta")
        >>> c = SeqRecord(Seq("AAAAGGT"), id="Gamma")
        >>> d = SeqRecord(Seq("AAAACGT"), id="Delta")
        >>> e = SeqRecord(Seq("AAA-GGT"), id="Epsilon")
        >>> align = MultipleSeqAlignment([a, b, c, d, e])

        You can access a row of the alignment as a SeqRecord using an integer
        index (think of the alignment as a list of SeqRecord objects here):

        >>> first_record = align[0]
        >>> print("%s %s" % (first_record.id, first_record.seq))
        Alpha AAAACGT
        >>> last_record = align[-1]
        >>> print("%s %s" % (last_record.id, last_record.seq))
        Epsilon AAA-GGT

        You can also access use python's slice notation to create a sub-alignment
        containing only some of the SeqRecord objects:

        >>> sub_alignment = align[2:5]
        >>> print(sub_alignment)
        Alignment with 3 rows and 7 columns
        AAAAGGT Gamma
        AAAACGT Delta
        AAA-GGT Epsilon

        This includes support for a step, i.e. align[start:end:step], which
        can be used to select every second sequence:

        >>> sub_alignment = align[::2]
        >>> print(sub_alignment)
        Alignment with 3 rows and 7 columns
        AAAACGT Alpha
        AAAAGGT Gamma
        AAA-GGT Epsilon

        Or to get a copy of the alignment with the rows in reverse order:

        >>> rev_alignment = align[::-1]
        >>> print(rev_alignment)
        Alignment with 5 rows and 7 columns
        AAA-GGT Epsilon
        AAAACGT Delta
        AAAAGGT Gamma
        AAA-CGT Beta
        AAAACGT Alpha

        You can also use two indices to specify both rows and columns. Using simple
        integers gives you the entry as a single character string. e.g.

        >>> align[3, 4]
        'C'

        This is equivalent to:

        >>> align[3][4]
        'C'

        or:

        >>> align[3].seq[4]
        'C'

        To get a single column (as a string) use this syntax:

        >>> align[:, 4]
        'CCGCG'

        Or, to get part of a column,

        >>> align[1:3, 4]
        'CG'

        However, in general you get a sub-alignment,

        >>> print(align[1:5, 3:6])
        Alignment with 4 rows and 3 columns
        -CG Beta
        AGG Gamma
        ACG Delta
        -GG Epsilon

        This should all seem familiar to anyone who has used the NumPy
        array or matrix objects.
           Invalid index type. c                 3       | ]}|  V  qd S rB   r$   rD   	col_indexr$   r%   rH         z3MultipleSeqAlignment.__getitem__.<locals>.<genexpr>c                 3   rs   rB   r$   rD   rt   r$   r%   rH     s    
)
r   intr   slicer   r    r)   rj   r   rN   )r!   indexnewrm   rn   	row_indexr$   rt   r%   __getitem__  s,   
o



z MultipleSeqAlignment.__getitem__c                 C   s(   t |tst |tstd| j|= dS )z:Delete SeqRecord by index or multiple SeqRecords by slice.rq   N)r   rw   rx   r   r   )r!   ry   r$   r$   r%   __delitem__'  s   z MultipleSeqAlignment.__delitem__Fc                 C   s4   |du r| j jdd |d dS | j j||d dS )a	  Sort the rows (SeqRecord objects) of the alignment in place.

        This sorts the rows alphabetically using the SeqRecord object id by
        default. The sorting can be controlled by supplying a key function
        which must map each SeqRecord to a sort value.

        This is useful if you want to add two alignments which use the same
        record identifiers, but in a different order. For example,

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> align1 = MultipleSeqAlignment([
        ...              SeqRecord(Seq("ACGT"), id="Human"),
        ...              SeqRecord(Seq("ACGG"), id="Mouse"),
        ...              SeqRecord(Seq("ACGC"), id="Chicken"),
        ...          ])
        >>> align2 = MultipleSeqAlignment([
        ...              SeqRecord(Seq("CGGT"), id="Mouse"),
        ...              SeqRecord(Seq("CGTT"), id="Human"),
        ...              SeqRecord(Seq("CGCT"), id="Chicken"),
        ...          ])

        If you simple try and add these without sorting, you get this:

        >>> print(align1 + align2)
        Alignment with 3 rows and 8 columns
        ACGTCGGT <unknown id>
        ACGGCGTT <unknown id>
        ACGCCGCT Chicken

        Consult the SeqRecord documentation which explains why you get a
        default value when annotation like the identifier doesn't match up.
        However, if we sort the alignments first, then add them we get the
        desired result:

        >>> align1.sort()
        >>> align2.sort()
        >>> print(align1 + align2)
        Alignment with 3 rows and 8 columns
        ACGCCGCT Chicken
        ACGTCGTT Human
        ACGGCGGT Mouse

        As an example using a different sort order, you could sort on the
        GC content of each sequence.

        >>> from Bio.SeqUtils import gc_fraction
        >>> print(align1)
        Alignment with 3 rows and 4 columns
        ACGC Chicken
        ACGT Human
        ACGG Mouse
        >>> align1.sort(key = lambda record: gc_fraction(record.seq))
        >>> print(align1)
        Alignment with 3 rows and 4 columns
        ACGT Human
        ACGC Chicken
        ACGG Mouse

        There is also a reverse argument, so if you wanted to sort by ID
        but backwards:

        >>> align1.sort(reverse=True)
        >>> print(align1)
        Alignment with 3 rows and 4 columns
        ACGG Mouse
        ACGT Human
        ACGC Chicken

        Nc                 S   s   | j S rB   r=   )rr$   r$   r%   <lambda>w  s    z+MultipleSeqAlignment.sort.<locals>.<lambda>keyreverse)r   sort)r!   r   r   r$   r$   r%   r   .  s   HzMultipleSeqAlignment.sortc                 C   s  t jdd | D  }z|d W n	 ty   Y nw dt|}tj|dd}t| D ]G\}}|j	}|j
dd}t| D ]4\}}||krI n+|j	}	|j
dd}
t||	D ]\}}|dkraqX|dkrfqX|||f  ||
 7  < qXq?q-|| 7 }|d	 }|S )
aA  Return an Array with the number of substitutions of letters in the alignment.

        As an example, consider a multiple sequence alignment of three DNA sequences:

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import MultipleSeqAlignment
        >>> seq1 = SeqRecord(Seq("ACGT"), id="seq1")
        >>> seq2 = SeqRecord(Seq("A--A"), id="seq2")
        >>> seq3 = SeqRecord(Seq("ACGT"), id="seq3")
        >>> seq4 = SeqRecord(Seq("TTTC"), id="seq4")
        >>> alignment = MultipleSeqAlignment([seq1, seq2, seq3, seq4])
        >>> print(alignment)
        Alignment with 4 rows and 4 columns
        ACGT seq1
        A--A seq2
        ACGT seq3
        TTTC seq4

        >>> m = alignment.substitutions
        >>> print(m)
            A   C   G   T
        A 3.0 0.5 0.0 2.5
        C 0.5 1.0 0.0 2.0
        G 0.0 0.0 1.0 1.0
        T 2.5 2.0 1.0 1.0
        <BLANKLINE>

        Note that the matrix is symmetric, with counts divided equally on both
        sides of the diagonal. For example, the total number of substitutions
        between A and T in the alignment is 3.5 + 3.5 = 7.

        Any weights associated with the sequences are taken into account when
        calculating the substitution matrix.  For example, given the following
        multiple sequence alignment::

            GTATC  0.5
            AT--C  0.8
            CTGTC  1.0

        For the first column we have::

            ('A', 'G') : 0.5 * 0.8 = 0.4
            ('C', 'G') : 0.5 * 1.0 = 0.5
            ('A', 'C') : 0.8 * 1.0 = 0.8

        c                 s   s    | ]}t |jV  qd S rB   )setr:   rE   r>   r$   r$   r%   rH     rI   z5MultipleSeqAlignment.substitutions.<locals>.<genexpr>-rr   rp   dimsweight      ?g       @)r   unionremoveKeyErrorrN   sortedr
   Array	enumerater:   r   getri   	transpose)r!   lettersmrec_num1
alignment1seq1weight1rec_num2
alignment2seq2weight2residue1residue2r$   r$   r%   substitutions{  s6   1z"MultipleSeqAlignment.substitutionsc                    s  dd | j D }|r{dd |D }t|\}}t||D ]W\}}|jrodd t|jD }t|j}|j  t	||_|
 D ])\}	 t trWd fdd|D  nt }
|
 fdd|D   ||	< qA||_qt	||_qt||}ntg }| j|_| j|_|S )	a  Return an Alignment object based on the MultipleSeqAlignment object.

        This makes a copy of each SeqRecord with a gap-less sequence. Any
        future changes to the original records in the MultipleSeqAlignment will
        not affect the new records in the Alignment.
        c                 S   s   g | ]}t  |qS r$   )copyr   r$   r$   r%   
<listcomp>      z2MultipleSeqAlignment.alignment.<locals>.<listcomp>c                 S   s   g | ]}t |jqS r$   )bytesr:   r   r$   r$   r%   r     r   c                 S   s   g | ]
\}}|d kr|qS )r   r$   )rE   icr$   r$   r%   r     s    rr   c                       g | ]} | qS r$   r$   rE   r   r-   r$   r%   r         c                 3       | ]} | V  qd S rB   r$   r   r   r$   r%   rH     rv   z1MultipleSeqAlignment.alignment.<locals>.<genexpr>)r   	Alignmentparse_printed_alignmentri   letter_annotationsr   r:   r   clearr   rj   r   rY   rN   typer   r    )r!   r"   rP   seqdatacoordinatesr>   seqrowindicesr   r   cls	alignmentr$   r   r%   r     s.   




zMultipleSeqAlignment.alignment)NNN)r4   rB   NF)r<   
__module____qualname____doc__r&   r/   r0   propertyr    r?   rQ   rR   r\   r_   r`   r*   r   rM   rd   ro   r|   r}   r   r   r   r$   r$   r$   r%   r   ?   s<    T
;
$, <
0^ 
M
Kr   c                   @   s  e Zd ZdZedd Zedd Zd]ddZd]d	d
Zdd Z	e
dd Ze
dd Zejdd Ze
dd Zejdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd^d8d9Z d:d; Z!d<d= Z"d>d? Z#d@dA Z$dBdC Z%dDdE Z&e
dFdG Z'e
dHdI Z(e
dJdK Z)e
dLdM Z*e
dNdO Z+d_dQdRZ,dSdT Z-dUdV Z.e
dWdX Z/dYdZ Z0d[d\ Z1dS )`r   a  Represents a sequence alignment.

    An Alignment object has a `.sequences` attribute storing the sequences
    (Seq, MutableSeq, SeqRecord, or string objects) that were aligned, as well
    as a `.coordinates` attribute storing the sequence coordinates defining the
    alignment as a NumPy array.

    Other commonly used attributes (which may or may not be present) are:
         - annotations        - A dictionary with annotations describing the
                                alignment;
         - column_annotations - A dictionary with annotations describing each
                                column in the alignment;
         - score              - The alignment score.
    c                 C   s,   t dt dd |D }| |\}}|S )a  Infer the coordinates from a printed alignment (DEPRECATED).

        This method is primarily employed in Biopython's alignment parsers,
        though it may be useful for other purposes.

        For an alignment consisting of N sequences, printed as N lines with
        the same number of columns, where gaps are represented by dashes,
        this method will calculate the sequence coordinates that define the
        alignment. The coordinates are returned as a NumPy array of integers,
        and can be used to create an Alignment object.

        This is an example for the alignment of three sequences TAGGCATACGTG,
        AACGTACGT, and ACGCATACTTG, with gaps in the second and third sequence:

        >>> from Bio.Align import Alignment
        >>> lines = ["TAGGCATACGTG",
        ...          "AACG--TACGT-",
        ...          "-ACGCATACTTG",
        ...         ]
        >>> sequences = [line.replace("-", "") for line in lines]
        >>> sequences
        ['TAGGCATACGTG', 'AACGTACGT', 'ACGCATACTTG']
        >>> coordinates = Alignment.infer_coordinates(lines)
        >>> print(coordinates)
        [[ 0  1  4  6 11 12]
         [ 0  1  4  4  9  9]
         [ 0  0  3  5 10 11]]
        >>> alignment = Alignment(sequences, coordinates)
        zThe method infer_coordinates is deprecated; please use the method parse_printed_alignment instead. This method is much faster than infer_coordinates, and returns both the sequences after removal of the gaps and the coordinates.c                 S   s   g | ]}|  qS r$   )encode)rE   liner$   r$   r%   r   !  r   z/Alignment.infer_coordinates.<locals>.<listcomp>)warningswarnr   r   )r   rP   r   r   r$   r$   r%   infer_coordinates  s   zAlignment.infer_coordinatesc           	      C   sV   t d}g }|D ]}||\}}|| q	|j}t|tj}|| ||fS )a  Infer the sequences and coordinates from a printed alignment.

        This method is primarily employed in Biopython's alignment parsers,
        though it may be useful for other purposes.

        For an alignment consisting of N sequences, printed as N lines with
        the same number of columns, where gaps are represented by dashes,
        this method will calculate the sequence coordinates that define the
        alignment. It returns the tuple (sequences, coordinates), where
        sequences is the list of N sequences after removing the gaps, and
        the coordinates is a 2D NumPy array of integers. Together, the
        sequences and coordinates can be used to create an Alignment object.

        This is an example for the alignment of three sequences TAGGCATACGTG,
        AACGTACGT, and ACGCATACTTG, with gaps in the second and third sequence.
        Note that the input sequences are bytes objects.

        >>> from Bio.Align import Alignment
        >>> from Bio.Seq import Seq
        >>> lines = [b"TAGGCATACGTG",
        ...          b"AACG--TACGT-",
        ...          b"-ACGCATACTTG",
        ...         ]
        >>> sequences, coordinates = Alignment.parse_printed_alignment(lines)
        >>> sequences
        [b'TAGGCATACGTG', b'AACGTACGT', b'ACGCATACTTG']
        >>> print(coordinates)
        [[ 0  1  4  6 11 12]
         [ 0  1  4  4  9  9]
         [ 0  0  3  5 10 11]]
        >>> sequences = [Seq(sequence) for sequence in sequences]
        >>> sequences
        [Seq('TAGGCATACGTG'), Seq('AACGTACGT'), Seq('ACGCATACTTG')]
        >>> alignment = Alignment(sequences, coordinates)
        >>> print(alignment)
                          0 TAGGCATACGTG 12
                          0 AACG--TACGT-  9
                          0 -ACGCATACTTG 11
        <BLANKLINE>
            )	r   PrintedAlignmentParserfeedrM   shapenpemptyint64fill)	r   rP   parser	sequencesr   nbytessequencer   r   r$   r$   r%   r   %  s   
*
z!Alignment.parse_printed_alignmentNc                 C   s   || _ |du rCz	dd |D }W n	 ty   Y n*w t|dkr(tjdtd}nt|dkr?| }td|ggt| }ntd|| _	dS )	a  Initialize a new Alignment object.

        Arguments:
         - sequences   - A list of the sequences (Seq, MutableSeq, SeqRecord,
                         or string objects) that were aligned.
         - coordinates - The sequence coordinates that define the alignment.
                         If None (the default value), assume that the sequences
                         align to each other without any gaps.
        Nc                 S   s   h | ]}t |qS r$   r)   rE   r   r$   r$   r%   	<setcomp>f  r   z%Alignment.__init__.<locals>.<setcomp>r   r   r   )dtype   z:sequences must have the same length if coordinates is None)
r   r   r)   r   r   rw   poparrayr   r   )r!   r   r   lengthsr(   r$   r$   r%   r&   Y  s    

zAlignment.__init__c              
   C   s  | j  }t| j}t| j d}t|dkddk}t|D ]E\}}|||f }|dk r/q|dk r]t	|||< t
|||d d f  ||d d f< ||d d f  ||d d f< qtd| |d}	||	k|dkB  swtdt
|}
t|	}t|
|fd}t|
D ]o}|| }||df }d}t|| |	D ]Y\}}|dkr|| }|| }
z
t||| }W n ty   t||| d}Y nw |||d d f jd||
< |}|
}q|dk r||7 }q|| }
d||||
f< |
}qq|d urt||}|S )	Nr   r   Inconsistent steps in row Unequal step sizes in alignmentS1UTF8B   -)r   r   listr   r   diffsumr   allr   r)   r   maxr   rangeri   r   r   datacastr   )r!   r   r   r   stepsalignedr   r   rowr   nr   r   rm   stepgapjsubsequencer$   r$   r%   	__array__x  sX   

$ 
 

zAlignment.__array__c              	   C   s  t |tstt| t|krtd| jdddf }| jdddf }| j}|jdddf }|jdddf }|j}g }t||||||D ]\}	}
}}}}||	|
 |||  }|| qH|| | }| j|dddf  }|j|dddf  }t	j||dd}t||}i }z"| j
 D ]\}}z|j
| |kr|||< W q ty   Y qw W n	 ty   Y nw ||_
i }z | j D ]\}}z||j|  ||< W q ty   Y qw W n
 ty   Y |S w ||_|S )a  Combine two alignments by adding them row-wise.

        For example,

        >>> import numpy as np
        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> from Bio.Align import Alignment
        >>> a1 = SeqRecord(Seq("AAAAC"), id="Alpha")
        >>> b1 = SeqRecord(Seq("AAAC"), id="Beta")
        >>> c1 = SeqRecord(Seq("AAAAG"), id="Gamma")
        >>> a2 = SeqRecord(Seq("GTT"), id="Alpha")
        >>> b2 = SeqRecord(Seq("TT"), id="Beta")
        >>> c2 = SeqRecord(Seq("GT"), id="Gamma")
        >>> left = Alignment([a1, b1, c1],
        ...                  coordinates=np.array([[0, 3, 4, 5],
        ...                                        [0, 3, 3, 4],
        ...                                        [0, 3, 4, 5]]))
        >>> left.annotations = {"tool": "demo", "name": "start"}
        >>> left.column_annotations = {"stats": "CCCXC"}
        >>> right = Alignment([a2, b2, c2],
        ...                   coordinates=np.array([[0, 1, 2, 3],
        ...                                         [0, 0, 1, 2],
        ...                                         [0, 1, 1, 2]]))
        >>> right.annotations = {"tool": "demo", "name": "end"}
        >>> right.column_annotations = {"stats": "CXC"}

        Now, let's look at these two alignments:

        >>> print(left)
        Alpha             0 AAAAC 5
        Beta              0 AAA-C 4
        Gamma             0 AAAAG 5
        <BLANKLINE>
        >>> print(right)
        Alpha             0 GTT 3
        Beta              0 -TT 2
        Gamma             0 G-T 2
        <BLANKLINE>

        And add them:

        >>> combined = left + right
        >>> print(combined)
        Alpha             0 AAAACGTT 8
        Beta              0 AAA-C-TT 6
        Gamma             0 AAAAGG-T 7
        <BLANKLINE>

        For this to work, both alignments must have the same number of sequences
        (here they both have 3 rows):

        >>> len(left)
        3
        >>> len(right)
        3
        >>> len(combined)
        3

        The sequences are SeqRecord objects, and these can be added together. Refer
        to the SeqRecord documentation for details of how the annotation is handled. This
        example is a special case in that both original alignments shared the same names,
        meaning when the rows are added they also get the same name.

        Any common annotations are preserved, but differing annotation is lost. This is
        the same behavior used in the SeqRecord annotations and is designed to prevent
        accidental propagation of inappropriate values:

        >>> combined.annotations
        {'tool': 'demo'}

        Similarly any common per-column-annotations are combined:

        >>> combined.column_annotations
        {'stats': 'CCCXCCXC'}

        re   Nr   rK   r   axis)r   r   rh   r)   r   r   r   ri   rM   r   r   rj   r   AttributeErrorr    )r!   rk   starts1ends1
sequences1starts2ends2
sequences2r   start1end1r   start2end2r   r   offsetcoordinates1coordinates2r   r   r   rm   rn   r    r$   r$   r%   ro     sj   
N
zAlignment.__add__c              
   C   s  | j  }t| j}t| j d}t|dkddk}t|D ]E\}}|||f }|dk r/q|dk r]t	|||< t
|||ddf  ||ddf< ||ddf  ||ddf< qtd| |d}||k|dkB  swtdt
|}	t|}
i }t|	D ]}|| }z	|jdd}W n ty   d}Y nw ||df }d}t|| |D ]\}}|dkr|| }|| }	z
t||| }W n ty   t||| d}Y nw tt||	|D ]"\}}t|}||}|du rt|
}|||< ||  |7  < q|}|	}q|dk r||7 }q|| }	d	}||}|du r0t|
}|||< |||	  |7  < |	}qq|S )
aL  Return the frequency of each letter in each column of the alignment.

        Gaps are represented by a dash ("-") character.
        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = "global"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 -GACCT-G 6
                          0 -||--|-| 8
        query             0 CGA--TCG 6
        <BLANKLINE>
        >>> alignment.frequencies
        {'-': array([1., 0., 0., 1., 1., 0., 1., 0.]), 'G': array([0., 2., 0., 0., 0., 0., 0., 2.]), 'A': array([0., 0., 2., 0., 0., 0., 0., 0.]), 'C': array([1., 0., 0., 1., 1., 0., 1., 0.]), 'T': array([0., 0., 0., 0., 0., 2., 0., 0.])}
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACCT-G 6
                          0 ||--|-| 7
        query             1 GA--TCG 6
        <BLANKLINE>
        >>> alignment.frequencies
        {'G': array([2., 0., 0., 0., 0., 0., 2.]), 'A': array([0., 2., 0., 0., 0., 0., 0.]), 'C': array([0., 0., 1., 1., 0., 1., 0.]), 'T': array([0., 0., 0., 0., 2., 0., 0.]), '-': array([0., 0., 1., 1., 0., 1., 0.])}
        r   r   Nr   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r)   r   r   r   r   r   r   ri   r   r   chrzeros)r!   r   r   r   r   r   r   r   r   r   r(   countsr   rm   r   r   r   r   r   ry   letter	characterr$   r$   r%   frequencies'  st   

$ 








zAlignment.frequenciesc                 C   s(   t | j}|dkrtd| | jd S )z2Return self.sequences[0] for a pairwise alignment.rp   Uself.target is defined for pairwise alignments only (found alignment of %d sequences)r   r)   r   r   r!   r   r$   r$   r%   target  s   

zAlignment.targetc                 C   ,   t | j}|dkrtd| || jd< dS )z0For a pairwise alignment, set self.sequences[0].rp   r  r   Nr  r!   r-   r   r$   r$   r%   r       
c                 C   s(   t | j}|dkrtd| | jd S )z2Return self.sequences[1] for a pairwise alignment.rp   Tself.query is defined for pairwise alignments only (found alignment of %d sequences)r   r  r  r$   r$   r%   query  s   

zAlignment.queryc                 C   r  )z0For a pairwise alignment, set self.sequences[1].rp   r
  r   Nr  r  r$   r$   r%   r    r	  c              	   C   sr   t | j|jD ])\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||kr0 dS qt| j|jS )z:Check if two Alignment objects specify the same alignment.Fr   r   r:   r   r   array_equalr   r!   rk   rf   rg   r$   r$   r%   __eq__  s   

zAlignment.__eq__c              	   C   st   t | j|jD ])\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||kr0 dS qt| j|j S )z9Check if two Alignment objects have different alignments.Tr  r  r$   r$   r%   __ne__  s   

zAlignment.__ne__c              	   C   s   t | j|jD ]0\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||k r0 dS ||kr7 dS qt| j |j D ]\}}t|t|}}||k rW dS ||kr^ dS qCdS )z'Check if self should come before other.TFr   r   r:   r   ri   r   r   tupler  r$   r$   r%   __lt__  4   

zAlignment.__lt__c              	   C   s   t | j|jD ]0\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||k r0 dS ||kr7 dS qt| j |j D ]\}}t|t|}}||k rW dS ||kr^ dS qCdS )z6Check if self should come before or is equal to other.TFr  r  r$   r$   r%   __le__  r  zAlignment.__le__c              	   C   s   t | j|jD ]0\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||k r0 dS ||kr7 dS qt| j |j D ]\}}t|t|}}||krW dS ||k r^ dS qCdS )z&Check if self should come after other.FTr  r  r$   r$   r%   __gt__  r  zAlignment.__gt__c              	   C   s   t | j|jD ]0\}}z|j}W n	 ty   Y nw z|j}W n	 ty(   Y nw ||k r0 dS ||kr7 dS qt| j |j D ]\}}t|t|}}||krW dS ||k r^ dS qCdS )z5Check if self should come after or is equal to other.FTr  r  r$   r$   r%   __ge__  r  zAlignment.__ge__c                 C   s  t | jd}t|}|dk r||7 }|dk rtdn||kr$tdt|dkddk}| j|ddf }| j| }t|D ]1}|||f }t|dkt|dk k rp||ddf  ||ddf< ||krpt|}t|| }q?|	d}	z|j
}W n	 ty   Y nw || }|d }
t|ttfrd}t||	D ](\}}|dkr|
| }|t||
| 7 }|}
q|dk r|
|7 }
q|d| 7 }q|S g }t||	D ] \}}|dkr|
| }|||
|  |}
q|dg|  q|S )aO  Return self[index], where index is an integer (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[row]

        where row is an integer.
        Return value is a string if the aligned sequences are string, Seq,
        or SeqRecord objects, otherwise the return value is a list.
        r   r   zrow index out of rangeNrr   r   )r   r   r   r)   
IndexErrorr   r   r   r   r   r:   r   r   rY   r   ri   r   )r!   ry   r   r   r   r   r   r   aligned_stepsr   rm   r   r   r   r   r$   r$   r%   _get_row0  s^   




zAlignment._get_rowc                 C   sx   | j | }| j|  }t||}t| j|r:z| j|_W n	 ty'   Y nw z| j|_W |S  ty9   Y |S w |S )zReturn self[key], where key is a slice object (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[rows]

        where rows is a slice object. Return value is an Alignment object.
        )	r   r   r   r   r   r  scorer   r    )r!   r   r   r   r   r$   r$   r%   	_get_rowsk  s"   
	

zAlignment._get_rowsc           	      C   sR   |  }|j|dd}|| r'|||  }|t|d|d  | 7 }|| S dS )a  Return the sequence contents at alignment column j (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[row, col]

        where both row and col are integers.
        Return value is a string of length 1.
        rg   sideNr   r   )cumsumsearchsortedr   )	r!   r   colr   r   r   r   ry   r   r$   r$   r%   _get_row_col  s   
zAlignment._get_row_colc                 C   s:  |  }|j|dd}|||d j|dd }	z|j}W n	 ty&   Y nw t|ttfr||	kr\|| }
|| dkrBd|
 }|S || | ||d   }||
 }t||| }|S || | }
|| dkrmd|
 }n||d  }||
 }t||| }|d7 }||	k r|| }|| dkr|d| 7 }n|| }||d  }|t||| 7 }|d7 }||	k s|||d   }
|
dkr|| dkr|d|
 7 }|S || }||
 }|t||| 7 }|S ||	kr|| }
|| dkrdg|
 }|S || | ||d   }||
 }||| }|S || | }
|| dkr#dg|
 }n||d  }||
 }||| }|d7 }||	k rl|| }|| dkrP|dg|  n|| }||d  }||||  |d7 }||	k s<|||d   }
|
dkr||	 dkr|dg|
  |S || }||
 }||||  |S )a  Return the alignment contents of one row and consecutive columns (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[row, cols]

        where row is an integer and cols is a slice object with step 1.
        Return value is a string if the aligned sequences are string, Seq,
        or SeqRecord objects, otherwise the return value is a list.
        rg   r  Nr   r   r   )r  r   r:   r   r   rY   r   r   )r!   
coordinatestart_index
stop_indexr   r   r   r   r   r   r(   r   startstopr   r$   r$   r%   _get_row_cols_slice  s   
B>
	($



	
zAlignment._get_row_cols_slicec                    s`  z|j }W n	 ty   Y nw t|ttfrdd |d }t|dd |D ]\}}||k r8 t||| 7  n d| 7  |}q%zd fdd|D  W  S  tyX     tyc   t	ddw g  |d }t|dd |D ]\}}||k r 
|||  n 
dg|  |}qsz fd	d
|D  W  S  ty     ty   t	ddw )a  Return the alignment contents of one row and multiple columns (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[row, cols]

        where row is an integer and cols is an iterable of integers.
        Return value is a string if the aligned sequences are string, Seq,
        or SeqRecord objects, otherwise the return value is a list.
        rr   r   r   Nr   c                 3   r   rB   r$   rE   r!  r   r$   r%   rH   
  rv   z3Alignment._get_row_cols_iterable.<locals>.<genexpr>?second index must be an integer, slice, or iterable of integersc                    r   r$   r$   r)  r*  r$   r%   r     r   z4Alignment._get_row_cols_iterable.<locals>.<listcomp>)r:   r   r   rY   r   ri   rN   r  	Exceptionr   r   )r!   r#  colsr   r   r&  endr   r$   r*  r%   _get_row_cols_iterable  sX   
z Alignment._get_row_cols_iterablec                 C   sx   |  }|j|dd}|| | }d}	t|||D ] \}
}}|| dkr)|	d7 }	q|| ||  | }|	|
| 7 }	q|	S )a  Return the alignment contents of multiple rows and one column (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[rows, col]

        where rows is a slice object, and col is an integer.
        Return value is a string.
        rg   r  rr   r   r   )r  r   ri   )r!   r   r!  r   r   r   r   r   r   r   r   r#  r   ry   r$   r$   r%   _get_rows_col$  s   

zAlignment._get_rows_colc              	   C   s  t j|| j| kdd}| }|j|dd}	|	||	d j|dd d }
|dd|	f ||	  | }|dd|	f  ||dd|	f dk 7  < ||
d  | }|dd|
f  ||dd|
d f dk 8  < |dd|	|
d f }| j| }t|||D ]\}}}|rt||dd  |dd< qt||}t 	| j|rz| j
|_
W n	 ty   Y nw z| j}W n
 ty   Y |S w i |_| D ]\}}||| }z| }W n	 ty   Y nw ||j|< q|S )a  Return a subalignment of multiple rows and consecutive columns (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[rows, cols]

        where rows is an arbitrary slice object, and cols is a slice object
        with step 1, allowing the alignment sequences to be reused in the
        subalignment. Return value is an Alignment object.
        r   r   rg   r  Nrf   r   )r   anyr   r  r   r   ri   r)   r   r  r  r   r    rj   r   )r!   r   r   r$  r%  r   r   rcsr   r   r   r   r   r#  rcr   r   r    r   r-   r$   r$   r%   _get_rows_cols_slice:  sJ   ,0


zAlignment._get_rows_cols_slicec              	      s  t |}g }t|D ]m\}}	z|	j}
W n ty   |	}
Y nw d ||df }t|| |D ]\}}|rE|| } t|
|| 7  |}q. d| 7  q.zd fdd|D  W n tyb     tym   t	ddw  
  |  q
| |\}}t|D ]5\}}	||  z|	j}
W n ty   t|	tr  }	n|	 }	Y nw t|	}	|
 |	_|	||< qt||}z| j}W n
 ty   Y |S w i |_| D ]"\}fdd|D }ttrd|n||j|< q|S )	at  Return a subalignment of multiple rows and columns (PRIVATE).

        This method is called by __getitem__ for invocations of the form

        self[rows, cols]

        where rows is a slice object and cols is an iterable of integers.
        This method will create new sequences for use by the subalignment
        object. Return value is an Alignment object.
        rr   r   r   c                 3   r   rB   r$   rE   ry   r*  r$   r%   rH     rv   z4Alignment._get_rows_cols_iterable.<locals>.<genexpr>r+  Nc                 3   r   rB   r$   r5  r   r$   r%   rH     rv   )r  r   r:   r   ri   rY   rN   r  r,  r   r   rM   r   r   decoder;   r   deepcopyr   r    rj   )r!   r   r!  r   r   r   r   rP   r   r   srm   r   r   r   r   r   r    r   valuesr$   )r   r-   r%   _get_rows_cols_iterablek  st   











z!Alignment._get_rows_cols_iterablec              	   C   s  t |tjr| |S t |tr| |S t| j}| j	 }t
|d}t|dkddk}t|D ]V\}}|||f }|dk rCq2|dk r||ddf  ||ddf< t|||ddf  ||ddf< t|||< z|j|| _W q2 ty   Y q2w td| |d}	||	k|dkB  stdt|	}
t |trz|\}}W n ty   tdw tdt |tjr|dk r||
7 }|dk s||
krtd||
f || }t |tjr3|| }t |tjr| ||df |||	|S ||ddf }t |tr+||
\}}}||k r%|dkr%| |||||	|S t|||}| |||	|S t |tr|| }|| }t |tjrQ| ||||	|S t |try||
\}}}||k rs|dkrs| ||||||	S t|||}| ||||	|S td	)
a|  Return self[key].

        Indices of the form

        self[:, :]

        return a copy of the Alignment object;

        self[:, i:]
        self[:, :j]
        self[:, i:j]
        self[:, iterable] (where iterable returns integers)

        return a new Alignment object spanning the selected columns;

        self[k, i]
        self[k, i:]
        self[k, :j]
        self[k, i:j]
        self[k, iterable] (where iterable returns integers)
        self[k] (equivalent to self[k, :])

        return a string with the aligned sequence (including gaps) for the
        selected columns, where k = 0 represents the target and k = 1
        represents the query sequence; and

        self[:, i]

        returns a string with the selected column in the alignment.

        >>> from Bio.Align import PairwiseAligner
        >>> aligner = PairwiseAligner()
        >>> alignments = aligner.align("ACCGGTTT", "ACGGGTT")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 ACCGG-TTT 8
                          0 ||-||-||- 9
        query             0 AC-GGGTT- 7
        <BLANKLINE>
        >>> alignment[0, :]
        'ACCGG-TTT'
        >>> alignment[1, :]
        'AC-GGGTT-'
        >>> alignment[0]
        'ACCGG-TTT'
        >>> alignment[1]
        'AC-GGGTT-'
        >>> alignment[0, 1:-2]
        'CCGG-T'
        >>> alignment[1, 1:-2]
        'C-GGGT'
        >>> alignment[0, (1, 5, 2)]
        'C-C'
        >>> alignment[1, ::2]
        'A-GT-'
        >>> alignment[1, range(0, 9, 2)]
        'A-GT-'
        >>> alignment[:, 0]
        'AA'
        >>> alignment[:, 5]
        '-G'
        >>> alignment[:, 1:]  # doctest:+ELLIPSIS
        <Alignment object (2 rows x 8 columns) at 0x...>
        >>> print(alignment[:, 1:])
        target            1 CCGG-TTT 8
                          0 |-||-||- 8
        query             1 C-GGGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 2:])
        target            2 CGG-TTT 8
                          0 -||-||- 7
        query             2 -GGGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 3:])
        target            3 GG-TTT 8
                          0 ||-||- 6
        query             2 GGGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 3:-1])
        target            3 GG-TT 7
                          0 ||-|| 5
        query             2 GGGTT 7
        <BLANKLINE>
        >>> print(alignment[:, ::2])
        target            0 ACGTT 5
                          0 |-||- 5
        query             0 A-GT- 3
        <BLANKLINE>
        >>> print(alignment[:, range(1, 9, 2)])
        target            0 CG-T 3
                          0 ||-| 4
        query             0 CGGT 4
        <BLANKLINE>
        >>> print(alignment[:, (2, 7, 3)])
        target            0 CTG 3
                          0 -|| 3
        query             0 -TG 2
        <BLANKLINE>
        r   r   Nr   r   z0only tuples of length 2 can be alignment indicesz5alignment indices must be integers, slices, or tuplesz-column index %d is out of bounds (%d columns)z'first index must be an integer or slice) r   numbersIntegralr  rx   r  r   r   r   r   r   r   r   r   r   r)   r   r=   r   r   r   r  r   r  r"  r   r(  r   r/  r0  r4  r:  )r!   r   r   r   r   r   r   r   r   r   r   r!  r#  r$  r%  r   r$   r$   r%   r|     s   d




$


	
zAlignment.__getitem__c                 C   s   t |ttfr| S t |tr|S t |trt|S z|j}W t|S  ty,   Y nw zt|}W n
 t	y=   Y dS w |j
dkrGt|S dS )zHConvert given sequence to string using the appropriate method (PRIVATE).r   N)r   r   	bytearrayr6  rY   r   r:   r   
memoryviewr   format)r!   r   viewr$   r$   r%   _convert_sequence_stringd  s*   


z"Alignment._convert_sequence_stringc                 C   s
   |  |S )zkReturn the alignment as a string in the specified file format.

        Wrapper for self.format().
        r?  )r!   rZ   r$   r$   r%   r\   {  s   
zAlignment.__format__rr   c                 O   sz   |dkr|   S t|}|jjdkrt| dz|jdg|R i |}W n ty7   td| ddw || S )a  Return the alignment as a string in the specified file format.

        Arguments:
         - fmt       - File format. Acceptable values are an empty string to
                       create a human-readable representation of the alignment,
                       or any of the alignment file formats supported by
                       `Bio.Align` (some have not yet been implemented).

        All other arguments are passed to the format-specific writer functions:
         - mask      - PSL format only. Specify if repeat regions in the target
                       sequence are masked and should be reported in the
                       `repMatches` field of the PSL file instead of in the
                       `matches` field. Acceptable values are
                       None   : no masking (default);
                       "lower": masking by lower-case characters;
                       "upper": masking by upper-case characters.
         - wildcard  - PSL format only. Report alignments to the wildcard
                       character in the target or query sequence in the
                       `nCount` field of the PSL file instead of in the
                       `matches`, `misMatches`, or `repMatches` fields.
                       Default value is 'N'.
         - md        - SAM format only. If True, calculate the MD tag from
                       the alignment and include it in the output. If False
                       (default), do not include the MD tag in the output.
        rr   bz is a binary file formatNz;Formatting alignments has not yet been implemented for the  format)_format_pretty_loadAlignmentIteratormoder   AlignmentWriterr   format_alignment)r!   fmtargskwargsmodulewriterr$   r$   r%   r?    s   

zAlignment.formatc           5   	      s  t | j}|dkrd}nd}t| jd}t|dkddk}d}g }g }t| jjt}t	t
| j| j|D ]\}	\}
}}z|
j}|du rGtW n tya   |dkr]|	dkrZd}nd	}nd
}Y n	w |d|d  }||}|| z|
j}
W n	 ty   Y nw t|}t|}|
|| }
||	|f }t |dkr||	 }t|dkt|dk krt|}|| |dd< n||	ddf  ||	ddf< t|
}
t|}|| |dd< t|
tr|
 s|    S nCt|
ttfr&zt|
}
W n) ty    td||  }|
jD ]\}}t|
|| |||< q
|}
Y nw |
 }
n|    S ||
 q6|d}|d}t| |k||}t	|D ]E\}	}t|}|dk|@ }|| }|| }||k  rjqJd| |k  r|dd  d9  < d!||	 d ||	< d}qJt"dd}d}d}g  |ddddf |ddddf  }|d}|d}t| |k||}t
||| j|D ]\}}
}}|d }|}|d }t
||dd |dd D ]\}}}|dk r-|| |k r%t|}|t | d }|dk r d  d|| d d  7  < n
 d  d| 7  < |}|}|}q||kr7d| }n|
|| }|t | |kr|| }|dkr d  |d| 7  < ||d }||kr|| t#|| krt|}n|d  }||k r||7 }n||8 }||7 }|} t|}|t | d }|dk r| d|| d d  7 } n| d| | 7 } | d7 }  |  || }|t | |ksF d  |7  < ||kr|}|}|t |7 }qq|du rd}!d}"t  d  d }# d }$g }%t
|#|$D ]U\}&}'|&|| d }(|'|| d })d
}*t
|(|)D ]'\}+},|+|,kr5|+dkr2 nd}-n|+|!ks?|,|!krBd}-nd}-|*|-7 }*q"d|"|*f }.|%|. |"t |*7 }"qt ttt| jdddf |"}/||/ |kr|| |k rd|/ d}0|#d  |0| jd  7  < |$d  |0| jd  7  < |%d  |0|" 7  < n3|\}1}2d}0|1t$| jd d } |#|  |0d|"f } |%|  |0|2| jd f } |$|   d
 d!d d! t
|#|$|%D S t  | t tt| jdddf }/||/ |k r<|| |k r/d|/ d}0t%|D ]}	 d |	    |0| j|	df  7  < q fd"d#t%D }3n7 fd$d#t%D }3g  d}0t%|D ]}	||	 t$| j|	df d }  |  qPd! d }4|3|4 d!|3S )%[Return default string representation (PRIVATE).

        Helper for self.format().
        rp   TFr   r   
   Nr  r  rr      ?r7   z  zInconsistent coordinatesP   rK   z ..r6   r   r8   |.z          %9d %sz %dr   rK   r   rK   z%s%9d9dz
          rL   c                 s   s,    | ]\}}}| d | d | d V  qdS rL   Nr$   )rE   line1line2pattern_liner$   r$   r%   rH   d	  s
    
z+Alignment._format_pretty.<locals>.<genexpr>c                    $   g | ]}d   |d d  qS rZ  rN   rE   r   rP   r   r$   r%   r   p	     $ z,Alignment._format_pretty.<locals>.<listcomp>c                    r^  rZ  r_  r`  ra  r$   r%   r   r	  rb  )&r)   r   r   r   r   r   r   r   rw   r   ri   r=   r   ljustrM   r:   minr   r   r   rY   isascii_format_unicoder   r   r   r   r=  defined_rangesr6  _format_generalizedwherer   rN   r   absr?  r   )5r!   r   write_patternr   r   
name_widthnamesseqsr   r   r:   	positionsr   namer&  r.  r  r8  minstepmaxstep	row_stepsrow_alignedprefix_widthposition_width
line_widthcolumnr$  r   	end_indexposition_textr   restr   dashpositionlines1lines2pattern_linesr[  r\  aligned_seq1aligned_seq2patternc1c2r   r]  final_position_widthrK  name1name2blocksblockr$   ra  r%   rE    s  
	







(

&

$










1


$





.

zAlignment._format_prettyc              	   C   s  g }g }| j  }t| j|D ]f\}}| |}|du r"|    S |d |d kr<t||dd  |dd< t|}|| z|j	}W n t
yd   t| jdkr`t|dkr]d}nd}nd}Y nw |dd }|d	}|| qt|d
d}g }t||D ]2\}}d}	|d }
t||d
d D ]\}}||
kr|	d| 7 }	n|	||
| 7 }	|}
q||	 qt|dkrd|d S |\}}d}t||D ]\}}||krd}n|dks|dkrd}nd}||7 }q| d| d| dS )rP  Nr   rK   rp   r  r  rr   	   rQ  r   r   rL   rT  rU  )r   r   ri   r   rA  rh  r)   r   rM   r=   r   rc  r   r   r   rN   )r!   rn  rm  r   r:   r   rp  r   aligned_seqsaligned_seqr&  r   r.  r  r  r  r  r  r   r$   r$   r%   rf  |	  s^   



	

zAlignment._format_unicodec                 C   s  | j \}}g }g }g }| jdddf \}}|dks|dkrk||krG|d||  D ]}t|}	dt|	 }
||
 ||	 ||
 q*n$|d||  D ]}t|}
dt|
 }	||
 ||	 ||	 qO|}|}| jddddf  D ]\}}||kr||| D ]}t|}	dt|	 }
||
 ||	 ||
 q|}q|||kr||| D ]}t|}
dt|
 }	||
 ||	 ||	 q|}q|||| }||| }t|t|krtdt||D ]a\}}t|}
t|}	t|
}t|	}||krd}nd}||k r&|| d }|
|7 }
||| |  n ||kr?|| d }|	|7 }	||| |  n|||  ||
 ||	 q|}|}q|d|}d|}d|}| d	| d	| d	S )
zgReturn generalized string representation (PRIVATE).

        Helper for self._format_pretty().
        Nr   r6   r   r   r   rT  rU  rL   )	r   r   rY   r)   rM   r   r   ri   rN   )r!   r   r   r  r  r  r   r   r  s2s1r  r   r   t1t2m1m2pspacer$   r$   r%   rh  	  s   




"










zAlignment._format_generalizedc                 C   s   |   S )a  Return a human-readable string representation of the alignment.

        For sequence alignments, each line has at most 80 columns.
        The first 10 columns show the (possibly truncated) sequence name,
        which may be the id attribute of a SeqRecord, or otherwise 'target'
        or 'query' for pairwise alignments.
        The next 10 columns show the sequence coordinate, using zero-based
        counting as usual in Python.
        The remaining 60 columns shown the sequence, using dashes to represent
        gaps.
        At the end of the alignment, the end coordinates are shown on the right
        of the sequence, again in zero-based coordinates.

        Pairwise alignments have an additional line between the two sequences
        showing whether the sequences match ('|') or mismatch ('.'), or if
        there is a gap ('-').
        The coordinates shown for this line are the column indices, which can
        be useful when extracting a subalignment.

        For example,

        >>> from Bio.Align import PairwiseAligner
        >>> aligner = PairwiseAligner()

        >>> seqA = "TTAACCCCATTTG"
        >>> seqB = "AAGCCCCTTT"
        >>> seqC = "AAAGGGGCTT"

        >>> alignments = aligner.align(seqA, seqB)
        >>> len(alignments)
        1
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 TTAA-CCCCATTTG 13
                          0 --||-||||-|||- 14
        query             0 --AAGCCCC-TTT- 10
        <BLANKLINE>

        Note that seqC is the reverse complement of seqB. Aligning it to the
        reverse strand gives the same alignment, but the query coordinates are
        switched:

        >>> alignments = aligner.align(seqA, seqC, strand="-")
        >>> len(alignments)
        1
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 TTAA-CCCCATTTG 13
                          0 --||-||||-|||- 14
        query            10 --AAGCCCC-TTT-  0
        <BLANKLINE>

        rB  rG   r$   r$   r%   rQ   
  s   6zAlignment.__str__c                 C   s@   | j du rd| jjt| f S | j\}}d| jj||t| f S )a  Return a representation of the alignment, including its shape.

        The representation cannot be used with eval() to recreate the object,
        which is usually possible with simple python objects.  For example:

        <Alignment object (2 rows x 14 columns) at 0x10403d850>

        The hex string is the memory address of the object and can be used to
        distinguish different Alignment objects.  See help(id) for more
        information.

        >>> import numpy as np
        >>> from Bio.Align import Alignment
        >>> alignment = Alignment(("ACCGT", "ACGT"),
        ...                       coordinates = np.array([[0, 2, 3, 5],
        ...                                               [0, 2, 2, 4],
        ...                                              ]))
        >>> print(alignment)
        target            0 ACCGT 5
                          0 ||-|| 5
        query             0 AC-GT 4
        <BLANKLINE>
        >>> alignment  # doctest:+ELLIPSIS
        <Alignment object (2 rows x 5 columns) at 0x...>
        Nz<%s object at 0x%x>z*<%s object (%i rows x %i columns) at 0x%x>)r   r;   r<   r=   r   r!   r   r   r$   r$   r%   rR   9
  s   

zAlignment.__repr__c                 C   r]   )z0Return the number of sequences in the alignment.)r)   r   rG   r$   r$   r%   r`   `
  s   
zAlignment.__len__c                 C   s   t | j}|dkrdS t| jd}t|dkddk}t|D ]+}|||f }|dk r.q|dk rD||ddf  ||ddf< qtd| |d}||k|dkB  s^tdt	t|S )a  Return the alignment length, i.e. the number of columns when printed..

        The alignment length is the number of columns in the alignment when it
        is printed, and is equal to the sum of the number of matches, number of
        mismatches, and the total length of gaps in the target and query.
        Sequence sections beyond the aligned segment are not included in the
        number of columns.

        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = "global"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 -GACCT-G 6
                          0 -||--|-| 8
        query             0 CGA--TCG 6
        <BLANKLINE>
        >>> alignment.length
        8
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACCT-G 6
                          0 ||--|-| 7
        query             1 GA--TCG 6
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.length
        7
        r   r   Nr   r   )
r)   r   r   r   r   r   r   r   r   rw   )r!   r   r   r   r   r   r   r$   r$   r%   r(   d
  s    
% 
zAlignment.lengthc                 C   s   t | j}| j}||fS )a  Return the shape of the alignment as a tuple of two integer values.

        The first integer value is the number of sequences in the alignment as
        returned by len(alignment), which is always 2 for pairwise alignments.

        The second integer value is the number of columns in the alignment when
        it is printed, and is equal to the sum of the number of matches, number
        of mismatches, and the total length of gaps in the target and query.
        Sequence sections beyond the aligned segment are not included in the
        number of columns.

        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = "global"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 -GACCT-G 6
                          0 -||--|-| 8
        query             0 CGA--TCG 6
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.shape
        (2, 8)
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACCT-G 6
                          0 ||--|-| 7
        query             1 GA--TCG 6
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.shape
        (2, 7)
        )r)   r   r(   r  r$   r$   r%   r   
  s   
*zAlignment.shapec                 C   s  t | jdkrtd| j }t|d}t|dkddk}t| jD ]?\}}|||f }|dk	 r5q$|dk	 r]||ddf  ||ddf< t |||ddf  ||ddf< q$t
d| | }tj|dd}t|d}t|}||ddf }||d ddf }	tj||	gdd }
t| jd}t| jD ]0\}}|||f }|dk	 rq|dk	 rt ||
|ddf  |
|ddf< qt
d| |
S )a	  Return the indices of subsequences aligned to each other.

        This property returns the start and end indices of subsequences
        in the target and query sequence that were aligned to each other.
        If the alignment between target (t) and query (q) consists of N
        chunks, you get two tuples of length N:

            (((t_start1, t_end1), (t_start2, t_end2), ..., (t_startN, t_endN)),
             ((q_start1, q_end1), (q_start2, q_end2), ..., (q_startN, q_endN)))

        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> alignments = aligner.align("GAACT", "GAT")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GAACT 5
                          0 ||--| 5
        query             0 GA--T 3
        <BLANKLINE>
        >>> alignment.aligned
        array([[[0, 2],
                [4, 5]],
        <BLANKLINE>
               [[0, 2],
                [2, 3]]])
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            0 GAACT 5
                          0 |-|-| 5
        query             0 G-A-T 3
        <BLANKLINE>
        >>> alignment.aligned
        array([[[0, 1],
                [2, 3],
                [4, 5]],
        <BLANKLINE>
               [[0, 1],
                [1, 2],
                [2, 3]]])

        Note that different alignments may have the same subsequences
        aligned to each other. In particular, this may occur if alignments
        differ from each other in terms of their gap placement only:

        >>> aligner.mismatch_score = -10
        >>> alignments = aligner.align("AAACAAA", "AAAGAAA")
        >>> len(alignments)
        2
        >>> print(alignments[0])
        target            0 AAAC-AAA 7
                          0 |||--||| 8
        query             0 AAA-GAAA 7
        <BLANKLINE>
        >>> alignments[0].aligned
        array([[[0, 3],
                [4, 7]],
        <BLANKLINE>
               [[0, 3],
                [4, 7]]])
        >>> print(alignments[1])
        target            0 AAA-CAAA 7
                          0 |||--||| 8
        query             0 AAAG-AAA 7
        <BLANKLINE>
        >>> alignments[1].aligned
        array([[[0, 3],
                [4, 7]],
        <BLANKLINE>
               [[0, 3],
                [4, 7]]])

        The property can be used to identify alignments that are identical
        to each other in terms of their aligned sequences.
        rp   z=aligned is currently implemented for pairwise alignments onlyr   r   Nr   r   )r)   r   rh   r   r   r   r   r   r   r   r   r   rj  rd  flatnonzerostack)r!   r   r   r   r   r   r   r   startsendssegmentsr$   r$   r%   r   
  s>   N
&
&zAlignment.alignedc                 C   sn  t | jt }| jj\}}t | jd}t|dkddk}|dd|f }t |t}t	|D ] \}}|dk
 r?d||< q0|dk
 rJd||< q0td| d}d}	| jdddf }
td|D ]Q}|
}| jdd|f }
t|||
|D ]:\}}}}|dkr||k r|| | }	t|||||	< qw|dkr||kr|| | }	t|d |d d|||	< qw|	}qc|S )a  Return the sequence index of each lettter in the alignment.

        This property returns a 2D NumPy array with the sequence index of each
        letter in the alignment. Gaps are indicated by -1.  The array has the
        same number of rows and columns as the alignment, as given by
        `self.shape`.

        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = "local"

        >>> alignments = aligner.align("GAACTGG", "AATG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            1 AACTG 6
                          0 ||-|| 5
        query             0 AA-TG 4
        <BLANKLINE>
        >>> alignment.indices
        array([[ 1,  2,  3,  4,  5],
               [ 0,  1, -1,  2,  3]])
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            1 AACTGG 7
                          0 ||-|-| 6
        query             0 AA-T-G 4
        <BLANKLINE>
        >>> alignment.indices
        array([[ 1,  2,  3,  4,  5,  6],
               [ 0,  1, -1,  2, -1,  3]])

        >>> alignments = aligner.align("GAACTGG", "CATT", strand="-")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            1 AACTG 6
                          0 ||-|| 5
        query             4 AA-TG 0
        <BLANKLINE>
        >>> alignment.indices
        array([[ 1,  2,  3,  4,  5],
               [ 3,  2, -1,  1,  0]])
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            1 AACTGG 7
                          0 ||-|-| 6
        query             4 AA-T-G 0
        <BLANKLINE>
        >>> alignment.indices
        array([[ 1,  2,  3,  4,  5,  6],
               [ 3,  2, -1,  1, -1,  0]])

        r   r   NFTr   rK   )r   onesr   rw   r   r   r   r   boolr   r   r   r   ri   )r!   ar   r   r   r   r2  r   r   r   r  rm   r  r&  r.  r3  r$   r$   r%   r   ;  s8   8

zAlignment.indicesc                 C   s  dd | j D }| jj\}}t| jd}t|dkddk}|dd|f }t|t}t|D ] \}}|dk	 r?d||< q0|dk	 rJd||< q0t
d| d}d}	t|d D ]o}
| jdd|
f }| jdd|
d f }t||||D ]O\}}}}|dkr||k r|| | }	t||	|||< qx|dkr||kr|| | }	|dkrt||	||d |d d	< qx|dkrt||	||d dd	< qx|	}q[|S )
a  Return the alignment column index for each letter in each sequence.

        This property returns a list of 1D NumPy arrays; the number of arrays
        is equal to the number of aligned sequences, and the length of each
        array is equal to the length of the corresponding sequence. For each
        letter in each sequence, the array contains the corresponding column
        index in the alignment. Letters not included in the alignment are
        indicated by -1.

        For example,

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = "local"

        >>> alignments = aligner.align("GAACTGG", "AATG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            1 AACTG 6
                          0 ||-|| 5
        query             0 AA-TG 4
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1,  0,  1,  2,  3,  4, -1]), array([0, 1, 3, 4])]
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            1 AACTGG 7
                          0 ||-|-| 6
        query             0 AA-T-G 4
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1,  0,  1,  2,  3,  4,  5]), array([0, 1, 3, 5])]
        >>> alignments = aligner.align("GAACTGG", "CATT", strand="-")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            1 AACTG 6
                          0 ||-|| 5
        query             4 AA-TG 0
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1,  0,  1,  2,  3,  4, -1]), array([4, 3, 1, 0])]
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            1 AACTGG 7
                          0 ||-|-| 6
        query             4 AA-T-G 0
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1,  0,  1,  2,  3,  4,  5]), array([5, 3, 1, 0])]

        c                 S   s   g | ]}t t|t qS r$   )r   r  r)   rw   r   r$   r$   r%   r     s    z-Alignment.inverse_indices.<locals>.<listcomp>r   r   NFTr   rK   )r   r   r   r   r   r   r   r  r   r   r   r   ri   )r!   r  r   r   r   r   r2  r   r   r   rm   r  r  r&  r.  r3  r$   r$   r%   inverse_indices  s<   5

zAlignment.inverse_indicesFc                    s   | j  du rz	dd D }W n ty   }Y n
w  fddD }ttt|j|d}fdd|D | _ | j|d| _dS )aG  Sort the sequences of the alignment in place.

        By default, this sorts the sequences alphabetically using their id
        attribute if available, or by their sequence contents otherwise.
        For example,

        >>> from Bio.Align import PairwiseAligner
        >>> aligner = PairwiseAligner()
        >>> aligner.gap_score = -1
        >>> alignments = aligner.align("AATAA", "AAGAA")
        >>> len(alignments)
        1
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 AATAA 5
                          0 ||.|| 5
        query             0 AAGAA 5
        <BLANKLINE>
        >>> alignment.sort()
        >>> print(alignment)
        target            0 AAGAA 5
                          0 ||.|| 5
        query             0 AATAA 5
        <BLANKLINE>

        Alternatively, a key function can be supplied that maps each sequence
        to a sort value.  For example, you could sort on the GC content of each
        sequence.

        >>> from Bio.SeqUtils import gc_fraction
        >>> alignment.sort(key=gc_fraction)
        >>> print(alignment)
        target            0 AATAA 5
                          0 ||.|| 5
        query             0 AAGAA 5
        <BLANKLINE>

        You can reverse the sort order by passing `reverse=True`:

        >>> alignment.sort(key=gc_fraction, reverse=True)
        >>> print(alignment)
        target            0 AAGAA 5
                          0 ||.|| 5
        query             0 AATAA 5
        <BLANKLINE>

        The sequences are now sorted by decreasing GC content value.
        Nc                 S   s   g | ]}|j qS r$   r~   r   r$   r$   r%   r     s    z"Alignment.sort.<locals>.<listcomp>c                    s   g | ]} |qS r$   r$   r   )r   r$   r%   r     r   r   c                    r   r$   r$   r5  r   r$   r%   r      r   r   )r   r   r   r   r)   r|   r   take)r!   r   r   r9  r   r$   )r   r   r%   r     s   1zAlignment.sortc           "      C   sZ  | |}}t |jt |jkrtdt |jt |jf |j}|j}|j}|j}t |j}t |j}	t|d}
tt|
d}|dk	 rKd}n|dk	 rTd}ntdt|d}tt|d}|dk	 rpd}n|dk	 ryd}ntd|dkr|dkr|
 }|	|dddf  |dddf< nN|
 }||dddf  |dddf< |
 }||dddd	f  |dddf< |dkr|	|dddd	f  |dddf< n|dddd	f |dddf< t|d}
|
d}|
|k|
dkB 	 std
t|d}|d}||k|dkB 	 stdg }tjtj}}t| }tjtj}}|D ]\}}||k rD||k rD n||}}q4tjtj}}| D ]\}}||k r||k r	 ||k ry||k rt|| }n|| }nt||k r|| }||k r|| }n|| }|}|| }||ks||kr||kr||kr|||g |||g || }|| }|||g n%||}}|D ]\}}||k r||k r n||}}q|| }nqe||7 }||7 }||k r||k sd||}}qVt| } ||kr"|	| dddf  | dddf< ||g}!t|!| }|S )a  Map the alignment to self.target and return the resulting alignment.

        Here, self.query and alignment.target are the same sequence.

        A typical example is where self is the pairwise alignment between a
        chromosome and a transcript, the argument is the pairwise alignment
        between the transcript and a sequence (e.g., as obtained by RNA-seq),
        and we want to find the alignment of the sequence to the chromosome:

        >>> from Bio import Align
        >>> aligner = Align.PairwiseAligner()
        >>> aligner.mode = 'local'
        >>> aligner.open_gap_score = -1
        >>> aligner.extend_gap_score = 0
        >>> chromosome = "AAAAAAAACCCCCCCAAAAAAAAAAAGGGGGGAAAAAAAA"
        >>> transcript = "CCCCCCCGGGGGG"
        >>> alignments1 = aligner.align(chromosome, transcript)
        >>> len(alignments1)
        1
        >>> alignment1 = alignments1[0]
        >>> print(alignment1)
        target            8 CCCCCCCAAAAAAAAAAAGGGGGG 32
                          0 |||||||-----------|||||| 24
        query             0 CCCCCCC-----------GGGGGG 13
        <BLANKLINE>
        >>> sequence = "CCCCGGGG"
        >>> alignments2 = aligner.align(transcript, sequence)
        >>> len(alignments2)
        1
        >>> alignment2 = alignments2[0]
        >>> print(alignment2)
        target            3 CCCCGGGG 11
                          0 ||||||||  8
        query             0 CCCCGGGG  8
        <BLANKLINE>
        >>> alignment = alignment1.map(alignment2)
        >>> print(alignment)
        target           11 CCCCAAAAAAAAAAAGGGG 30
                          0 ||||-----------|||| 19
        query             0 CCCC-----------GGGG  8
        <BLANKLINE>
        >>> format(alignment, "psl")
        '8\t0\t0\t0\t0\t0\t1\t11\t+\tquery\t8\t0\t8\ttarget\t40\t11\t30\t2\t4,4,\t0,4,\t11,26,\n'

        Mapping the alignment does not depend on the sequence contents. If we
        delete the sequence contents, the same alignment is found in PSL format
        (though we obviously lose the ability to print the sequence alignment):

        >>> alignment1.target = Seq(None, len(alignment1.target))
        >>> alignment1.query = Seq(None, len(alignment1.query))
        >>> alignment2.target = Seq(None, len(alignment2.target))
        >>> alignment2.query = Seq(None, len(alignment2.query))
        >>> alignment = alignment1.map(alignment2)
        >>> format(alignment, "psl")
        '8\t0\t0\t0\t0\t0\t1\t11\t+\tquery\t8\t0\t8\ttarget\t40\t11\t30\t2\t4,4,\t0,4,\t11,26,\n'

        The map method can also be used to lift over an alignment between
        different genome assemblies. In this case, self is a DNA alignment
        between two genome assemblies, and the argument is an alignment of a
        transcript against one of the genome assemblies:

        >>> np.set_printoptions(threshold=5)  # print 5 array elements per row
        >>> chain = Align.read("Blat/panTro5ToPanTro6.over.chain", "chain")
        >>> chain.sequences[0].id
        'chr1'
        >>> len(chain.sequences[0].seq)
        228573443
        >>> chain.sequences[1].id
        'chr1'
        >>> len(chain.sequences[1].seq)
        224244399
        >>> print(chain.coordinates)
        [[122250000 122250400 122250400 ... 122909818 122909819 122909835]
         [111776384 111776784 111776785 ... 112019962 112019962 112019978]]

        showing that the range 122250000:122909835 of chr1 on chimpanzee genome
        assembly panTro5 aligns to range 111776384:112019978 of chr1 of
        chimpanzee genome assembly panTro6.

        >>> alignment = Align.read("Blat/est.panTro5.psl", "psl")
        >>> alignment.sequences[0].id
        'chr1'
        >>> len(alignment.sequences[0].seq)
        228573443
        >>> alignment.sequences[1].id
        'DC525629'
        >>> len(alignment.sequences[1].seq)
        407
        >>> print(alignment.coordinates)
        [[122835789 122835847 122840993 122841145 122907212 122907314]
         [       32        90        90       242       242       344]]

        This shows that nucleotide range 32:344 of expressed sequence tag
        DC525629 aligns to range 122835789:122907314 of chr1 of chimpanzee
        genome assembly panTro5.

        Note that the target sequence chain.sequences[0].seq and the target
        sequence alignment.sequences[0] have the same length:

        >>> len(chain.sequences[0].seq) == len(alignment.sequences[0].seq)
        True

        We swap the target and query of the chain such that the query of the
        chain corresponds to the target of alignment:

        >>> chain = chain[::-1]
        >>> chain.sequences[0].id
        'chr1'
        >>> len(chain.sequences[0].seq)
        224244399
        >>> chain.sequences[1].id
        'chr1'
        >>> len(chain.sequences[1].seq)
        228573443
        >>> print(chain.coordinates)
        [[111776384 111776784 111776785 ... 112019962 112019962 112019978]
         [122250000 122250400 122250400 ... 122909818 122909819 122909835]]

        Now we can get the coordinates of DC525629 against chimpanzee genome
        assembly panTro6 by calling map on the chain, with alignment as the
        argument:

        >>> lifted_alignment = chain.map(alignment)
        >>> lifted_alignment.sequences[0].id
        'chr1'
        >>> len(lifted_alignment.sequences[0].seq)
        224244399
        >>> lifted_alignment.sequences[1].id
        'DC525629'
        >>> len(lifted_alignment.sequences[1].seq)
        407
        >>> print(lifted_alignment.coordinates)
        [[111982717 111982775 111987921 111988073 112009200 112009302]
         [       32        90        90       242       242       344]]

        This shows that nucleotide range 32:344 of expressed sequence tag
        DC525629 aligns to range 111982717:112009302 of chr1 of chimpanzee
        genome assembly panTro6. Note that the genome span of DC525629 on
        chimpanzee genome assembly panTro5 is 122907314 - 122835789 = 71525 bp,
        while on panTro6 the genome span is 112009302 - 111982717 = 26585 bp.
        zUlength of alignment1 query sequence (%d) != length of alignment2 target sequence (%d)r   r   +r   z)Inconsistent steps in the first alignmentz*Inconsistent steps in the second alignmentNrK   z%Unequal step sizes in first alignmentz&Unequal step sizes in second alignment)r)   r  r  r   r   r   r   prodsignr   r   r   sysmaxsizer^   r   rM   r   r   )"r!   r   r   r   r  r  r   r   n1n2steps1r   strand1steps2strand2gaps1gaps2pathtEndqEndtStart1qStart1tEnd1qEnd1tStart2qStart2tEnd2qEnd2sizer   qStarttStartr   r   r$   r$   r%   map#  s    


  "$








!$
 
zAlignment.mapc                 C   sR  d}t |}|D ]R}t|jd}t|dkddk}|dd|f }|d\}}||kr0d}n|| kr8d}n|d| krAd}n
td| d| |du rR|}q||krZtdqt| jddddf | jddddf  dd}t	d	t
|d ft}	d|	d
< |t| |	dddf< td|	d ddg}
t|D ]J\}}|| j|ddf  |	dddf< td|	d d|
d< t|
|	}|j }|dddf  |9  < |
d |jd g}t||}||||< qdd tt
|D }	d}|du rd}tdd |D }t|D ]~\}}|jjdkr(|	| |	| d  q|jd
 |krP|	| |jd  |jddddf |_|j rNd}q|jd
 |krt
|	| r|jd |	| d krp|| }nd}|	| |	| d |  q|	| |jd  qt|}|du sdd |D }
t|	}	t|
|	}|S )zDMap each of the alignments to self, and return the mapped alignment.Nr   r   r7   zunexpected steps z, z%inconsistent step sizes in alignmentsrK   rp   r   rW  r'   rX  c                 S   s   g | ]}g qS r$   r$   r   r$   r$   r%   r   ;  s    z$Alignment.mapall.<locals>.<listcomp>FTc                 s   s"    | ]}|j jr|j d  V  qdS )r   N)r   r  rE   r   r$   r$   r%   rH   ?  s    
z#Alignment.mapall.<locals>.<genexpr>)r   r   c                 S   s   g | ]}|j d  qS )r   r  r  r$   r$   r%   r   X  r   )r   r   r   r   r   r   rj  r   clipr   r)   rw   r  r   r   r   r   r   r  r   rd  r  rM   r1  r,  r   )r!   
alignmentsfactorr   r   r   step1step2r   r   r   r   r   r   r   r   doner}  previousr$   r$   r%   mapall  s~   
<"







zAlignment.mapallc                 C   sB  | j  }t| j}t| j d}t|dkddk}t|D ]6\}}|||f }|dk r/q|dk rNt	|||< t
|||ddf  ||ddf< qtd| t }|D ];}zt|}	W n- ty   z|j}W n	 tyw   Y nw |jD ]\}
}t||
| }	||	 q{Y qZw ||	 qZdt|}tj|dd}t
|}t|D ]r}|| }||ddf }t|d |D ]\}|| }||ddf }tjtj}}t||D ]A\}}||k r||k r||| }||| }t
|t
|krtdt||D ]\}}|||f  d	7  < q||}}qqq|S )
a-  Return an Array with the number of substitutions of letters in the alignment.

        As an example, consider a sequence alignment of two RNA sequences:

        >>> from Bio.Align import PairwiseAligner
        >>> target = "ATACTTACCTGGCAGGGGAGATACCATGATCACGAAGGTGGTTTTCCCAGGGCGAGGCTTATCCATTGCACTCCGGATGTGCTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACTGCATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTTTCCCCTG"  # human spliceosomal small nuclear RNA U1
        >>> query = "ATACTTACCTGACAGGGGAGGCACCATGATCACACAGGTGGTCCTCCCAGGGCGAGGCTCTTCCATTGCACTGCGGGAGGGTTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACTGTATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTATCCCCCG"  # sea lamprey spliceosomal small RNA U1
        >>> aligner = PairwiseAligner()
        >>> aligner.gap_score = -10
        >>> alignments = aligner.align(target, query)
        >>> len(alignments)
        1
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 ATACTTACCTGGCAGGGGAGATACCATGATCACGAAGGTGGTTTTCCCAGGGCGAGGCTT
                          0 |||||||||||.||||||||..|||||||||||..|||||||..|||||||||||||||.
        query             0 ATACTTACCTGACAGGGGAGGCACCATGATCACACAGGTGGTCCTCCCAGGGCGAGGCTC
        <BLANKLINE>
        target           60 ATCCATTGCACTCCGGATGTGCTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACT
                         60 .|||||||||||.|||..|.|.||||||||||||||||||||||||||||||||||||||
        query            60 TTCCATTGCACTGCGGGAGGGTTGACCCCTGCGATTTCCCCAAATGTGGGAAACTCGACT
        <BLANKLINE>
        target          120 GCATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTTTCCCCTG 164
                        120 |.||||||||||||||||||||||||||||||||||.|||||.| 164
        query           120 GTATAATTTGTGGTAGTGGGGGACTGCGTTCGCGCTATCCCCCG 164
        <BLANKLINE>
        >>> m = alignment.substitutions
        >>> print(m)
             A    C    G    T
        A 28.0  1.0  2.0  1.0
        C  0.0 39.0  1.0  2.0
        G  2.0  0.0 45.0  0.0
        T  2.0  5.0  1.0 35.0
        <BLANKLINE>

        Note that the matrix is not symmetric: rows correspond to the target
        sequence, and columns to the query sequence.  For example, the number
        of T's in the target sequence that are aligned to a C in the query
        sequence is

        >>> m['T', 'C']
        5.0

        and the number of C's in the query sequence tat are aligned to a T in
        the query sequence is

        >>> m['C', 'T']
        2.0

        For some applications (for example, to define a scoring matrix from
        the substitution matrix), a symmetric matrix may be preferred, which
        can be calculated as follows:

        >>> m += m.transpose()
        >>> m /= 2.0
        >>> print(m)
             A    C    G    T
        A 28.0  0.5  2.0  1.5
        C  0.5 39.0  0.5  3.5
        G  2.0  0.5 45.0  0.5
        T  1.5  3.5  0.5 35.0
        <BLANKLINE>

        The matrix is now symmetric, with counts divided equally on both sides
        of the diagonal:

        >>> m['C', 'T']
        3.5
        >>> m['T', 'C']
        3.5

        The total number of substitutions between T's and C's in the alignment
        is 3.5 + 3.5 = 7.
        r   r   Nr   rr   rp   r   r   r   )r   r   r   r   r   r   r   r   r   r   r)   r   r   r   r:   r   rg  r,   rN   r   r
   r   r   r  r  ri   )r!   r   r   r   r   r   r   r   r   r8  r&  r.  r   r   i1	sequence1r   i2	sequence2r   r   r   r   r   segment1segment2r  r  r$   r$   r%   r   ]  sd   
L
&
	zAlignment.substitutionsc           
      C   s   d } }}t | D ]7\}}t | D ].\}}||kr n%t||D ]\}}	|dks-|	dkr2|d7 }q!||	kr;|d7 }q!|d7 }q!qq
t|||S )a  Return number of identities, mismatches, and gaps of a pairwise alignment.

        >>> aligner = PairwiseAligner(mode='global', match_score=2, mismatch_score=-1)
        >>> for alignment in aligner.align("TACCG", "ACG"):
        ...     print("Score = %.1f:" % alignment.score)
        ...     c = alignment.counts()  # namedtuple
        ...     print(f"{c.gaps} gaps, {c.identities} identities, {c.mismatches} mismatches")
        ...     print(alignment)
        ...
        Score = 6.0:
        2 gaps, 3 identities, 0 mismatches
        target            0 TACCG 5
                          0 -||-| 5
        query             0 -AC-G 3
        <BLANKLINE>
        Score = 6.0:
        2 gaps, 3 identities, 0 mismatches
        target            0 TACCG 5
                          0 -|-|| 5
        query             0 -A-CG 3
        <BLANKLINE>

        This classifies each pair of letters in a pairwise alignment into gaps,
        perfect matches, or mismatches. It has been defined as a method (not a
        property) so that it may in future take optional argument(s) allowing
        the behavior to be customized. These three values are returned as a
        namedtuple. This is calculated for all the pairs of sequences in the
        alignment.
        r   r   r   )r   ri   r   )
r!   r   r   r   r   r   r   r   r  rC  r$   r$   r%   r     s   


zAlignment.countsc                 C   s   dd | j D }tdd t|| jD }t||}z| j}W n
 ty*   Y |S w i |_| D ] \}}t	|tj
rF|ddd  }n|ddd }||j|< q2|S )a  Reverse-complement the alignment and return it.

        >>> sequences = ["ATCG", "AAG", "ATC"]
        >>> coordinates = np.array([[0, 2, 3, 4], [0, 2, 2, 3], [0, 2, 3, 3]])
        >>> alignment = Alignment(sequences, coordinates)
        >>> print(alignment)
                          0 ATCG 4
                          0 AA-G 3
                          0 ATC- 3
        <BLANKLINE>
        >>> rc_alignment = alignment.reverse_complement()
        >>> print(rc_alignment)
                          0 CGAT 4
                          0 C-TT 3
                          0 -GAT 3
        <BLANKLINE>

        The attribute `column_annotations`, if present, is associated with the
        reverse-complemented alignment, with its values in reverse order.

        >>> alignment.column_annotations = {"score": [3, 2, 2, 2]}
        >>> rc_alignment = alignment.reverse_complement()
        >>> print(rc_alignment.column_annotations)
        {'score': [2, 2, 2, 3]}
        c                 S   s   g | ]}t |qS r$   r   r   r$   r$   r%   r   !  r   z0Alignment.reverse_complement.<locals>.<listcomp>c                 S   s&   g | ]\}}t ||d d d  qS NrK   r   )rE   r   r   r$   r$   r%   r   #  s    NrK   )r   r   r   ri   r   r   r    r   rj   r   ndarrayr   )r!   r   r   r   r    r   r-   r$   r$   r%   r     s(   


	zAlignment.reverse_complementrB   )rr   r   )2r<   r   r   r   classmethodr   r   r&   r   ro   r   r  r  setterr  r  r  r  r  r  r  r  r  r"  r(  r/  r0  r4  r:  r|   rA  r\   r?  rE  rf  rh  rQ   rR   r`   r(   r   r   r   r  r   r  r  r   r   r   r$   r$   r$   r%   r     s    
)

3
/ 
X






;\31C 7
' T8M8'
7
-
p
U

T= vE
|-r   c                   @   s<   e Zd ZdZdd Zedd Zedd Zedd	 Zd
S )AlignmentsAbstractBaseClassaF  Abstract base class for sequence alignments.

    Most users will not need to use this class. It is used internally as a base
    class for the list-like Alignments class, and for the AlignmentIterator
    class in Bio.Align.interfaces, which itself is the abstract base class for
    the alignment parsers in Bio/Align/.
    c                 C   s   |    | S )zyIterate over the alignments as Alignment objects.

        This method SHOULD NOT be overridden by any subclass.
        )rewindrG   r$   r$   r%   r_   A  s   z$AlignmentsAbstractBaseClass.__iter__c                 C      dS )zReturn the next alignment.Nr$   rG   r$   r$   r%   __next__I      z$AlignmentsAbstractBaseClass.__next__c                 C   r  )zJRewind the iterator to let it loop over the alignments from the beginning.Nr$   rG   r$   r$   r%   r  M  r  z"AlignmentsAbstractBaseClass.rewindc                 C   r  )z Return the number of alignments.Nr$   rG   r$   r$   r%   r`   Q  r  z#AlignmentsAbstractBaseClass.__len__N)	r<   r   r   r   r_   r   r  r  r`   r$   r$   r$   r%   r  8  s    

r  c                       s6   e Zd Zd
 fdd	Zdd Zdd Zdd	 Z  ZS )
Alignmentsr$   c                    s   t  | d| _d S r  )superr&   _index)r!   r  r;   r$   r%   r&   W  s   
zAlignments.__init__c                 C   s4   | j d }z| | }W n	 ty   tw || _ |S Nr   )r  r  rc   )r!   ry   itemr$   r$   r%   r  [  s   
zAlignments.__next__c                 C   s
   d| _ d S r  )r  rG   r$   r$   r%   r  d     
zAlignments.rewindc                 C   s
   t | S rB   )r   r`   rG   r$   r$   r%   r`   g  r  zAlignments.__len__)r$   )r<   r   r   r&   r  r  r`   __classcell__r$   r$   r  r%   r  V  s
    	r  c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )PairwiseAlignmentsa<  Implements an iterator over pairwise alignments returned by the aligner.

    This class also supports indexing, which is fast for increasing indices,
    but may be slow for random access of a large number of alignments.

    Note that pairwise aligners can return an astronomical number of alignments,
    even for relatively short sequences, if they align poorly to each other. We
    therefore recommend to first check the number of alignments, accessible as
    len(alignments), which can be calculated quickly even if the number of
    alignments is very large.
    c                 C   s    ||g| _ || _|| _d| _dS )a5  Initialize a new PairwiseAlignments object.

        Arguments:
         - seqA  - The first sequence, as a plain string, without gaps.
         - seqB  - The second sequence, as a plain string, without gaps.
         - score - The alignment score.
         - paths - An iterator over the paths in the traceback matrix;
                   each path defines one alignment.

        You would normally obtain a PairwiseAlignments object by calling
        aligner.align(seqA, seqB), where aligner is a PairwiseAligner object
        or a CodonAligner object.
        rK   N)r   r  _pathsr  )r!   seqAseqBr  pathsr$   r$   r%   r&   x  s   

zPairwiseAlignments.__init__c                 C   r]   rB   )r)   r  rG   r$   r$   r%   r`     r  zPairwiseAlignments.__len__c                 C   s   t |tstd|jj |dk r|t| j7 }|| jkr!| jS || jk r.| j	  d| _	 zt
| }W n tyA   tdd w | j|krJ	 |S q/)Nzindex must be an integer, not r   rK   Tzindex out of range)r   rw   r   r;   r<   r)   r  r  
_alignmentresetrb   rc   r  )r!   ry   r   r$   r$   r%   r|     s&   





zPairwiseAlignments.__getitem__c                 C   s@   t | j}|  jd7  _t|}t| j|}| j|_|| _|S r  )	rb   r  r  r   r   r   r   r  r  )r!   r  r   r   r$   r$   r%   r    s   

zPairwiseAlignments.__next__c                 C   s   | j   d| _d S r  )r  r  r  rG   r$   r$   r%   r    s   

zPairwiseAlignments.rewindN)	r<   r   r   r   r&   r`   r|   r  r  r$   r$   r$   r%   r  k  s    	r  c                       sV   e Zd ZdZd fdd	Zdd Zd fdd		Zd fd
d	Zdd Zdd Z	  Z
S )PairwiseAligneraV  Performs pairwise sequence alignment using dynamic programming.

    This provides functions to get global and local alignments between two
    sequences.  A global alignment finds the best concordance between all
    characters in two sequences.  A local alignment finds just the
    subsequences that align the best.

    To perform a pairwise sequence alignment, first create a PairwiseAligner
    object.  This object stores the match and mismatch scores, as well as the
    gap scores.  Typically, match scores are positive, while mismatch scores
    and gap scores are negative or zero.  By default, the match score is 1,
    and the mismatch and gap scores are zero.  Based on the values of the gap
    scores, a PairwiseAligner object automatically chooses the appropriate
    alignment algorithm (the Needleman-Wunsch, Smith-Waterman, Gotoh, or
    Waterman-Smith-Beyer global or local alignment algorithm).

    Calling the "score" method on the aligner with two sequences as arguments
    will calculate the alignment score between the two sequences.
    Calling the "align" method on the aligner with two sequences as arguments
    will return a generator yielding the alignments between the two
    sequences.

    Some examples:

    >>> from Bio import Align
    >>> aligner = Align.PairwiseAligner()
    >>> alignments = aligner.align("TACCG", "ACG")
    >>> for alignment in sorted(alignments):
    ...     print("Score = %.1f:" % alignment.score)
    ...     print(alignment)
    ...
    Score = 3.0:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>
    Score = 3.0:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>

    Specify the aligner mode as local to generate local alignments:

    >>> aligner.mode = 'local'
    >>> alignments = aligner.align("TACCG", "ACG")
    >>> for alignment in sorted(alignments):
    ...     print("Score = %.1f:" % alignment.score)
    ...     print(alignment)
    ...
    Score = 3.0:
    target            1 ACCG 5
                      0 |-|| 4
    query             0 A-CG 3
    <BLANKLINE>
    Score = 3.0:
    target            1 ACCG 5
                      0 ||-| 4
    query             0 AC-G 3
    <BLANKLINE>

    Do a global alignment.  Identical characters are given 2 points,
    1 point is deducted for each non-identical character.

    >>> aligner.mode = 'global'
    >>> aligner.match_score = 2
    >>> aligner.mismatch_score = -1
    >>> for alignment in aligner.align("TACCG", "ACG"):
    ...     print("Score = %.1f:" % alignment.score)
    ...     print(alignment)
    ...
    Score = 6.0:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>
    Score = 6.0:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>

    Same as above, except now 0.5 points are deducted when opening a
    gap, and 0.1 points are deducted when extending it.

    >>> aligner.open_gap_score = -0.5
    >>> aligner.extend_gap_score = -0.1
    >>> aligner.target_end_gap_score = 0.0
    >>> aligner.query_end_gap_score = 0.0
    >>> for alignment in aligner.align("TACCG", "ACG"):
    ...     print("Score = %.1f:" % alignment.score)
    ...     print(alignment)
    ...
    Score = 5.5:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>
    Score = 5.5:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>

    The alignment function can also use known matrices already included in
    Biopython:

    >>> from Bio.Align import substitution_matrices
    >>> aligner = Align.PairwiseAligner()
    >>> aligner.substitution_matrix = substitution_matrices.load("BLOSUM62")
    >>> alignments = aligner.align("KEVLA", "EVL")
    >>> alignments = list(alignments)
    >>> print("Number of alignments: %d" % len(alignments))
    Number of alignments: 1
    >>> alignment = alignments[0]
    >>> print("Score = %.1f" % alignment.score)
    Score = 13.0
    >>> print(alignment)
    target            0 KEVLA 5
                      0 -|||- 5
    query             0 -EVL- 3
    <BLANKLINE>

    You can also set the value of attributes directly during construction
    of the PairwiseAligner object by providing them as keyword arguments:

    >>> aligner = Align.PairwiseAligner(mode='global', match_score=2, mismatch_score=-1)
    >>> for alignment in aligner.align("TACCG", "ACG"):
    ...     print("Score = %.1f:" % alignment.score)
    ...     print(alignment)
    ...
    Score = 6.0:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>
    Score = 6.0:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>

    Nc                    s   t    |du r
n9|dkrtd| _d| _d| _n(|dkr,td| _d| _d| _n|d	kr=td
| _d| _d| _ntd| | D ]
\}}t	| || qGdS )a  Initialize a PairwiseAligner as specified by the keyword arguments.

        If scoring is None, use the default scoring scheme match = 1.0,
        mismatch = 0.0, gap score = 0.0
        If scoring is "blastn", "megablast", or "blastp", use the default
        substitution matrix and gap scores for BLASTN, MEGABLAST, or BLASTP,
        respectively.

        Loops over the remaining keyword arguments and sets them as attributes
        on the object.
        NblastnBLASTNg      g       	megablast	MEGABLASTg      blastpBLASTPg      (g      zUnknown scoring scheme '%s')
r  r&   r
   loadsubstitution_matrixopen_gap_scoreextend_gap_scorer   rj   setattr)r!   scoringrM  rp  r-   r  r$   r%   r&   @  s&   
zPairwiseAligner.__init__c                 C   s.   |t tjvrtd| tj| || d S )Nz.'PairwiseAligner' object has no attribute '%s')dirr	   r  r   __setattr__)r!   r   r-   r$   r$   r%   r  d  s   zPairwiseAligner.__setattr__r  c           	         sr   t |tttfrt|}n|}|dkr|}nt|}t |tttfr&t|}t |||\}}t||||}|S )z=Return the alignments of two sequences using PairwiseAligner.r  )	r   r   r   r   r   r   r  alignr  )	r!   r  r  strandsAsBr  r  r  r  r$   r%   r  l  s   
zPairwiseAligner.alignc                    sP   t |tttfrt|}|dkrt|}t |tttfr t|}t |||S )zBReturn the alignment score of two sequences using PairwiseAligner.r   )r   r   r   r   r   r   r  r  )r!   r  r  r  r  r$   r%   r  |  s   zPairwiseAligner.scorec                 C   sn   | j | j| j| j| j| j| j| j| j| j	| j
| j| j| jd}| jd u r0| j|d< | j|d< |S | j|d< |S )N)wildcardtarget_internal_open_gap_score target_internal_extend_gap_scoretarget_left_open_gap_scoretarget_left_extend_gap_scoretarget_right_open_gap_scoretarget_right_extend_gap_scorequery_internal_open_gap_scorequery_internal_extend_gap_scorequery_left_open_gap_scorequery_left_extend_gap_scorequery_right_open_gap_scorequery_right_extend_gap_scorerH  match_scoremismatch_scorer  )r  r  r  r  r  r  r  r  r   r  r  r  r  rH  r  r  r  )r!   stater$   r$   r%   __getstate__  s*   



zPairwiseAligner.__getstate__c                 C   s   |d | _ |d | _|d | _|d | _|d | _|d | _|d | _|d | _|d	 | _|d
 | _	|d | _
|d | _|d | _|d | _|d}|d u r[|d | _|d | _d S || _d S )Nr  r  r  r  r  r  r  r  r   r  r  r  r  rH  r  r  r  )r  r  r  r  r  r  r  r  r   r  r  r  r  rH  r   r  r  r  )r!   r  r  r$   r$   r%   __setstate__  s*   















zPairwiseAligner.__setstate__rB   )r  )r<   r   r   r   r&   r  r  r  r  r	  r  r$   r$   r  r%   r    s     $
r  c                       s:   e Zd ZdZd
 fdd	Z fddZ fdd	Z  ZS )CodonAlignerzAligns a nucleotide sequence to an amino acid sequence.

    This class implements a dynamic programming algorithm to align a nucleotide
    sequence to an amino acid sequence.
    NrQ  c                    s<   t    |du rtjd }n
t|tjstd|| _dS )zInitialize a CodonAligner for a specific genetic code.

        Arguments:
         - codon_table - a CodonTable object representing the genetic code.
           If codon_table is None, the standard genetic code is used.

        Nr   z&Input table is not a CodonTable object)r  r&   r   generic_by_idr   r   codon_table)r!   r  
anchor_lenr  r$   r%   r&     s   

zCodonAligner.__init__c                    s8  | j }t|tttfrt|}nt|tr| }ntd|ddt	|d   }|dddt	|d d    }|dddt	|d d    }t|tttfrn|
|}|
|}	|
|}
t|}t|	}	t|
}
n%t|trt
||}t
||}	t
||}
| }|	 }	|
 }
ntdt |||	|
S )a	  Return the alignment score of a protein sequence and nucleotide sequence.

        Arguments:
         - seqA  - the protein sequence of amino acids (plain string, Seq,
           MutableSeq, or SeqRecord).
         - seqB  - the nucleotide sequence (plain string, Seq, MutableSeq, or
           SeqRecord); both DNA and RNA sequences are accepted.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> aligner = CodonAligner()
        >>> dna = SeqRecord(Seq('ATGTCTCGT'), id='dna')
        >>> pro = SeqRecord(Seq('MSR'), id='pro')
        >>> score = aligner.score(pro, dna)
        >>> print(score)
        3.0
        >>> rna = SeqRecord(Seq('AUGUCUCGU'), id='rna')
        >>> score = aligner.score(pro, rna)
        >>> print(score)
        3.0

        This is an example with a frame shift in the DNA sequence:

        >>> dna = "ATGCTGGGCTCGAACGAGTCCGTGTATGCCCTAAGCTGAGCCCGTCG"
        >>> pro = "MLGSNESRVCPKLSPS"
        >>> len(pro)
        16
        >>> aligner.frameshift_score = -3.0
        >>> score = aligner.score(pro, dna)
        >>> print(score)
        13.0

        In the following example, the position of the frame shift is ambiguous:

        >>> dna = 'TTTAAAAAAAAAAATTT'
        >>> pro = 'FKKKKF'
        >>> len(pro)
        6
        >>> aligner.frameshift_score = -1.0
        >>> alignments = aligner.align(pro, dna)
        >>> print(alignments.score)
        5.0
        >>> len(alignments)
        3
        >>> print(next(alignments))
        target            0 F  K  K  K   4
        query             0 TTTAAAAAAAAA 12
        <BLANKLINE>
        target            4 K  F    6
        query            11 AAATTT 17
        <BLANKLINE>
        >>> print(next(alignments))
        target            0 F  K  K   3
        query             0 TTTAAAAAA 9
        <BLANKLINE>
        target            3 K  K  F    6
        query             8 AAAAAATTT 17
        <BLANKLINE>
        >>> print(next(alignments))
        target            0 F  K   2
        query             0 TTTAAA 6
        <BLANKLINE>
        target            2 K  K  K  F    6
        query             5 AAAAAAAAATTT 17
        <BLANKLINE>
        >>> print(next(alignments))
        Traceback (most recent call last):
        ...
        StopIteration

        ;seqA must be a string, Seq, MutableSeq, or SeqRecord objectNr7   r   rp   ;seqB must be a string, Seq, MutableSeq, or SeqRecord object)r  r   r   r   r   r   rY   r   r   r)   r   r  r  )r!   r  r  r  r  seqB0seqB1seqB2sB0sB1sB2r  r$   r%   r    s:   H


  








zCodonAligner.scorec                    sN  | j }t|tttfrt|}nt|tr| }ntd|ddt	|d   }|dddt	|d d    }|dddt	|d d    }t|tttfrn|
|}|
|}	|
|}
t|}t|	}	t|
}
n%t|trt
||}t
||}	t
||}
| }|	 }	|
 }
ntdt |||	|
\}}t||||}|S )a  Align a nucleotide sequence to its corresponding protein sequence.

        Arguments:
         - seqA  - the protein sequence of amino acids (plain string, Seq,
           MutableSeq, or SeqRecord).
         - seqB  - the nucleotide sequence (plain string, Seq, MutableSeq, or
           SeqRecord); both DNA and RNA sequences are accepted.

        Returns an iterator of Alignment objects.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqRecord import SeqRecord
        >>> aligner = CodonAligner()
        >>> dna = SeqRecord(Seq('ATGTCTCGT'), id='dna')
        >>> pro = SeqRecord(Seq('MSR'), id='pro')
        >>> alignments = aligner.align(pro, dna)
        >>> alignment = alignments[0]
        >>> print(alignment)
        pro               0 M  S  R   3
        dna               0 ATGTCTCGT 9
        <BLANKLINE>
        >>> rna = SeqRecord(Seq('AUGUCUCGU'), id='rna')
        >>> alignments = aligner.align(pro, rna)
        >>> alignment = alignments[0]
        >>> print(alignment)
        pro               0 M  S  R   3
        rna               0 AUGUCUCGU 9
        <BLANKLINE>

        This is an example with a frame shift in the DNA sequence:

        >>> dna = "ATGCTGGGCTCGAACGAGTCCGTGTATGCCCTAAGCTGAGCCCGTCG"
        >>> pro = "MLGSNESRVCPKLSPS"
        >>> alignments = aligner.align(pro, dna)
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 M  L  G  S  N  E  S   7
        query             0 ATGCTGGGCTCGAACGAGTCC 21
        <BLANKLINE>
        target            7 R  V  C  P  K  L  S  P  S   16
        query            20 CGTGTATGCCCTAAGCTGAGCCCGTCG 47
        <BLANKLINE>

        r  Nr7   r   rp   r  )r  r   r   r   r   r   rY   r   r   r)   r   r  r  r  )r!   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r$   r%   r  5  s>   -


  








zCodonAligner.align)NrQ  )r<   r   r   r   r&   r  r  r  r$   r$   r  r%   r
    s
    hr
  )a2mbedbigbedbigmafbigpslchainclustalemboss	exoneratefastahhrmafmauvemsfnexusphylippslsam	stockholmtabular_modulesrK  returnc                 C   sV   |   } zt|  W S  ty   Y nw | tvrtd|  td|  }|t| < |S )NzUnknown file format %sz
Bio.Align.)lowerr*  r   formatsr   	importlibimport_module)rK  rN  r$   r$   r%   rF    s   
rF  c                 O   s^   t | tr| g} t|}z|j}W n ty    td| dw ||g|R i || S )a)  Write alignments to a file.

    Arguments:
     - alignments - An Alignments object, an iterator of Alignment objects, or
       a single Alignment.
     - target     - File or file-like object to write to, or filename as string.
     - fmt        - String describing the file format (case-insensitive).

    Note if providing a file or file-like object, your code should close the
    target after calling this function, or call .flush(), to ensure the data
    gets flushed to disk.

    Returns the number of alignments written (as an integer).
    z2File writing has not yet been implemented for the rD  )r   r   rF  rI  r   r   rW   )r  r  rK  rL  rM  rN  rO  r$   r$   r%   rW     s   


rW   c                 C   s   t |}|| }|S )a  Parse an alignment file and return an iterator over alignments.

    Arguments:
     - source - File or file-like object to read from, or filename as string.
     - fmt    - String describing the file format (case-insensitive).

    Typical usage, opening a file to read in, and looping over the alignments:

    >>> from Bio import Align
    >>> filename = "Exonerate/exn_22_m_ner_cigar.exn"
    >>> for alignment in Align.parse(filename, "exonerate"):
    ...    print("Number of sequences in alignment", len(alignment))
    ...    print("Alignment score:", alignment.score)
    Number of sequences in alignment 2
    Alignment score: 6150.0
    Number of sequences in alignment 2
    Alignment score: 502.0
    Number of sequences in alignment 2
    Alignment score: 440.0

    For lazy-loading file formats such as bigMaf, for which the file contents
    is read on demand only, ensure that the file remains open while extracting
    alignment data.

    You can use the Bio.Align.read(...) function when the file contains only
    one alignment.
    )rF  rG  )sourcerK  rN  r  r$   r$   r%   parse  s   
r1  c                 C   sV   t | |}zt|}W n ty   tddw zt| td ty*   Y |S w )aD  Parse a file containing one alignment, and return it.

    Arguments:
     - source - File or file-like object to read from, or filename as string.
     - fmt    - String describing the file format (case-insensitive).

    This function is for use parsing alignment files containing exactly one
    alignment.  For example, reading a Clustal file:

    >>> from Bio import Align
    >>> alignment = Align.read("Clustalw/opuntia.aln", "clustal")
    >>> print("Alignment shape:", alignment.shape)
    Alignment shape: (7, 156)
    >>> for sequence in alignment.sequences:
    ...     print(sequence.id, len(sequence))
    gi|6273285|gb|AF191659.1|AF191 146
    gi|6273284|gb|AF191658.1|AF191 148
    gi|6273287|gb|AF191661.1|AF191 146
    gi|6273286|gb|AF191660.1|AF191 146
    gi|6273290|gb|AF191664.1|AF191 150
    gi|6273289|gb|AF191663.1|AF191 150
    gi|6273291|gb|AF191665.1|AF191 156

    If the file contains no records, or more than one record, an exception is
    raised.  For example:

    >>> from Bio import Align
    >>> filename = "Exonerate/exn_22_m_ner_cigar.exn"
    >>> alignment = Align.read(filename, "exonerate")
    Traceback (most recent call last):
        ...
    ValueError: More than one alignment found in file

    Use the Bio.Align.parse function if you want to read a file containing
    more than one alignment.
    zNo alignments found in fileNz%More than one alignment found in file)r1  rb   rc   r   )r[   rK  r  r   r$   r$   r%   read  s   
%
r2  __main__)run_doctest):r   collectionsr   r.  r;  r  typesr   abcr   r   	itertoolsr   numpyr   ImportErrorrV   r   r   	Bio.Alignr   r   r	   r
   Bio.Datar   Bio.Seqr   r   r   r   r   Bio.SeqRecordr   r   
namedtupler   r   r   r  r   r  r  r  r
  r-  r*  r   rY   
ModuleType__annotations__rF  rW   r1  r2  r<   
Bio._utilsr4  r$   r$   r$   r%   <module>   s   	       3                    aD  
 Q!
2
