
    Ri                       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mZ ddlm	Z	 ddl
mZ 	 ddlZddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ dd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#  G d d      Z$ G d d      Z% G d de      Z& G d de&e'      Z( G d d e&      Z) G d! d"ejT                        Z* G d# d$ejV                        Z+d%Z,i Z-e.e/ej`                  f   e1d&<   d'e/d(ej`                  fd)Z2d* Z3d+ Z4d, Z5e6d-k(  rdd.l7m8Z8  e8        yy# e$ r ddlmZ  ed      dw xY w)/zCode 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)_alignmentcounts)substitution_matrices)
CodonTable)
MutableSeq)reverse_complement)Seq)	translate)UndefinedSequenceError)SequenceDataAbstractBaseClass)_RestrictedDict)	SeqRecordc                       e Zd ZdZ	 ddZd Zd Z eeed      ZddZ	d	 Z
d
 Zd Zd Zd Zd Zd Zd ZddZd Zd Zd ZddZed        Zed        Zy)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                     |t        d      g | _        |r| j                  |       |i }nt        |t              st        d      || _        |i }|| _        y)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    s        J/home/agent/.friday_env/lib/python3.12/site-packages/Bio/Align/__init__.py__init__zMultipleSeqAlignment.__init__   sn    N KLLKK  KK.CDD& %!#"4    c                     t        |t              st        d      t        |       r=| j	                         }t        |      | _        | j                  j                  |       y d | _        |rt        d      y )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_lengths      r$   _set_per_column_annotationsz0MultipleSeqAlignment._set_per_column_annotations   sv    %&Q  t9"779O(7(OD%%%,,U3 )-D% K  r&   c                     | j                   /t        |       r| j                         }nd}t        |      | _         | j                   S )Nr   r(   )r,   r*   r+   r   )r!   r/   s     r$   _get_per_column_annotationsz0MultipleSeqAlignment._get_per_column_annotations   sC    $$,4y"&";";"= #$(7(OD%(((r&   z5Dictionary of per-letter-annotation for the sequence.)fgetfsetdocc                    |j                   j                  j                  dk(  rdt        |j                         |k  r|j                    d|j                   S |j                   d|dz
   d|j                   dd d|j                  S t        |j                         |k  r|j                    d|j                   S |j                   d|dz
   d|j                   dd d|j                  S )zReturn a truncated string representation of a SeqRecord (PRIVATE).

        This is a PRIVATE function used by the __str__ method.
        CodonSeq N   ...   )seq	__class____name__r*   id)r!   recordr)   s      r$   	_str_linezMultipleSeqAlignment._str_line   s    
 ::((J66::&( **Qvyyk22 JJ|!,JJrsOII  6::&( **Qvyyk22 JJ|!,JJrsOII r&   c                     t         j                        }d| j                         fz  g}|dk  r%|j                   fd j                  D               ne|j                   fd j                  dd D               |j	                  d       |j	                   j                   j                  d                d	j                  |      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   @   K   | ]  }j                  |        y wNrB   .0recr!   s     r$   	<genexpr>z/MultipleSeqAlignment.__str__.<locals>.<genexpr>$  s     F,F   c              3   @   K   | ]  }j                  |        y wrF   rG   rH   s     r$   rK   z/MultipleSeqAlignment.__str__.<locals>.<genexpr>&  s     K,KrL   N   r:   
)r*   r   r+   r   appendrB   join)r!   rowsliness   `  r$   __str__zMultipleSeqAlignment.__str__  s    . 4==!3T..012
 2:LLFFFLLKcr8JKKLLLLb(9:;yyr&   c                 |    d| j                   t        | j                        | j                         t	        |       fz  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@   r!   s    r$   __repr__zMultipleSeqAlignment.__repr__+  s=     ?NN%%'tH	B
 
 	
r&   c                     |r7ddl m} ddlm}  |       }|j	                  | g||       |j                         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)iorZ   Bior[   writegetvaluestr)r!   format_specrZ   r[   handles        r$   
__format__zMultipleSeqAlignment.__format__E  s@    @ ##ZFMM4&&+6??$$ t9r&   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   rW   s    r$   __iter__zMultipleSeqAlignment.__iter__q  s    . DMM""r&   c                 ,    t        | j                        S )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   rW   s    r$   __len__zMultipleSeqAlignment.__len__  s     4==!!r&   c                     d}| j                   D ]0  }t        |j                        |kD  st        |j                        }2 |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_lengthrA   s      r$   r+   z)MultipleSeqAlignment.get_alignment_length  sA    0 
mm 	-F6::+ _
	- r&   c                    t        |       r| j                         }n;t        |      }	 t        |      }t        |      }| j                  ||       i | _        |D ]  }| j                  ||        y# t        $ r Y yw xY w)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+   re   nextStopIteration_appendr    )r!   r"   r/   rJ   s       r$   r   zMultipleSeqAlignment.extend  s    N t9"779O 7mG7m "#hOLLo. ')D#  	/CLLo.	/ ! s   A2 2	A>=A>c                     | j                   r!| j                  || j                                y| j                  |       y)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   rn   r+   )r!   rA   s     r$   rQ   zMultipleSeqAlignment.append  s/    V ==LL!:!:!<=LL r&   c                     t        |t              st        d      |t        |      |k7  rt	        d      | j
                  j                  |       y)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   rQ   )r!   rA   r/   s      r$   rn   zMultipleSeqAlignment._append"  sK    &),DEE
 &3v;/+I DEEV$r&   c                    t        |t              st        t        |       t        |      k7  rt	        d      d t        | |      D        }i }| j                  j                         D ],  \  }}||j                  v s|j                  |   |k(  s(|||<   . i }| j                  j                         D ])  \  }}||j                  v s||j                  |   z   ||<   + t        |||      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              3   ,   K   | ]  \  }}||z     y wrF    )rI   leftrights      r$   rK   z/MultipleSeqAlignment.__add__.<locals>.<genexpr>  s     C;4$,Cs   )r   r    )	r   r   NotImplementedErrorr*   r   zipr   itemsr    )r!   othermergedr   kvr    s          r$   __add__zMultipleSeqAlignment.__add__2  s   R %!56%%t9E
".  D#dE2BC$$**, 	#DAqE%%%%*;*;A*>!*C!"A	#  ++113 	HDAqE,,,()E,D,DQ,G(G"1%	H $@R
 	
r&   c                     t        |t              r| j                  |   S t        |t              rnt	        | j                  |         }| j
                  rHt        |      t        |       k(  r1| j
                  j                         D ]  \  }}||j
                  |<    |S t        |      dk7  rt        d      |\  }t        |t              r| j                  |      S t        t              r'dj                  fd| j                  |   D              S t	        fd| j                  |   D              }| j
                  rKt        |      t        |       k(  r4| j
                  j                         D ]  \  }}|   |j
                  |<    |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   (   K   | ]	  }|     y wrF   rt   rI   rJ   	col_indexs     r$   rK   z3MultipleSeqAlignment.__getitem__.<locals>.<genexpr>  s     Nc3y>N   c              3   (   K   | ]	  }|     y wrF   rt   r   s     r$   rK   z3MultipleSeqAlignment.__getitem__.<locals>.<genexpr>  s      '#&I'r   )
r   intr   slicer   r    r*   ry   r   rR   )r!   indexnewr|   r}   	row_indexr   s         @r$   __getitem__z MultipleSeqAlignment.__getitem__  sq   ^ eS! ==''u%&t}}U';<C&&3s8s4y+@ !3399; 2DAq01C**1-2JZ1_122  %	9i%==+I66	3'77NT]]95MNNN ' '*.--	*B' C &&3s8s4y+@ !3399; =DAq01)C**1-=Jr&   c                 t    t        |t              st        |t              st        d      | j                  |= y)z:Delete SeqRecord by index or multiple SeqRecords by slice.r   N)r   r   r   r   r   )r!   r   s     r$   __delitem__z MultipleSeqAlignment.__delitem__#  s-    %%j.F122MM% r&   c                     || j                   j                  d |       y| j                   j                  ||       y)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                     | j                   S rF   )r@   )rs    r$   <lambda>z+MultipleSeqAlignment.sort.<locals>.<lambda>s  s
    QTT r&   keyreverse)r   sort)r!   r   r   s      r$   r   zMultipleSeqAlignment.sort*  s8    P ;MM>7CMM38r&   c                 l   t        j                  d | D         }	 |j                  d       dj	                  t        |            }t        j                  |d      }t        |       D ]  \  }}|j                  }|j                  j                  dd      }t        |       D ]f  \  }}||k(  r F|j                  }	|j                  j                  dd      }
t        ||	      D ]#  \  }}|dk(  r|dk(  r|||fxx   ||
z  z  cc<   % h  ||j                         z  }|dz  }|S # t        $ r Y w xY w)	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              3   F   K   | ]  }t        |j                          y wrF   )setr=   )rI   rA   s     r$   rK   z5MultipleSeqAlignment.substitutions.<locals>.<genexpr>  s     A&c&**oAs   !-r   r   dimsweight      ?g       @)r   unionremoveKeyErrorrR   sortedr   Array	enumerater=   r   getrx   	transpose)r!   lettersmrec_num1
alignment1seq1weight1rec_num2
alignment2seq2weight2residue1residue2s                r$   substitutionsz"MultipleSeqAlignment.substitutionsw  sO   b ))ADAB	NN3 ''&/*!''a8$-dO 	A Hj>>D ,,003?G(1$ 
A$*x'!~~$0044XsC*-dD/ A&Hh3 3 x*+w/@@+A
A	A 	
Q[[]	S-  		s   D& &	D32D3c           	         | j                   D cg c]  }t        j                  |       }}|rY|D cg c]  }t        |j                         }}t        j                  |      \  }}t        ||      D ]  \  }}|j                  rt        |j                        D cg c]  \  }}|dk7  s| }	}}t        |j                        }
|j                  j                          t        |      |_        |
j                         D ]Y  \  }t        t              r#dj                  |	D cg c]  }|   	 c}      nt!              } |fd|	D              |
|<   [ |
|_        t        |      |_         t	        ||      }nt	        g       }| j"                  |_        | j$                  |_        |S c c}w c c}w c c}}w c c}w )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.
        r   r   c              3   (   K   | ]	  }|     y wrF   rt   )rI   ir.   s     r$   rK   z1MultipleSeqAlignment.alignment.<locals>.<genexpr>  s     'BQa'Br   )r   copybytesr=   	Alignmentparse_printed_alignmentrx   letter_annotationsr   r   clearr   ry   r   r`   rR   typer   r    )r!   rA   r"   rT   seqdatacoordinatesseqrowr   cindicesr   r   cls	alignmentr.   s                 @r$   r   zMultipleSeqAlignment.alignment  s    48==A499V$AA5<=6U6::&=E=#,#D#DU#K G["%gw"7 -,,-6vzz-BOTQa3hqOGO)-f.G.G)H&--335!$VFJ&8&>&>&@ 8
U%eS1$&GGw,G!U1X,G$HE"&u+C$''B''B$BE27*3/8 1CF-!$VFJ-  "';7I!"I $ 0 0	'+'>'>	$3 B= P -Hs   F9F>"G0G+G	)NNN)2   rF   NF)r?   
__module____qualname____doc__r%   r0   r2   propertyr    rB   rU   rX   rc   rf   rh   r+   r   rQ   rn   r~   r   r   r   r   r   rt   r&   r$   r   r   ;   s    Qh LP95v&
) "((G0" H
4*X#2
"@:/x.!`% \
|Qf!K9Z I IV    r&   r   c                      e Zd ZdZed        Zeded    ed    z  dd fd       Zd2dZ	d3dZ
d	 Zed
        Zed        Zej                  d        Zed        Zej                  d        Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d4d Z"d2d!Z#d2d"Z$d2d#Z%d$ Z&d% Z'd& Z(ed'        Z)ed(        Z*ed)        Z+ed*        Z,ed+        Z-d5d,Z.d- Z/d. Z0ed/        Z1d2d0Z2d1 Z3y)6r   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                    t        j                  d      }g }|D ]'  }|j                  |      \  }}|j                  |       ) |j                  }t        j                  |t
        j                        }|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feedrQ   shapenpemptyintpfill)	r   rT   parser	sequenceslinenbytessequencer   r   s	            r$   r   z!Alignment.parse_printed_alignment  s    T 2259	 	'D%{{40FHX&	' hhubgg.K +%%r&   
alignmentsreturnc                 x   t        |      dk(  rt        d      |D cg c]  }|j                  d    c}t        fdD              st        d      t	               }D ]8  }	 |j
                  }	 |j                  t        |      j                                : t        |      dkD  rt        d      |d   j                  d   }|D cg c]  }|j                  dd D ]  }|  }}}|g|z   }g }	|D ]T  }|j                  }
t        d|
j                  d         D ]*  }|	j                  |
d|gddf   j                                , V |	D ch c]  }|d   	 }}|	D ch c]  }|d	   	 }}t        |      dk7  st        |      dk7  rt        d
      |j!                         }|	D cg c]  }t#        |       }}g }t%        j&                  |D cg c]  }t)        |       c}      }t%        j&                  |D cg c]  }t)        |       c}      }|j                  |gt+        |dddf         z          	 |t,        j.                  k(  j                         rn|dddf   |z
  }t%        j0                  |      }||   }|dddf   |dddf   z
  }||   }||z  }||ddf   ||ddf<   t)        ||   t,        j.                        ||ddf<   |dk(  r|dk(  r@t3        |      D ]1  \  }}||k7  s|dkD  r||ddfxx   |z  cc<   #||dfxx   |z  cc<   3 |j                  |gt+        |dddf         z          
t%        j&                  |      j                         } | ||      S c c}w # t        $ r Y w xY w# t        $ r Y 6w xY wc c}}w c c}w c c}w c c}w c c}w c c}w )a  Create an Alignment from a list of alignments in which the first sequence is the same (reference sequence).

        This method combines multiple alignments into a single multiple sequence alignment.
        All alignments must share the same reference sequence (ignoring gaps).

        Args:
            alignments: A list or tuple of Alignment objects.

        Returns:
            An Alignment object representing a multiple sequence alignment.

        Raises:
            ValueError: If no alignments are provided or if the reference
            sequences do not match across all alignments.

        Example 1: Basic Usage with Strings
            >>> from Bio.Seq import Seq
            >>> from Bio.SeqRecord import SeqRecord
            >>> from Bio.Align import PairwiseAligner, Alignment
            >>> import numpy as np

            Consider the following reference and sequences:
            >>> reference_str = "ACGT"
            >>> seq1_str = "ACT"
            >>> seq2_str = "ACGGT"
            >>> seq3_str = "AT"

            To produce a pairwise alignment:
            >>> aligner = PairwiseAligner()
            >>> pwa = next(aligner.align(reference_str, seq1_str))

            To produce a three sequence alignment:
            >>> coords = np.array([
            ...     [0, 1, 2, 3, 3, 4],
            ...     [0, 1, 2, 3, 4, 5],
            ...     [0, 1, 1, 1, 1, 2]
            ... ])

            >>> not_pwa = Alignment([reference_str, seq2_str, seq3_str], coords)

            The pairwise alignment would look like
            >>> print(f"Reference: {pwa[0]}")
            Reference: ACGT
            >>> print(f"Seq1:      {pwa[1]}")
            Seq1:      AC-T

            The three sequence alignment would look like
            >>> str(not_pwa[0])
            'ACG-T'
            >>> str(not_pwa[1])
            'ACGGT'
            >>> str(not_pwa[2])
            'A---T'

            Now, we can combine these alignments into a multiple sequence alignment:
            >>> msa = Alignment.from_alignments_with_same_reference([pwa, not_pwa])
            >>> str(msa[0])
            'ACG-T'
            >>> str(msa[1])
            'AC--T'
            >>> str(msa[2])
            'ACGGT'
            >>> str(msa[3])
            'A---T'

        Example 2: Using SeqRecord Objects with Metadata
            Consider the following reference and sequences with metadata:
            >>> reference_seqr = SeqRecord(Seq("ACGT"), id="reference", description="desc 1")
            >>> seq1 = SeqRecord(Seq("ACGGT"), id="seq1", description="desc 2")
            >>> seq2 = SeqRecord(Seq("AT"), id="seq2", description="desc 3")

            To produce pairwise alignments:
            >>> aligner = PairwiseAligner()
            >>> pwa1 = next(aligner.align(reference_seqr, seq1))
            >>> pwa2 = next(aligner.align(reference_seqr, seq2))

            The msa retains the metadata from the original SeqRecord objects:
            >>> msa = Alignment.from_alignments_with_same_reference([pwa1, pwa2])
            >>> print(msa.format("fasta"))
            >reference desc 1
            ACG-T
            >seq1 desc 2
            ACGGT
            >seq2 desc 3
            A---T
            <BLANKLINE>

        r   z No pairwise alignments provided.c              3   R   K   | ]  }t        |      t        d          k(     yw)r   N)r*   )rI   	first_seq
first_seqss     r$   rK   z@Alignment.from_alignments_with_same_reference.<locals>.<genexpr>  s#     TI3y>SA%77Ts   $'z2All reference sequences must have the same length.   z4All reference sequences must match (excluding gaps).Nr   r   )rO   r   zKReference coordinates do not align consistently across pairwise alignments.)r*   r   r   allr   r=   AttributeErroraddr`   upperr   r   ranger   rQ   r   popre   r   arrayrl   listsysmaxsizeargminr   )r   r   r   string_first_seqsr   reference_seqr=   other_sequencesr   paired_coordinatescoordsr   r   reference_startsreference_endsreference_positionr   msa_coordinates	positionsnext_positionstarget_stepsr   target_stepquery_steps
query_stepr   r   s                             @r$   #from_alignments_with_same_referencez-Alignment.from_alignments_with_same_reference+  s   z z?a?@@ ?IIi))!,I
TTTQRR  E# 
	I%MM	!%%c)n&:&:&<=
	  !A%STT #1//2!+
y7J7J127N
03C

 
 #Oo5	  # 	QI**F"1fll1o6 Q	"))&!Y1B*C*M*M*OPQ	Q .@@AdG@@,>?q!E(?? A%^)<)A]  .113(:;1tAw;;HH{;!d1g;<	K"@q47"@A 23d9QT?6KKL#++-224)!Q$/2DDLIIl+E&u-K(A.1a4@K$U+J+-"0":IeQh'+K,>'LN5!8$a? &/{%; ;MAzEz%>%adO{:O &adO{:O; ""$6#7$yA:O#OPA D ((?3==?9o..u J " 
 * 
 A? < <"@sM   M8'M=4(NNN#%N(.N-N2N7=	N
	N
	NNNc                    || _         |	 |D ch c]  }t        |       }}t        |      dk(  r,t        j                  dt        j                        }|| _	        yt        |      dk(  rK|j                         }t        j                  d|ggt        |      z  t        j                        }|| _	        yt        d      || _	        yc c}w # t        $ r
 Y || _	        yw xY w)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.
        Nr   r   r   z:sequences must have the same length if coordinates is None)
r   r*   r   r   r   r   r   r   r   r   )r!   r   r   r   lengthsr)   s         r$   r%   zAlignment.__init__  s     #9BCX3x=CC w<1$"$((6277";K ' \Q&$[[]F"$((QK=3y>+I277"SK
 ' %T  '! D   's!   C C	C 	C 	C! C!c                 \   |du rt        d      | j                  j                         }t        | j                        }t        j                  | j                  d      }t        |dk7  d      dkD  }t        |      D ]|  \  }}|||f   }	|	dk\  j                         r!|	dk  j                         r<t        |      ||<   t        |      ||d d f   z
  ||d d f<   ||d d f    ||d d f<   pt        d|        |j                  d      }
||
k(  |dk  z  j                         st        d      t        |      }t        |
      }t        j                  ||fd      }t        |      D ]  }||   }||df   }d}t        ||   |
      D ]h  \  }}|dkD  rC||z   }||z   }	 t!        |||       }|||d d f   j$                  j'                  d	      || |}|}N|dk  r||z  }Y||z   }d
||||f<   |}j  |t        j(                  ||      }|S # t"        $ r t!        ||| d      }Y }w xY w)NFz[As calling array on an alignment must return a new array, the copy argument cannot be Falser   r   Inconsistent steps in row Unequal step sizes in alignmentS1UTF8B   -)r   r   r   r   r   r   diffsumr   r   r   r*   maxr   r   rx   r   r   datacastr   )r!   dtyper   r   r   stepsalignedr   r   rowgapsnr   r
  r|   stepgapjsubsequences                      r$   	__array__zAlignment.__array__  s~   5=m  &&++-(	((!,eqj!$q($Y/ 		CKAx7
#Cq~~(!1(;	!$'MK14E$EAqD!$QT{lad #=aS!ABB		C yy|$5A:.335>??JIxxA%q 	A |HAqD!AA q40 	c!8DADAC&+HQqM&: 6ADAJOO((-a2AAAXIACA#'DAaCLA!		* 88D%(D % C&+HQqM6&BCs   HH+*H+c                    t        |t              st        t        |       t        |      k7  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 ]%  \  }	}
}}}}||	|
 ||| z   }|j                  |       ' ||z
  |z   }| j
                  |dddf   z
  }|j
                  |dddf   z
  }t        j                  ||d      }t        ||      }i }	 | j                  j                         D ]  \  }}	 |j                  |   |k(  r|||<    	 ||_
        i }	 | j                  j                         D ]  \  }}	 ||j                  |   z   ||<    	 ||_        |S # t        $ r Y xw xY w# t        $ r Y _w xY w# t        $ r Y Qw xY w# t        $ r Y |S w xY w)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'}

        rr   Nr   rO   r   axis)r   r   rw   r*   r   r   r   rx   rQ   r   r   ry   r   r   r    )r!   rz   starts1ends1
sequences1starts2ends2
sequences2r   start1end1r   start2end2r   r   offsetcoordinates1coordinates2r   r   r   r|   r}   r    s                            r$   r~   zAlignment.__add__:  s[   \ %+%%t9E
".  ""1a4(  B'^^
##AqD)!!!R%(__
	69UJ
7
 	'2FD$d F4(4t+<<HX&		'
 57*'''!T'*::((6!T'?:iilCi5	
	0((..0 1((+q0)*A %0I!		>//557 1,-0H0H0K,K&q) ,>I(#    		    	 		sl   2 G F9*G 7 G& G-G& 9	GG GG 	GG	G# G& "G##G& &	G32G3c                 (   | j                   j                         }t        | j                        }t	        j
                  | j                   d      }t        |dk7  d      dkD  }t        |      D ]|  \  }}|||f   }|dk\  j                         r!|dk  j                         r<t        |      ||<   t        |      ||ddf   z
  ||ddf<   ||ddf    ||ddf<   pt        d|        |j                  d      }||k(  |dk  z  j                         st        d      t        |      }	t        |      }
i }t        |	      D ]  }||   }	 |j                  j                  dd      }||df   }d}t#        ||   |      D ]  \  }}|dkD  r||z   }||z   }		 t%        |||       }t#        t        ||	      |      D ]J  \  }}t)        |      }|j                  |      }|t	        j*                  |
      }|||<   ||xx   |z  cc<   L |}|	}|dk  r||z  }||z   }	d	}|j                  |      }|t	        j*                  |
      }|||<   |||	xxx |z  ccc |	}  |S # t         $ r d}Y w xY w# t&        $ r t%        ||| d      }Y w xY w)
a  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 -GACCTG 6
                          0 -||.|-| 7
        query             0 CGATC-G 6
        <BLANKLINE>
        >>> alignment.frequencies
        {'-': array([1., 0., 0., 0., 0., 1., 0.]), 'G': array([0., 2., 0., 0., 0., 0., 2.]), 'A': array([0., 0., 2., 0., 0., 0., 0.]), 'C': array([1., 0., 0., 1., 2., 0., 0.]), 'T': array([0., 0., 0., 1., 0., 1., 0.])}
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACC 4
                          0 ||.| 4
        query             1 GATC 5
        <BLANKLINE>
        >>> alignment.frequencies
        {'G': array([2., 0., 0., 0.]), 'A': array([0., 2., 0., 0.]), 'C': array([0., 0., 1., 2.]), 'T': array([0., 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   rx   r   r   chrzeros)r!   r   r   r  r  r   r   r  r  r  r)   countsr   r|   r   r  r  r  r  r   letter	characters                         r$   frequencieszAlignment.frequencies  s   < &&++-(	((!,eqj!$q($Y/ 		CKAx7
#Cq~~(!1(;	!$'MK14E$EAqD!$QT{lad #=aS!ABB		C yy|$5A:.335>??JTq #	A |H!--11(C@ AqD!AA q40 	c!8DADAC&+HQqM&: *-U1a[+)F -v$'K	$jj3;"$((6"2C03F9-E
f,
- AAAXIACA #I **Y/C{ hhv.,/y)!H&HA7#	H A "  % C&+HQqM6&BCs$   I$I6$I32I36JJc                 p    t        | j                        }|dkD  rt        d|z        | j                  d   S )z2Return self.sequences[0] for a pairwise alignment.r   Uself.target is defined for pairwise alignments only (found alignment of %d sequences)r   r*   r   r   r!   r  s     r$   targetzAlignment.target  sB     q5g  ~~a  r&   c                 r    t        | j                        }|dk7  rt        d|z        || j                  d<   y)z0For a pairwise alignment, set self.sequences[0].r   r/  r   Nr0  r!   r.   r  s      r$   r2  zAlignment.target  sA     6g  "qr&   c                 p    t        | j                        }|dk7  rt        d|z        | j                  d   S )z2Return self.sequences[1] for a pairwise alignment.r   Tself.query is defined for pairwise alignments only (found alignment of %d sequences)r   r0  r1  s     r$   queryzAlignment.query*  sB     6f  ~~a  r&   c                 r    t        | j                        }|dk7  rt        d|z        || j                  d<   y)z0For a pairwise alignment, set self.sequences[1].r   r6  r   Nr0  r4  s      r$   r7  zAlignment.query5  sA     6f  "qr&   c                 $   t        | j                  |j                        D ]&  \  }}	 |j                  }	 |j                  }||k7  s& y t	        j
                  | j                  |j                        S # t        $ r Y Kw xY w# t        $ r Y Mw xY w)z:Check if two Alignment objects specify the same alignment.Fr   r   r=   r   r   array_equalr   r!   rz   ru   rv   s       r$   __eq__zAlignment.__eq__@  s    &t~~uG 
	KD%xx		 u}
	 ~~d..0A0ABB "  " s"   A4B4	B ?B 	BBc                 &   t        | j                  |j                        D ]&  \  }}	 |j                  }	 |j                  }||k7  s& y t	        j
                  | j                  |j                         S # t        $ r Y Lw xY w# t        $ r Y Nw xY w)z9Check if two Alignment objects have different alignments.Tr:  r<  s       r$   __ne__zAlignment.__ne__O  s    &t~~uG 
	KD%xx		 u}
	 >>$"2"2E4E4EFFF "  " s"   A5B5	B B	BBc                    t        | j                  |j                        D ]-  \  }}	 |j                  }	 |j                  }||k  r y||kD  s- y t	        | j
                  j                         |j
                  j                               D ])  \  }}t        |      t        |      }}||k  r y||kD  s) y y# t        $ r Y w xY w# t        $ r Y w xY w)z'Check if self should come before other.TFr   r   r=   r   rx   r   r   tupler<  s       r$   __lt__zAlignment.__lt___  s    &t~~uG 	KD%xx		 e|e|	 &&(%*;*;*E*E*G
 	KD%  +uU|%De|e|	 % "  " "   B:C	:	CC		CCc                    t        | j                  |j                        D ]-  \  }}	 |j                  }	 |j                  }||k  r y||kD  s- y t	        | j
                  j                         |j
                  j                               D ])  \  }}t        |      t        |      }}||k  r y||kD  s) y y# t        $ r Y w xY w# t        $ r Y w xY w)z6Check if self should come before or is equal to other.TFrA  r<  s       r$   __le__zAlignment.__le__x  s    &t~~uG 	KD%xx		 e|e|	 &&(%*;*;*E*E*G
 	KD%  +uU|%De|e|	 % "  " rD  c                    t        | j                  |j                        D ]-  \  }}	 |j                  }	 |j                  }||k  r y||kD  s- y t	        | j
                  j                         |j
                  j                               D ])  \  }}t        |      t        |      }}||kD  r y||k  s) y y# t        $ r Y w xY w# t        $ r Y w xY w)z&Check if self should come after other.FTrA  r<  s       r$   __gt__zAlignment.__gt__  s    &t~~uG 	KD%xx		 e|e|	 &&(%*;*;*E*E*G
 	KD%  +uU|%De|e|	 % "  " rD  c                    t        | j                  |j                        D ]-  \  }}	 |j                  }	 |j                  }||k  r y||kD  s- y t	        | j
                  j                         |j
                  j                               D ])  \  }}t        |      t        |      }}||kD  r y||k  s) y y# t        $ r Y w xY w# t        $ r Y w xY w)z5Check if self should come after or is equal to other.FTrA  r<  s       r$   __ge__zAlignment.__ge__  s    &t~~uG 	KD%xx		 e|e|	 &&(%*;*;*E*E*G
 	KD%  +uU|%De|e|	 % "  " rD  c                    t        j                  | j                  d      }t        |      }|dk  r||z  }|dk  rt	        d      ||k\  rt	        d      t        |dk7  d      dkD  }| j                  |ddf   }| j                  |   }t        |      D ]W  }|||f   }t        |dkD        t        |dk        k  s(||ddf    ||ddf<   ||k(  s?t        |      }t        |      |z
  }Y |j                  d      }		 |j                  }||   }|d   }
t        |t        t        f      rId}t        ||	      D ]6  \  }}|dkD  r|
|z   }|t        ||
|       z  }|}
$|dk  r|
|z  }
/|d|z  z  }8 |S g }t        ||	      D ];  \  }}|dkD  r|
|z   }|j!                  ||
|        |}
'|j!                  dg|z         = |S # t        $ r Y w xY w)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 rangeNr   r   )r   r  r   r*   
IndexErrorr  r   r   r   r	  r=   r   r   r`   r   rx   r   )r!   r   r  r  r  r   r   r   aligned_stepsr  r|   r   r  r  r  s                  r$   _get_rowzAlignment._get_row  s%    ((!,J19QJEqy !9::aZ566eqj!$q(&&uax0>>%(q 	>A!!W*-M=1$%MA,=(>>$QT{lad:1(;H"%h-+"=K	> yy|	||H eNhc
+D - &	c!8DAC1..DAAXIAC#I%D&$  D - .	c!8DAKK1.AKK-. 1  		s   G 	GGc                 @   | j                   |   }| j                  |   j                         }t        ||      }t	        j
                  | j                  |      r&	 | j                  |_        	 | j                  |_        |S |S # t        $ r Y !w xY w# t        $ r Y |S w xY w)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   s        r$   	_get_rowszAlignment._get_rows  s     NN3'	&&s+002i5	>>$**K8"&**	/3/F/F	, y "  " s$   B ,B 	BB	BBc                     |j                         }|j                  |d      }||   r$|||   z
  }|t        |d|dz          |z   z  }||   S y)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.
        rv   sideNr   r   )cumsumsearchsortedr  )	r!   r  colr  r  r   r   r   r$  s	            r$   _get_row_colzAlignment._get_row_col  se     ++-$$Sw$7<75>)FU;UQY'(611AA;r&   c                    |j                         }|j                  |d      }|||d j                  |d      z   }		 |j                  }t	        |t
        t        f      r||	k(  rA||z
  }
||   dk(  rd|
z  }|S ||   |z   }|dkD  r|||dz
     z  }||
z   }t        |||       }|S ||   |z
  }
||   dk(  rd|
z  }n||dz      }||
z
  }t        |||       }|dz  }||	k  r?||   }||   dk(  r	|d|z  z  }n||   }||dz      }|t        |||       z  }|dz  }||	k  r?|||dz
     z
  }
|
dkD  r-||   dk(  r
|d|
z  z  }|S ||   }||
z   }|t        |||       z  }|S ||	k(  r9||z
  }
||   dk(  rdg|
z  }|S ||   |z   }|dkD  r|||dz
     z  }||
z   }||| }|S ||   |z
  }
||   dk(  rdg|
z  }n||dz      }||
z
  }||| }|dz  }||	k  rO||   }||   dk(  r|j                  dg|z         n!||   }||dz      }|j                  |||        |dz  }||	k  rO|||dz
     z
  }
|
dkD  r=||	   dk(  r|j                  dg|
z         |S ||   }||
z   }|j                  |||        |S # t        $ r Y 0w xY w)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.
        rv   rS  Nr   r   r   )rU  rV  r=   r   r   r`   r   r   )r!   
coordinatestart_index
stop_indexr  r  r   r   r   r  r)   r   startstopr  s                  r$   _get_row_cols_slicezAlignment._get_row_cols_slice(  s    ++-  7 ;(('(BB	||H hc
+Av#k18q=<DL I 'qMK7E1uQ/ 6>Dxd34D@ } !k18q=<D%a!e,D 6MExd34DQ!e7DQx1}d
* *1)!a%0HU4$8 99FA !e $ga!en4A:Qx1}f,T Q !+1$v~HU4$8 99L I Av#k18q= 6F?DB ? 'qMK7E1uQ/ 6>D#E$/D6 3 !k18q= 6F?D%a!e,D 6ME#E$/DQ!e7DQx1}TFTM2 *1)!a%0HU4$89FA !e $ga!en4A:Qx1}TFVO4
  !+1$v~HU4$89Y  		s   I. .	I;:I;c                 |  	 	 |j                   }t        |t        t        f      r\d	|d   }t        |dd |      D ]&  \  }}||k  r	t        |||       z  	n	d|z  z  	|}( 	 dj                  	fd|D              		S g 	|d   }t        |dd |      D ]6  \  }}||k  r	j                  |||        n	j                  dg|z         |}8 	 |D cg c]  }	|   	 c}		S # t        $ r Y w xY w# t        $ r  t        $ r t        d      dw xY wc c}w # t        $ r  t        $ r t        d      dw xY 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.
        r   r   r   Nr   c              3   (   K   | ]	  }|     y wrF   rt   )rI   rW  r   s     r$   rK   z3Alignment._get_row_cols_iterable.<locals>.<genexpr>  s     9StCy9r   ?second index must be an integer, slice, or iterable of integers)r=   r   r   r`   r   rx   rR   rL  	Exceptionr   r   )
r!   rZ  colsr  r   r]  endr  rW  r   s
            @r$   _get_row_cols_iterablez Alignment._get_row_cols_iterable  s   	||H hc
+DqME
125 S3;Cs 344DC#I%Dww9D990 ! DqME
125 S3;KKs 34KK--12cS	2 I  		   U 3  Us;   C& %C5 D D!D &	C21C25DD D;c                     |j                         }|j                  |d      }||   |z
  }d}	t        |||      D ]*  \  }
}}||   dk(  r|	dz  }	||   ||   z   |z
  }|	|
|   z  }	, |	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.
        rv   rS  r   r   r   )rU  rV  rx   )r!   r   rW  r  r  r   r   r  r$  r   r   rZ  r  r   s                 r$   _get_rows_colzAlignment._get_rows_col  s     ++-  7 3c!*-ie*L 	(&Hj$Aw!|"1Q/&8'	( r&   c                    t        j                  || j                  |   k7  d      }|j                         }|j	                  |d      }	|	||	d j	                  |d      z   dz   }
|dd|	f   ||	   z
  |z   }|dd|	fxx   ||dd|	f   dkD  z  z  cc<   ||
dz
     |z
  }|dd|
fxx   ||dd|
dz
  f   dkD  z  z  cc<   |dd|	|
dz   f   }| j
                  |   }t        |||      D ]  \  }}}|s
t        |      |dd z
  |dd  t        ||      }t        j                  | j                  |      r	 | j                  |_
        	 | j                  }i |_        |j                         D ]*  \  }}||| }	 |j                         }||j                  |<   , |S # t        $ r Y ^w xY w# t        $ r Y -w xY w# t        $ r Y |S w xY w)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  rv   rS  Nru   r   )r   anyr   rU  rV  r   rx   r*   r   r;  rP  r   r    ry   r   )r!   r   r  r[  r\  r  r  rcsr   r   r  r$  r   rZ  rcr   r   r    r   r.   s                       r$   _get_rows_cols_slicezAlignment._get_rows_cols_slice  s"    ff[D$4$4S$99B++-  7 ;((&(AAAEq!twqz)K7AqDVuQT{Q77Q*,AqDVuQAX':;;!!QQY,/NN3'	(+Ki(H 	>$JH #H
1 =
1	> i5	>>$**K8"&**		:!%!8!8 ,.I(0668 :
Uk*5!JJLE 5:	,,S1: ! "  &   	 	s6   :F F< ;F-	F*)F*-	F98F9<	G	G	c                 H   t        |      }g }t        |      D ]  \  }}		 |	j                  }
d||df   }t	        ||   |      D ](  \  }}|r||z   }t        |
||       z  |}!d|z  z  * 	 dj                  fd|D              j                         |j                          | j                  |      \  }}t        |      D ]G  \  }}	||   	 |	j                  }
t        j                  |	      }	|
j                        |	_        |	||<   I t%        ||      }	 | j&                  }i |_        |j)                         D ]R  \  }fd|D        }t!        t
              rdj                  |      nj                  |      |j&                  |<   T |S # t        $ r |	}
Y w xY w# t        $ r  t        $ r t        d      dw xY w# t        $ r5 t!        |	t
              rj#                         }	n|	j                        }	Y w xY w# t        $ r Y |S w xY w)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.
        r   r   r   c              3   (   K   | ]	  }|     y wrF   rt   )rI   r   r   s     r$   rK   z4Alignment._get_rows_cols_iterable.<locals>.<genexpr>  s     @utE{@r   rb  Nc              3   (   K   | ]	  }|     y wrF   rt   )rI   r   r.   s     r$   rK   z4Alignment._get_rows_cols_iterable.<locals>.<genexpr>=  s     <5%,<r   )rB  r   r=   r   rx   r`   rR   rL  rc  r   encoderQ   r   r   deepcopyr>   r   decoder   r    ry   )r!   r   rW  r  r  r   r   rT   r   r   sr|   r  r  r  r   r   r    r   valuesr   r.   s                       @@r$   _get_rows_cols_iterablez!Alignment._get_rows_cols_iterable  sb    *$Y/ 	KAxLL DAqD!A q40 &	cDAC!AK'DAC#I%D&ww@@@ ;;=DLL/	0  $;;EB$Y/ 	$KAx1:D	1LL  ==2 {{40#IaL	$ i5		:!%!8!8 ,.I(0668 :
U<G<eS)GGFOE!OOF3E49	,,S1: c "    U " 8h,#{{}H'11$7H	8  	 	sA   F2F1G%H F.-F.1G;HH	H! H!c                    t        |t        j                        r| j                  |      S t        |t              r| j                  |      S t        | j                        }| j                  j                         }t        j                  |d      }t        |dk7  d      dkD  }t        |      D ]  \  }}|||f   }|dk\  j                         r!|dk  j                         rQ||ddf    ||ddf<   t        |      ||ddf   z
  ||ddf<   t!        |      ||<   	 |j"                  ||   _        t'        d|        |j)                  d      }	||	k(  |dk  z  j                         st'        d      t        |	      }
t        |t*              r	 |\  }}nt-        d      t        |t        j                        r$|dk  r||
z  }|dk  s||
k\  rt/        d||
fz        ||   }t        |t        j                        r||   }t        |t        j                        r| j1                  ||df   |||	|      S ||ddf   }t        |t              rB|j3                  |
      \  }}}||k  r|dk(  r| j5                  |||||	|      S t7        |||      }| j9                  |||	|      S t        |t              r||   }||   }t        |t        j                        r| j;                  ||||	|      S t        |t              rB|j3                  |
      \  }}}||k  r|dk(  r| j=                  ||||||	      S t7        |||      }| j?                  ||||	|      S t-        d	      # t$        $ r Y w xY w# t&        $ r t'        d      w xY w)
ab  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 ACCGGTTT 8
                          0 ||.||||- 8
        query             0 ACGGGTT- 7
        <BLANKLINE>
        >>> alignment[0, :]
        'ACCGGTTT'
        >>> alignment[1, :]
        'ACGGGTT-'
        >>> alignment[0]
        'ACCGGTTT'
        >>> alignment[1]
        'ACGGGTT-'
        >>> alignment[0, 1:-2]
        'CCGGT'
        >>> alignment[1, 1:-2]
        'CGGGT'
        >>> alignment[1, (1, 7, 2)]
        'C-G'
        >>> alignment[1, ::2]
        'AGGT'
        >>> alignment[1, range(0, 8, 2)]
        'AGGT'
        >>> alignment[:, 0]
        'AA'
        >>> alignment[:, 5]
        'TT'
        >>> alignment[:, 1:]  # doctest:+ELLIPSIS
        <Alignment object (2 rows x 7 columns) at 0x...>
        >>> print(alignment[:, 1:])
        target            1 CCGGTTT 8
                          0 |.||||- 7
        query             1 CGGGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 2:])
        target            2 CGGTTT 8
                          0 .||||- 6
        query             2 GGGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 3:])
        target            3 GGTTT 8
                          0 ||||- 5
        query             3 GGTT- 7
        <BLANKLINE>
        >>> print(alignment[:, 3:-1])
        target            3 GGTT 7
                          0 |||| 4
        query             3 GGTT 7
        <BLANKLINE>
        >>> print(alignment[:, ::2])
        target            0 ACGT 4
                          0 |.|| 4
        query             0 AGGT 4
        <BLANKLINE>
        >>> print(alignment[:, range(1, 8, 2)])
        target            0 CGTT 4
                          0 |||- 4
        query             0 CGT- 3
        <BLANKLINE>
        >>> print(alignment[:, (2, 7, 3)])
        target            0 CTG 3
                          0 .-| 3
        query             0 G-G 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IntegralrN  r   rQ  r   r   r   r   r   r  r  r   r   r*   r   r@   r   r   r	  rB  r   rL  rX  r   r_  r   rf  rh  rm  rv  )r!   r   r   r   r  r  r   r   r  r  r   rW  rZ  r[  r\  r  s                   r$   r   zAlignment.__getitem__E  s   H c7++,==%%c5!>>#&&(	&&++-Q'eqj!$q($Y/ 	CKAx7
#Cq~~(!$QT{lad$'MK14E$EAqD!1(;	!&.kkIaLO !#=aS!ABB	C yy|$5A:.335>??Ic5!US STTc7++,QwqQw#( CsAhN  c
c7++, ~H#w//0((Q'eT8  %S!V,J#u%03A-Z+	33"KUD(  KT:..z3hOOc5!!#I%c*K#w//0))+sE4SS#u%03A-Z+	44##"  KT://S%y  ABB{ &   U !STTUs   M%M5 %	M21M25N
c                 b   t        |t        t        f      r|j                         S t        |t              r|S t        |t
              rt	        |      S 	 |j                  }t	        |      S # t        $ r Y nw xY w	 t        |      }|j                  dk(  rt	        |      S y# t        $ r Y yw xY w)zHConvert given sequence to string using the appropriate method (PRIVATE).r   N)r   r   	bytearrayrs  r`   r   r=   r   
memoryviewformatr   )r!   r   views      r$   _convert_sequence_stringz"Alignment._convert_sequence_string  s    h	 23??$$h$Oh$x= 	!||H x=   			%h'D {{c!8}$  	 	s$   A, ,	A87A8<B" "	B.-B.c                 $    | j                  |      S )zkReturn the alignment as a string in the specified file format.

        Wrapper for self.format().
        r}  )r!   ra   s     r$   rc   zAlignment.__format__	  s    
 {{;''r&   c                    |j                  dd      }d}|Z|rX|d   }t        |t              r|j                  }|dd }n1t        |t        j
                  t        j                  f      r|}|dd }|K|It        |t              r|j                  }n,t        |t        j
                  t        j                  f      r|}|dk(  r| j                  |      S t        |      }|j                  j                  dk(  rt        | d      	  |j                  dg|i |}|j                  |       S # t        $ r t        d| d	      dw xY w)
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).
         - scoring  - Optional keyword-only parameter; default=None.
                       If provided, can be:

                     - A substitution matrix (typically from the
                        `Bio.Align.substitution_matrices` submodule)
                         used to mark positive matches (:) in the alignment string
                         when two different residues have a positive score.

                     - A PairwiseAligner object, in which case its substitution
                         matrix and settings are used for determining positive matches.

        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.
        scoringNr   r   r   bz is a binary file formatz;Formatting alignments has not yet been implemented for the  format)r   r   PairwiseAlignersubstitution_matrixr   ndarrayr   r   _format_pretty_loadAlignmentIteratormoder   AlignmentWriterr   format_alignment)	r!   fmtargskwargsr  r  firstmodulewriters	            r$   r}  zAlignment.format	  sc   H **Y-"?tGE%1&+&?&?#ABxEBJJ0E0K0K#LM&+#ABx&7+>'?3&-&A&A#Gbjj2G2M2M%NO&-#"9&&':;;s##((C/u$<=>>	+V++DB4B6BF
 &&t,,	  	McURYZ	s   D. .Ec                 <   t        | j                        }|dk(  rd}nd}t        j                  | j                  d      }t        |dk7  d      dkD  }d}g }g }t        j                  | j                  j                  t        j                        }	t        t        | j                  | j                  |	            D ]v  \  }
\  }}}	 |j                  }|t        	 |d|dz
   }|j                  |      }|j                  |       	 |j                  }t!        |      }t#        |      }||| }||
|f   }t        |      dk(  r||
   }t        |dkD        t        |dk        k\  rt!        |      }||z
  |dd n/||
ddf    ||
ddf<   t%        |      }t#        |      }||z
  |dd t'        |t(              r#|j+                         sY| j-                  |      c S t'        |t.        t0        f      r	 t3        |      }|j;                         }n| j=                  |      c S |j                  |       y |j!                  d      }|j#                  d      }t        j>                  | |kD  ||      }t        |	      D ]  \  }
}t        j                  |      }|dkD  |z  }||   }||   }||k(  jA                         rAd|z  |k(  jA                         r+|ddxxx dz  ccc djC                  ||
         dz   ||
<   d}tE        d       d}d}d}g }|	ddddf   |	ddddf   z
  }|j!                  d      }|j#                  d      }t        j>                  | |kD  ||      }t        ||| j                  |	      D ]  \  }}}}|d   }|}|d   }t        ||dd |dd       D ]j  \  }}}|dk  rX||z   |k  rIt)        |      }|t        |      z
  dz
  } | dk  r|dxx   d||  dz   d z   z  cc<   n|dxx   d|z   z  cc<   |}|}|}e||k(  rd|z  }n||| }|t        |      z   |k\  r||z
  }!|!dkD  rL|dxx   |d|! z  cc<   ||!d }||k7  r-||z
  tG        ||z
        k(  r|!}n|!dz   }||k  r||z  }n||z  }||!z  }|}"t)        |      }|t        |      z
  dz
  } | dk  r|"d||  dz   d z   z  }"n|"d| z  |z   z  }"|"dz  }"|j                  |"       ||z   }|t        |      z   |k\  r|dxx   |z  cc<   ||k7  r|}|}|t        |      z  }m  |du rd}#d}$t        |      dz  }%|d|% }&||%d }'g }(t        |&|'      D ]  \  })}*|)||z   d }+|*||z   d },d
}-t        |+|,      D ]`  \  }.}/|.|/k(  r
|.dk(  r nQd}0nG|.|#k(  s|/|#k(  rd}0n:d}0|6|.dk7  r1|/dk7  r,|.jI                         |/jI                         }2}1||1|2f   dkD  rd}0|-|0z  }-b d|$|-fz  }3|(j                  |3       |$t        |-      z  }$ t        t)        t#        t#        | j                  dddf         |$                  }4|4z   |k  rY||z   |k  rd|4 d}5|&dxx   |5| j                  d   z  z  cc<   |'dxx   |5| j                  d   z  z  cc<   |(dxx   |5|$z  z  cc<   n|\  }6}7d}5|6tK        | j                  d   d      z   }"|&j                  |"       |5d|$fz  }"|(j                  |"       |5|7| j                  d   fz  }"|'j                  |"       |j                  d
       d jC                  d! t        |&|'|(      D              S t        |      |z  }%t        t)        t#        | j                  dddf                     }4|4z   |k  rw||z   |k  r>d|4 d}5tM        |      D ]*  }
||%dz
  |
|%z  z   xx   |5| j                  |
df   z  z  cc<   , tM        |%      D 8cg c]  }8d jC                  ||8d|%         d z    }9}8ntM        |%      D 8cg c]  }8d jC                  ||8d|%         d z    }9}8g }d}5tM        |      D ]4  }
||
   tK        | j                  |
df   d      z   }"|j                  |"       6 d jC                  |      d z   }:|9j                  |:       d jC                  |9      S # t        $ r |dk(  r|
dk(  rd}nd	}nd
}Y w xY w# t        $ r Y w xY w# t4        $ r< t7        d||z
  z        }|j8                  D ]  \  }}t3        |||       |||  |}Y w xY wc c}8w c c}8w )"  Return default string representation (PRIVATE).

        Helper for self.format().

        Arguments:
         - matrix  - Optional; default=None
                     A substitution matrix (typically from the
                     `Bio.Align.substitution_matrices` submodule)
                     used to mark positive matches (:) in the alignment string
                     when two different residues have a positive score.
        r   TFr   r   
   Nr2  r7  r      ?r9   z  zInconsistent coordinatesP   rO   z ..r8   r   r;   |.:z          %9d %sz %dr   rO   r   rO   z%s%9d9dz
          rP   c              3   :   K   | ]  \  }}}| d | d | d   yw)rP   Nrt   )rI   line1line2pattern_lines       r$   rK   z+Alignment._format_pretty.<locals>.<genexpr>
  s1      0UE< 'L>E7"5s   )'r*   r   r   r  r   r  r)  r   r   r   rx   r@   r   ljustrQ   r=   minr	  r   r   r`   isascii_format_unicoder   r   r   r   r{  defined_rangesrs  _format_generalizedwherer   rR   r   absr   r}  r   );r!   matrixr  write_patternr  r  
name_widthnamesseqsr   r   r=   r   r  namer]  re  rM  rt  minstepmaxstep	row_stepsrow_alignedprefix_widthposition_width
line_widthrT   columnr[  r  	end_indexposition_textr$  restr   dashpositionr   lines1lines2pattern_linesr  r  aligned_seq1aligned_seq2patternc1c2r   c1uc2ur  final_position_widthr  name1name2r  blocksblocks;                                                              r$   r  zAlignment._format_prettyY	  sl
    6 M!M((!,eqj!$q(
((4++11277;(1 0 0':)
 3	$A$Y.vv<((   ,j1n-::j)DLLgg 	NEi.CeC.C!!W*-M=!Q& %a=1$%]Q->)??I"U*A$QT{lad(-)nyA#s#{{}//77C#z!23*C jjl//77KKg3	h ))A,))A,'G+Wg>( 	=FAsI$q=G3K!+.I!+.M]*//1i-=0557A!))DG,t3Q % !;<<	= 
12CRC0))A,))A,'G+Wg>),UD$:J:JG)T 4	!%D#y#aLEFa&K(+E9QR=#ab'(J 0!$c9!8#n4v=(+E
!/#m2D!Dq!H!A:!"Iw{}1M)MMI!"I})<<I'FE"+K+-d
AK	2As1vo3%.Daxb	QuX-	deH C< )K 7Ce<LL'+ *.}$s{ % %#t+D$'JM+c-.@@1DFzvgkm(D DDf} <<CKDLL&'.8F5 s1vo36 b	Q	)+"+KE#a& a0!	4	!j D DHE
aA2AYF12YFM #FF 3 )u$Z.%@%BC$Z.%@%BC!,= !FBRx9!trTz!-")c	')xxz288:C%c3h/!3$'qLG!  2Xw4GG$$\2CL())* $'s3s43C3CArE3J/KX+V'W#X ,,
:.06934A6C2J#(8(8(?"??J2J#(8(8(?"??J!"%x7%$uvd&6&6u&=tDDd#lH55$$T*eT%5%5e%<==d#R 99 474V  
 E
aA#&s3t/?/?2/F+G'H#I ,,z9.06934A6C"1X Na!ea!em,d6F6Fq"u6M0MM,NAFqJA$))E!$Q$K047JJAFqJA$))E!$Q$K047JJq 'A 8fT-=-=ae-Dd&KKDLL&' 		%(4/e$99V$${ " 6Av'&D " , . !$#+"67A&)&8&8 =
s',Ss^'<%=C	^ KJsC   bb<1c
!d;!db98b9<	c	c	Addc                 \   g }g }| j                   j                         }t        | j                  |      D ]  \  }}| j	                  |      }|| j                  |      c S |d   |d   kD  rt        |      |dd z
  |dd t        |      }|j                  |       	 |j                  }|dd }|j                  d	      }|j                  |        t        j                  |d
      j                  d      }g }	t        ||      D ]L  \  }}d}
|d   }t        ||d
d       D ]  \  }}||k(  r	|
d|z  z  }
n|
||| z  }
|} |	j                  |
       N t        |      dkD  rdj                  |	      dz   S |	\  }}d}t        ||      D ]Y  \  }}||k(  rd}nG|dk(  s|dk(  rd}n:d}|6|dk7  r1|dk7  r,|j!                         |j!                         }}|||f   dkD  rd}||z  }[ | d| d| dS # t        $ r2 t        | j                        dk(  rt        |      dk(  rd}nd}nd}Y |w xY w)r  Nr   rO   	   r   r2  r7  r   r  r   r   rP   r  r  r8   r  )r   r   rx   r   r  r  r*   r   rQ   r@   r   r  r   r  r	  rR   r   )r!   r  r  r  r   r=   r  r  r  aligned_seqsaligned_seqr]  r  re  r  r  r  r  r  r   r  r  s                         r$   r  zAlignment._format_unicode7
  s    &&++-DNNK8 	HC//4C{//771vBSCF*A(-KK vv BQx::b>DLL+	, Q'++A.K. 		-HCKFE AB0 	c%<3:-K3uS>1K ,		- t9q=99\*T11%1"l,5 	FBRxsbCi%")c	!xxz288:Cc3h'!+qLG	 r'"\N"==Q " t~~&!+5zQ'&Ds   G007H+*H+c                    | j                   \  }}g }g }g }| j                  dddf   \  }}|dkD  s|dkD  r||k  rZ|d||z
   D ]N  }	t        |	      }
dt        |
      z  }|j	                  |       |j	                  |
       |j	                  |       P nY|d||z
   D ]N  }t        |      }dt        |      z  }
|j	                  |       |j	                  |
       |j	                  |
       P |}|}| j                  ddddf   j                         D ]  \  }}||k(  rY||| D ]N  }	t        |	      }
dt        |
      z  }|j	                  |       |j	                  |
       |j	                  |       P |}e||k(  rY||| D ]N  }t        |      }dt        |      z  }
|j	                  |       |j	                  |
       |j	                  |
       P |}||| }||| }t        |      t        |      k7  rt        d      t        ||      D ]  \  }}	t        |      }t        |	      }
t        |      }t        |
      }||	k(  rd}n0d}|,|j                         |	j                         }}|||f   dkD  rd	}||k  r%||z
  dz  }||z  }|j	                  ||z  |z          n>||kD  r%||z
  dz  }|
|z  }
|j	                  ||z  |z          n|j	                  ||z         |j	                  |       |j	                  |
        |}|} dj                  |      }dj                  |      }dj                  |      }| d
| d
| d
S )a  Return generalized string representation (PRIVATE).

        Helper for self._format_pretty().

        Arguments:
         - matrix  - Optional; default=None
                     A substitution matrix (typically from the
                     `Bio.Align.substitution_matrices` submodule)
                     used to mark positive matches (:) in the alignment string
                     when two different residues have a positive score.
        Nr   r8   r   r   r  r  r  r  rP   )
r   r   r`   r*   rQ   r   r   rx   r   rR   )r!   r  r   r   r  r  r  r!  r#  r  s2s1r  r   r"  t1t2m1m2pr  r  spaces                          r$   r  zAlignment._format_generalizedz
  s    ^^
d%%ad+
d!8taxt|}- 'BRBs2wB ''+ ''+NN2&' }- 'BRBs2wB ''+ ''+NN2&' **1ab51;;= 0	JD$v~vd+ 'BRBs2wB ''+ ''+NN2&' vd+ 'BRBs2wB ''+ ''+NN2&' &&&&r7c"g%$%FGG!"bk ,FBRBRBRBRBRx!-')xxz288:C%c3h/!3$'Bw!#bCeq2v~6b!#bCeq2v~6q2v. ''+ ''+1,2 a0	b xx-xx-((7#r'"\N"==r&   c                 "    | j                         S )aV  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)
        3
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 .-|.||||-|||- 13
        query             0 A-AGCCCC-TTT- 10
        <BLANKLINE>
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 -.|.||||-|||- 13
        query             0 -AAGCCCC-TTT- 10
        <BLANKLINE>
        >>> alignment = alignments[2]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 --||.|||.|||- 13
        query             0 --AAGCCCCTTT- 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)
        3
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 .-|.||||-|||- 13
        query            10 A-AGCCCC-TTT-  0
        <BLANKLINE>
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 -.|.||||-|||- 13
        query            10 -AAGCCCC-TTT-  0
        <BLANKLINE>
        >>> alignment = alignments[2]
        >>> print(alignment)
        target            0 TTAACCCCATTTG 13
                          0 --||.|||.|||- 13
        query            10 --AAGCCCCTTT-  0
        <BLANKLINE>

        r  rW   s    r$   rU   zAlignment.__str__
  s    \ {{}r&   c                     | j                   $d| j                  j                  t        |       fz  S | j                  \  }}d| j                  j                  ||t        |       fz  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...>
        z<%s object at 0x%x>z*<%s object (%i rows x %i columns) at 0x%x>)r   r>   r?   r@   r   r!   r  r   s      r$   rX   zAlignment.__repr__"  sq    4 #(''4,   zz1;NN##tH	?
 
 	
r&   c                 ,    t        | j                        S )z0Return the number of sequences in the alignment.)r*   r   rW   s    r$   rh   zAlignment.__len__I  s    4>>""r&   c                    t        | j                        }|dk(  ryt        j                  | j                  d      }t	        |dk7  d      dkD  }t        |      D ]O  }|||f   }|dk\  j                         r|dk  j                         r||ddf    ||ddf<   Ct        d|        |j                  d      }||k(  |dk  z  j                         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 -GACCTG 6
                          0 -||.|-| 7
        query             0 CGATC-G 6
        <BLANKLINE>
        >>> alignment.length
        7
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACC 4
                          0 ||.| 4
        query             1 GATC 5
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.length
        4
        r   r   Nr  r  )
r*   r   r   r  r  r   r   r   r	  r   )r!   r  r  r  r   r  r  s          r$   r)   zAlignment.lengthM  s    J   !6((!,eqj!$q(q 	CA7
#Cq~~(!$QT{lad #=aS!ABB	C yy|$5A:.335>??3t9~r&   c                 L    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 -GACCTG 6
                          0 -||.|-| 7
        query             0 CGATC-G 6
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.shape
        (2, 7)
        >>> aligner.mode = "local"
        >>> alignments = aligner.align("GACCTG", "CGATCG")
        >>> alignment = alignments[0]
        >>> print(alignment)
        target            0 GACC 4
                          0 ||.| 4
        query             1 GATC 5
        <BLANKLINE>
        >>> len(alignment)
        2
        >>> alignment.shape
        (2, 4)
        )r*   r   r)   r  s      r$   r   zAlignment.shape  s'    T   !KK1vr&   c                 *   t        | j                        dkD  rt        d      | j                  j	                         }t        j                  |d      }t        |dk7  d      dkD  }t        | j                        D ]n  \  }}|||f   }|dk\  j                         r!|dk  j                         r.||ddf    ||ddf<   t        |      ||ddf   z
  ||ddf<   bt        d|        |j                         }t        j                  |d      }t        |      j                  d      }t        j                  |      }||ddf   }||dz   ddf   }	t        j                  ||	gd      j                         }
t        j                  | j                  d      }t        | j                        D ]]  \  }}|||f   }|dk\  j                         r!|dk  j                         rt        |      |
|ddf   z
  |
|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.
        r   z=aligned is currently implemented for pairwise alignments onlyr   r   Nr  r  )r*   r   rw   r   r   r   r  r  r   r   r   r   r  r  flatnonzerostack)r!   r   r  r  r   r   r  r   startsendssegmentss              r$   r  zAlignment.aligned  s   \ t~~"%O  &&++-Q'eqj!$q($T^^4 	CKAx7
#Cq~~(!$QT{lad$'MK14E$EAqD! #=aS!ABB	C "++-!,E
q!..'WaZ(7Q;>*88VTN3==?((!,$T^^4 	CKAx7
#Cq~~(!!$X!Q$!?A #=aS!ABB	C r&   c                    t        j                  | j                  t               }| j                  j                  \  }}t        j
                  | j                  d      }t        |dk7  d      dkD  }|dd|f   }t        j                  |t              }t        |      D ]D  \  }}|dk\  j                         rd||<   |dk  j                         rd||<   8t        d|        d}d}	| j                  dddf   }
t        d|      D ]}  }|
}| j                  dd|f   }
t        |||
|      D ]S  \  }}}}|dk(  r||k  r||z   |z
  }	t        ||      |||	 *|dk(  s0||kD  s6||z   |z
  }	t        |dz
  |dz
  d      |||	 U |	} |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            2 ACTG 6
                          0 |.|| 4
        query             0 AATG 4
        <BLANKLINE>
        >>> alignment.indices
        array([[2, 3, 4, 5],
               [0, 1, 2, 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            2 ACTG 6
                          0 |.|| 4
        query             4 AATG 0
        <BLANKLINE>
        >>> alignment.indices
        array([[2, 3, 4, 5],
               [3, 2, 1, 0]])

        r   r   NFTr  rO   )r   onesr   r   r   r  r  r)  boolr   r   r   r   rx   )r!   ar  r   r  r  rk  r   r  r  r  r|   r  r]  re  rl  s                   r$   r   zAlignment.indices$  s   p WWTZZ%%%%1((!,eqj!$q(aj!hhq$& 	CFAsq~~A(!A #=aS!ABB	C 1%q! 
	AF##AqD)D'*1fdC'@ =#UC;53;C%A$UC0C!H4ZECKE	CA$UQYa<C!H= A
	 r&   c                    | j                   D cg c]&  }t        j                  t        |      t               ( }}| j
                  j                  \  }}t        j                  | j
                  d      }t        |dk7  d      dkD  }|dd|f   }t        j                  |t              }t        |      D ]D  \  }}	|	dk\  j                         rd||<   |	dk  j                         rd||<   8t        d|        d}d}
t        |dz
        D ]  }| j
                  dd|f   }| j
                  dd|dz   f   }t        ||||      D ]v  \  }	}}}|dk(  r||k  r||z   |z
  }
t        ||
      |	|| *|dk(  s0||kD  s6||z   |z
  }
|dkD  rt        ||
      |	|dz
  |dz
  d<   \|dkD  sbt        ||
      |	|dz
  dd<   x |
} |S c c}w )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            2 ACTG 6
                          0 |.|| 4
        query             0 AATG 4
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1, -1,  0,  1,  2,  3, -1]), array([0, 1, 2, 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.inverse_indices
        [array([-1,  0,  1,  2,  3,  4, -1]), array([4, 3, 1, 0])]
        >>> alignment = alignments[1]
        >>> print(alignment)
        target            2 ACTG 6
                          0 |.|| 4
        query             4 AATG 0
        <BLANKLINE>
        >>> alignment.inverse_indices
        [array([-1, -1,  0,  1,  2,  3, -1]), array([3, 2, 1, 0])]

        r   r   NFTr  rO   )r   r   r  r*   r   r   r   r  r  r)  r  r   r   r   r   rx   )r!   r   r  r  r   r  r  rk  r   r  r  r|   r  r  r]  re  rl  s                    r$   inverse_indiceszAlignment.inverse_indicesz  s   j ;?..Ihbggc(mS))II%%1((!,eqj!$q(aj!hhq$& 	CFAsq~~A(!A #=aS!ABB	C q1u 	A%%ad+F##Aq1uH-D'*1fdC'@ 	;#UC;53;C%A%*1a[CcN4ZECKE	CAQw8=aEAIa"45/4Q{EAIOO,	; A	 = Js   +Gc                    | j                   }|	 |D cg c]  }|j                   }}n|D cg c]
  } ||       }}t        t	        t        |            |j                  |      }|D cg c]  }||   	 c}| _         | j                  j                  |d      | _        yc c}w # t        $ r |}Y vw xY wc c}w c c}w )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.
        Nr   r   )	r   r@   r   r   r   r*   r   r   take)r!   r   r   r   r   ru  r   r   s           r$   r   zAlignment.sort  s    b NN	;#6?@((++@@ 5>>c(m>F>s9~.F4F4FPWX8?@u)E*@++00!< A! #"# ?@s,   B( B#B( B9-B>#B( (B65B6c                 	   | |}}t        |j                        t        |j                        k7  r6t        dt        |j                        t        |j                        fz        |j                  }|j                  }|j                  }|j                  }t        |j                        }t        |j                        }	t        j                  |d      }
t        j                  t        j                  |
      d      }|dk\  j                         rd}n!|dk  j                         rd}nt        d      t        j                  |d      }t        j                  t        j                  |      d      }|dk\  j                         rd}n!|dk  j                         rd}nt        d      |dk(  r)|dk(  r|j                         }|	|dddf   z
  |dddf<   nr|j                         }||dddf   z
  |dddf<   |j                         }||dddd	f   z
  |dddf<   |dk(  r|	|dddd	f   z
  |dddf<   n|dddd	f   |dddf<   t        j                  |d      }
|
j                  d      }|
|k(  |
dk  z  j                         st        d
      t        j                  |d      }|j                  d      }||k(  |dk  z  j                         st        d      g }t        j                  t        j                  }}t        |j                               }t        j                  t        j                  }}|D ]  \  }}||k  r||k  r n||}} t        j                  t        j                  }}|j                         D ]  \  }}||k  r||k  r	 ||k  r||k  r||z
  }n||z
  }n|k  rt||z
  }||k  r||z
  }n||z
  }|}||z   }||k7  s||k7  r0||kD  r||kD  r|j!                  ||g       |j!                  ||g       ||z   }||z   }|j!                  ||g       n%|}}|D ]  \  }}||k  r||k  r n||}} ||z
  }n||z  }||z  }||k  r||k  r||}} t        j"                  |t
        j$                        j                         } ||k7  r|	| dddf   z
  | 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 alignmentNrO   z%Unequal step sizes in first alignmentz&Unequal step sizes in second alignmentr  )r*   r7  r2  r   r   r   r  prodsignr   r   r	  r   r   re   r   rQ   r   r   r   )"r!   r   r   r   r2  r7  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   s"                                     r$   mapzAlignment.map  s   \ "&yJ
z C
(9(9$::gz''(#j.?.?*@AB  ""  !--!--!!"!!"q)ggbggfoq)1H>>GQh^^GHIIq)ggbggfoq)1H>>GQh^^GIJJc>#~+002%',q!t*<%<QT"',,.L!#l1a4&8!8LA',,.L!#l1dd7&;!;LA#~%',q$B$w*?%?QT"%1!TrT'%:QT"q)

15Vq[1668DEEq)

15Vq[1668EFF[[#++dL2245;;( 	,LE57U?$eWG	, ;;(224 %	,LE5E/go( 7?#(7?D#*W#4D!(7!2 5=#(7?D#(7?D!(!(6!1!T>Vt^%}$ !%VTN ; KK(89&~%}T4L1',eWG(4 u"U?w!+0%
  %wA B 44G E/goH  %eWGK%	,L hht2773==?g "[A%6 6K1UO	i5	r&   c                    d}t        |      }|D ]  }t        j                  |j                  d      }t	        |dk7  d      dkD  }|dd|f   }|j	                  d      \  }}||k(  rd}n%|| k(  rd}n|d|z  k(  rd}nt        d| d|       ||}||k7  st        d       t        | j                  ddddf   | j                  ddddf   z
        j                  d      j                  d      }t        j                  d	t        |      dz   ft        j                        }	d|	d
<   |t        j                  |      z  |	dddf<   t        d|	d         dg}
t        |      D ]  \  }}|| j                  |ddf   z  |	dddf<   t        d|	d         |
d<   t        |
|	      }|j                  j!                         }|dddfxx   |z  cc<   |
d   |j"                  d   g}t        ||      }|j%                  |      ||<    t'        t        |            D cg c]  }g  }	}d}|du rVd}t)        d |D              }t        |      D ]+  \  }}|j                  j*                  dk(  r|	|   j-                  |	|   d          ;|j                  d
   |k(  rY|	|   j-                  |j                  d          |j                  ddddf   |_        |j                  j/                         sd}|j                  d
   |kD  rpt        |	|         r?|j                  d   |	|   d   kD  r|z
  }nd}|	|   j-                  |	|   d   |z          |	|   j-                  |j                  d          (t0         |}|du rV|D cg c]  }|j"                  d    }
}t        j2                  |	t        j                        }	t        |
|	      }|S c c}w c c}w )zDMap each of the alignments to self, and return the mapped alignment.Nr   r   r9   zunexpected steps z, z%inconsistent step sizes in alignmentsrO   r   r   r  r(   r  FTc              3   f   K   | ])  }|j                   j                  r|j                   d     + yw)r   N)r   r  )rI   r   s     r$   rK   z#Alignment.mapall.<locals>.<genexpr>(  s2      ((-- %%d+s   /1)r   r   )r   r   r  r   r  r   r  r	  clipr   r*   r   rU  r   r   r   r   r   r  r   r  r  rQ   rj  rc  r   )r!   r   factorr   r  r  step1step2r  r   r   r   r   r&  r  r   doner  previouss                      r$   mapallzAlignment.mapall  s   *%
# 	JIGGI1115E%1*a(1,G!W*%E 99Q<LE5~5&!e)# #4UG2eW!EFF~4 !HII!	J" D$$QU+d.>.>q#2#v.FFGKKANSSTUVhh3u:>2BGG<D#bii&66AqrEk%&894@	%j1 	7LAy &)9)9!Q$)? ?K1tK,>?IaL"9k:J$00557LA&(#A,	(;(;A(>?J":|<J&NN:6JqM	7 $)Z#9:ar::emD !+ H
 !** 5 $9((--2N))+a.*<=**40H<N)))*?*?*EF,5,A,A!QR%,HI) ,,002$**408;;q>*$006Q9KK#+h#6D#$D#A--k!nR.@4.GH#A--i.C.CD.IJ#O%$&  H5 em6 >HH	Y((+H	Hhh{BGG4i5	A ;: Is   $	OOc                    | j                   j                         }t        | j                        }t	        j
                  | j                   d      }t        |dk7  d      dkD  }t        |      D ]k  \  }}|||f   }|dk\  j                         r!|dk  j                         r+t        |      ||<   t        |      ||ddf   z
  ||ddf<   _t        d|        t               }|D ]  }	 t        |      }	|j                  |	       ! dj%                  t'        |            }t)        j*                  |d      }t        |      }t-        |      D ]  }||   }||ddf   }t-        |dz   |      D ]  }||   }||ddf   }t.        j0                  t.        j0                  }}t3        ||      D ]b  \  }}||k  rT||k  rO||| }||| }t        |      t        |      k7  rt        d      t3        ||      D ]  \  }}|||fxx   d	z  cc<    ||}}d   |S # t        $ rT 	 |j                  }n# t         $ r Y nw xY w|j"                  D ]$  \  }
}t        ||
|       }	|j                  |	       & Y w xY w)
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  r   r   r   r  r   )r   r   r   r   r   r  r  r   r   r   r*   r   r   r-   r   r=   r   r  rR   r   r   r   r   r   r   rx   )r!   r   r   r  r  r   r   r  r   rt  r]  re  r   r  i1	sequence1r%  i2	sequence2r&  r   r"  r!  r#  segment1segment2r  r  s                               r$   r   zAlignment.substitutionsF  s   X &&++-(	((!,eqj!$q($Y/ 	CKAx7
#Cq~~(!1(;	!$'MK14E$EAqD! #=aS!ABB	C %! 	"H"M q!	" ''&/*!''a8	N( 	0B!"I&r1u-LBFA& 0%bM	*2q51!$ckk"%lL"A 0JD$}$#,VD#9#,VD#9x=CM9",-N"OO&)(H&= -FBb"fI,I-%)4FF0	0	0  ; * &'||H% "*"9"9 &JE3HU3/0ANN1%&&s6   +H	I5"H/.I5/	H;8I5:H;;6I54I5c                 :   d}d}d}t        |t              r|}|j                  }nPt        |t              r|}n=t        |t        j
                  t        j                  f      r|}n|t        d|      |g }t        j                  dk(  rdnd}t        | j                        }dg|z  }t	        j                  |t              }	| j                  j!                         }
t	        j"                  |
d      }t%        |dk7  d      dkD  }t'        | j                        D ]t  \  }}|||f   }t%        |dkD        t%        |dk        k  r,t)        |      }t        |      |
|ddf   z
  |
|ddf<   d|	|<   	 |j*                  }	 |j.                  }t        |t0        t2        f      r|||<   t        |t              r%t	        j4                  t3        ||      d	
      ||<   t        |t6              r|||<   t        |t        j
                        r|||<   ||||<   |.|D ](  t9        fdD              r|j;                         * n|j<                  }t	        j>                  tA        jB                  |      d	t        |            ||<   w |tE        jF                  ||
|	|      S |tE        jF                  ||
|	|      S |tE        jF                  ||
|	|      S tE        jF                  ||
|	      S # t,        $ r Y w xY w# t,        $ r |}Y w xY w)a  Count the number of identities, mismatches, and gaps of an alignment.

        This method takes a single optional argument named scoring, which can be either None
        (default), a substitution matrix, a wildcard character, or a pairwise
        aligner object:

         - If the argument is a substitution matrix, (typically from the
           ``Bio.Align.substitution_matrices`` submodule), then use it to
           calculate the total substitution score for the alignment, as well as
           the number of positive matches.
         - If the argument is a single character, then it is interpreted as the
           wildcard character. This character is ignored in the calculation of
           the number of matches, mismatches, and positives.
         - If the argument is pairwise aligner object, then use it to set the
           wildcard character (if set) and also calculate the alignment score,
           the gap scores, and the total substitution score. If the aligner has
           an associated substitution matrix, then use it to calculate these
           scores, and also calculate the number of positive matches.

        >>> 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()
        ...     print(f"{c.gaps} gaps, {c.identities} identities, {c.mismatches} mismatches")
        ...     print(alignment)
        ...
        Score = 4.0:
        2 gaps, 3 identities, 0 mismatches
        target            0 TACCG 5
                          0 -||-| 5
        query             0 -AC-G 3
        <BLANKLINE>
        Score = 4.0:
        2 gaps, 3 identities, 0 mismatches
        target            0 TACCG 5
                          0 -|-|| 5
        query             0 -A-CG 3
        <BLANKLINE>

        The counts are calculated by summing over all pairs of sequences in the
        alignment.

        An `AlignmentCounts` object has the following properties:

         - score                      - the alignment score (calculated only if the
                                        argument is a pairwise aligner, and set to None
                                        otherwise);
         - aligned                    - the number of letters aligned to each other in
                                        the alignment;
         - substitution_score         - the total substitution score of letters aligned
                                        to each other (calculated only if the argument
                                        is a pairwise aligner or a substitution matrix,
                                        and set to None otherwise);
         - identities                 - the number of identical letters in the
                                        alignment;
         - mismatches                 - the number of mismatched letters in the
                                        alignment;
         - positives                  - the number of aligned letters with a positive
                                        score (set to None if no substitution matrix is
                                        defined);
         - gap_score                  - the total gap score (calculated only if the
                                        argument is a pairwise aligner, and set to None
                                        otherwise);
         - gaps                       - the total gap length;
         - open_gaps                  - the number of gaps opened in the alignment;
         - extend_gaps                - the number of gap extensions in the alignment;
         - open_left_gaps             - the number of gaps opened on the left side of
                                        the alignment;
         - open_right_gaps            - the number of gaps opened on the right side of
                                        the alignment;
         - open_internal_gaps         - the number of gaps opened in the interior of the
                                        alignment;
         - extend_left_gaps           - the number of gap extensions on the left side of
                                        the alignment;
         - extend_right_gaps          - the number of gap extensions on the right side
                                        of the alignment;
         - extend_internal_gaps       - the number of gap extensions in the interior of
                                        the alignment;
         - open_left_insertions       - the number of insertion gaps opened on the left
                                        side of the alignment;
         - open_left_deletions        - the number of deletion gaps opened on the left
                                        side of the alignment;
         - open_right_insertions      - the number of insertion gaps opened on the right
                                        side of the alignment;
         - open_right_deletions       - the number of deletion gaps opened on the right
                                        side of the alignment;
         - open_internal_insertions   - the number of insertion gaps opened in the
                                        interior of the alignment;
         - open_internal_deletions    - the number of deletion gaps opened in the
                                        interior of the alignment;
         - extend_left_insertions     - the number of insertion gap extensions on the
                                        left side of the alignment;
         - extend_left_deletions      - the number of deletion gap extensions on the
                                        left side of the alignment;
         - extend_right_insertions    - the number of insertion gap extensions on the
                                        right side of the alignment;
         - extend_right_deletions     - the number of deletion gap extensions on the
                                        right side of the alignment;
         - extend_internal_insertions - the number of insertion gap extensions in the
                                        interior of the alignment;
         - extend_internal_deletions  - the number of deletion gap extensions in the
                                        interior of the alignment;
         - left_insertions            - the number of letters inserted on the left side
                                        of the alignment;
         - left_deletions             - the number of letters deleted on the left side
                                        of the alignment;
         - right_insertions           - the number of letters inserted on the right side
                                        of the alignment;
         - right_deletions            - the number of letters deleted on the right side
                                        of the alignment;
         - internal_insertions        - the number of letters inserted in the interior
                                        of the alignment;
         - internal_deletions         - the number of letters deleted in the interior of
                                        the alignment;
         - insertions                 - the total number of letters inserted;
         - deletions                  - the total number of letters deleted;
         - left_gaps                  - the total gap length on the left side of the
                                        alignment;
         - right_gaps                 - the total gap length on the right side of the
                                        alignment;
         - internal_gaps              - the total gap length in the interior of the
                                        alignment.
        Nzunexpected argument little	utf-32-le	utf-32-ber   r   Tr   r  c              3   (   K   | ]	  }|k(    y wrF   rt   rI   r+  items     r$   rK   z#Alignment.counts.<locals>.<genexpr>r       "If46>"Ir   r  count)$r   r  r  r`   r   r  r   r   r   r   	byteorderr*   r   r)  r  r   r   r  r  r   r   r=   r   _datar   r{  
frombufferr   rj  rQ   r#   fromiterr  r   r   AlignmentCounts)r!   r  alignerwildcardr  r#   codecr  r   strandsr   r  aligned_flagsr   r   rM  r
  r"  s                    @r$   r*  zAlignment.counts  s   x "g/G")"="=%H"**.C.I.I!JK") 3G;?@@&H"}}8kFQJ	((1d#&&++-Q'EQJ*Q.$T^^4 #	KAx!!]"23M=1$%MA,=(>>-h7$'MK14E$EAqD!!
#<< ~~ $	 23#	!D#&!}}YtU-C3O	!D"?@#	!D"**-  $	!#	!&. $ 2""I"II$OOD12  3;;H!{{-SD	 	!C#	H #33;  !#33;  !,#33;1D  $33I{GTTS "  "   s$   6K;L;	LLLLc                 <   | j                   D cg c]  }t        |       }}t        j                  t	        || j
                        D cg c]  \  }}t        |      |ddd   z
   c}}t        j                        }t        ||      }	 | j                  }i |_	        |j                         D ]M  \  }}t        |t        j                        r|ddd   j                         }n|ddd   }||j                  |<   O |S c c}w c c}}w # t        $ r Y |S w xY w)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]}
        NrO   r  )r   r   r   r   rx   r   r*   r   r   r    ry   r   r  r   r   )	r!   r   r   r  r   r   r    r   r.   s	            r$   r   zAlignment.reverse_complement  s)   4 CG..Qh'1Q	Qhh &)D4D4D%E!Hc HDbD	) ''
 i5		:!%!8!8 ,.I(0668 :
UeRZZ0!$B$K,,.E!$B$KE49	,,S1: + R  	 	s   DD
D 	DDrF   )NN)r   r   )4r?   r   r   r   classmethodr   r   rB  r   r%   r  r~   r   r-  r2  setterr7  r=  r?  rC  rF  rH  rJ  rN  rQ  rX  r_  rf  rh  rm  rv  r   r  rc   r}  r  r  r  rU   rX   rh   r)   r   r  r   r  r   r  r  r   r*  r   rt   r&   r$   r   r     s
    1& 1&f z/k*U;-??z/	z/ z/x'>1f~@ V Vp 	! 	! ]]" " ! ! \\" "CG 22229v.&^@1f,/bAFtCl.(>-@\%|A>FV>pN`%
N# 5 5n + +Z n n` S Sj R Rh;=zsjCJ z zxCUJ/r&   r   c                   F    e Zd ZdZd Zed        Zed        Zed        Zy)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                 &    | j                          | S )zyIterate over the alignments as Alignment objects.

        This method SHOULD NOT be overridden by any subclass.
        )rewindrW   s    r$   rf   z$AlignmentsAbstractBaseClass.__iter__  s    
 	r&   c                      y)zReturn the next alignment.Nrt   rW   s    r$   __next__z$AlignmentsAbstractBaseClass.__next__      r&   c                      y)zJRewind the iterator to let it loop over the alignments from the beginning.Nrt   rW   s    r$   r6  z"AlignmentsAbstractBaseClass.rewind  r9  r&   c                      y)z Return the number of alignments.Nrt   rW   s    r$   rh   z#AlignmentsAbstractBaseClass.__len__  r9  r&   N)	r?   r   r   r   rf   r   r8  r6  rh   rt   r&   r$   r4  r4    sJ     ) ) Y Y / /r&   r4  c                   2     e Zd Zd fd	Zd Zd Zd Z xZS )
Alignmentsc                 2    t         |   |       d| _        y NrO   )superr%   _index)r!   r   r>   s     r$   r%   zAlignments.__init__  s    $r&   c                 d    | j                   dz   }	 | |   }|| _         |S # t        $ r t        w xY w)Nr   )rA  rL  rm   )r!   r   r"  s      r$   r8  zAlignments.__next__  sB    a	 ;D   	 	 s    /c                     d| _         y r?  )rA  rW   s    r$   r6  zAlignments.rewind  s	    r&   c                 ,    t         j                  |       S rF   )r   rh   rW   s    r$   rh   zAlignments.__len__  s    ||D!!r&   )rt   )r?   r   r   r%   r8  r6  rh   __classcell__r>   s   @r$   r=  r=    s    "r&   r=  c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	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                 @    ||g| _         || _        || _        d| _        y)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.
        rO   N)r   rP  _pathsrA  )r!   seqAseqBrP  pathss        r$   r%   zPairwiseAlignments.__init__  s$     
r&   c                 ,    t        | j                        S rF   )r*   rJ  rW   s    r$   rh   zPairwiseAlignments.__len__  s    4;;r&   c                     	 t        | j                        }|dk(  rd}n| d}	 t        t        |             }t        | j                  d      }d| d| d| dS # t        $ r dt        j                   d}Y Uw xY w)	Nr   z1 alignmentz alignments>gz<PairwiseAlignments object (z; score=z) at )	r*   rJ  OverflowErrorr   r   hexr@   r}  rP  )r!   r)   pointerrP  s       r$   rX   zPairwiseAlignments.__repr__  s    	0%F {&"8;/bh-tzz3'-fXXeWE'RSTT  	2[1F	2s   A A;:A;c                    t        |t              s"t        d|j                  j                         |dk  r|t        | j                        z  }|| j                  k(  r| j                  S || j                  k  r!| j                  j                          d| _        	 	 t        |       }| j                  |k(  r	 |S # t        $ r t        d      d w xY w)Nzindex must be an integer, not r   rO   zindex out of range)r   r   r   r>   r?   r*   rJ  rA  
_alignmentresetrl   rm   rL  )r!   r   r   s      r$   r   zPairwiseAlignments.__getitem__  s    %%<U__=U=U<VWXX19S%%EDKK??"4;;KKDKA J	 {{e#  ! A !56D@As   B; ;Cc                     t        | j                        }| xj                  dz  c_        t        j                  |t        j
                        }t        | j                  |      }| j                  |_        || _	        |S )Nr   r  )
rl   rJ  rA  r   r   r   r   r   rP  rV  )r!   r  r   r   s       r$   r8  zPairwiseAlignments.__next__1  sZ    DKK qhht2773dnnk:	**	#r&   c                 F    | j                   j                          d| _        y r?  )rJ  rW  rA  rW   s    r$   r6  zPairwiseAlignments.rewind:  s    r&   N)
r?   r   r   r   r%   rh   rX   r   r8  r6  rt   r&   r$   rH  rH    s&    
& U&r&   rH  c                   `    e Zd ZdZej
                  dk(  rdndZdW fd	Zi dddd	d
dddddddddddddddddddddd d!d"d#d$d%d&d'i d(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPZdQ Z	dR Z
dX fdS	ZdX fdT	ZdU ZdV Z xZS )Yr  a8  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, or the Fast
    Optimal Global Sequence Alignment Algorithm).

    The Fast Optimal Global Sequence Alignment Algorithm (FOGSAA) will never be
    automatically selected. If you wish to use FOGSAA, you must set the "mode"
    attribute to "fogsaa". As its name suggests, it only finds global
    alignments and cannot be used for local alignment. FOGSAA will raise a
    warning and may return incorrect results if the match score is less than
    the mismatch score or any gap score or if any gap score is greater than the
    mismatch score.

    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 = 1.0:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>
    Score = 1.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 = 2.0:
    target            1 AC 3
                      0 || 2
    query             0 AC 2
    <BLANKLINE>
    Score = 2.0:
    target            3 CG 5
                      0 || 2
    query             1 CG 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 = 4.0:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>
    Score = 4.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.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 = 11.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 = 4.0:
    target            0 TACCG 5
                      0 -||-| 5
    query             0 -AC-G 3
    <BLANKLINE>
    Score = 4.0:
    target            0 TACCG 5
                      0 -|-|| 5
    query             0 -A-CG 3
    <BLANKLINE>

    r  r  r  c                    t         |           |n|dk(  r)t        j                  d      | _        d| _        d| _        nj|dk(  r)t        j                  d      | _        d| _        d| _        n<|d	k(  r)t        j                  d
      | _        d| _        d| _        nt        d|z        |j                         D ]  \  }}t        | ||        y)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   loadr  open_gap_scoreextend_gap_scorer   ry   setattr)r!   r  r  r  r.   r>   s        r$   r%   zPairwiseAligner.__init__  s     	?
  '<'A'A('KD$"&D$(D!#'<'A'A+'ND$"&D$(D! '<'A'A('KD$"'D$(D!:WDEE!<<> 	'KD%D$&	'r&   target_internal_open_gap_scoreopen_internal_insertion_score target_internal_extend_gap_scoreextend_internal_insertion_scoretarget_internal_gap_scoreinternal_insertion_scoretarget_left_open_gap_scoreopen_left_insertion_scoretarget_left_extend_gap_scoreextend_left_insertion_scoretarget_left_gap_scoreleft_insertion_scoretarget_right_open_gap_scoreopen_right_insertion_scoretarget_right_extend_gap_scoreextend_right_insertion_scoretarget_right_gap_scoreright_insertion_scorequery_internal_open_gap_scoreopen_internal_deletion_scorequery_internal_extend_gap_scoreextend_internal_deletion_scorequery_left_open_gap_scoreopen_left_deletion_scorequery_left_extend_gap_scoreextend_left_deletion_scorequery_right_open_gap_scoreopen_right_deletion_scorequery_right_extend_gap_scoreextend_right_deletion_scoretarget_gap_functioninsertion_score_functionquery_gap_functiondeletion_score_functioninternal_open_gap_scoreopen_internal_gap_scoreinternal_extend_gap_scoreextend_internal_gap_scoreleft_open_gap_scoreopen_left_gap_scoreleft_extend_gap_scoreextend_left_gap_scoreright_open_gap_scoreopen_right_gap_scoreright_extend_gap_scoreextend_right_gap_scoreend_open_gap_scoreopen_end_gap_scoreend_extend_gap_scoreextend_end_gap_scoretarget_gap_scoreinsertion_scoretarget_open_gap_scoreopen_insertion_scoretarget_extend_gap_scoreextend_insertion_scoretarget_end_gap_scoreend_insertion_scoretarget_end_open_gap_scoreopen_end_insertion_scoretarget_end_extend_gap_scoreextend_end_insertion_scorequery_gap_scoredeletion_scorequery_open_gap_scoreopen_deletion_scorequery_extend_gap_scoreextend_deletion_scoreend_deletion_scoreopen_end_deletion_scoreextend_end_deletion_scoreinternal_deletion_scoreleft_deletion_scoreright_deletion_score)query_end_gap_scorequery_end_open_gap_scorequery_end_extend_gap_scorequery_internal_gap_scorequery_left_gap_scorequery_right_gap_scorec                    	 | j                   |   }t        j                  d|d|dt               |}t
        j                  j                  | ||       y # t        $ rn |dk(  r=t        j                  dt               t
        j                  j                  | ||       Y y |t        t
        j                        vrt        d|z        Y w xY w)NThe attribute '' was renamed to 'x'. This was done to be consistent with the
AlignmentCounts object returned by the .counts method of an Alignment object.r#   iThe alphabet property is deprecated. The current implementation stores the alphabet, but does not use it.z.'PairwiseAligner' object has no attribute '%s')
	_new_keyswarningswarnr   r   r
   r  __setattr__dirr   )r!   r   r.   new_keys       r$   r  zPairwiseAligner.__setattr__)  s    	nnS)G$ MM ! , C((44T3F3  	j O/
 !00<<T3N#.>>?? %DsJ 	 @	s   A A	C!)CCc                 j   	 | j                   |   }t        j                  d|d|dt               |}t
        j                  j                  | |      S # t        $ rU |dk(  rMt        j                  dt               	 t
        j                  j                  | |      cY S # t        $ r Y Y y w xY wY }w xY w)Nr  r  r  r#   r  )
r  r  r  r   r   r
   r  __getattr__r   __getattribute__)r!   r   r  s      r$   r  zPairwiseAligner.__getattr__G  s    	nnS)G MM ! , C//@@sKK)  
	 j O/
 +;;GGcRR%    !
	 s5   A (B2=BB2	B,(B2+B,,B21B2c                 &   t        |t        t        t        t        f      rNt        |      }t        j                  |t
        j                        j                  t
        j                        }nXt        |t              r:t        j                  t        || j                        t
        j                        }n	 t        |       |}|dk(  r|}nt/        |      }t        |t        t        t        t        f      rNt        |      }t        j                  |t
        j                        j                  t
        j                        }nXt        |t              r:t        j                  t        || j                        t
        j                        }n	 t        |       |}t2        | i  |||      \  }}	t7        ||||	      }
|
S # t        $ r | j                  }|0g }|D ](  t!        fd|D              r|j#                         * n|j$                  }t        j&                  t)        |j*                  |      t
        j                  t-        |            }Y w xY w# t        $ r | j                  }|C	  n# t0        $ r g }Y nw xY w|D ](  t!        fd|D              r|j#                         * n|j$                  }t        j&                  t)        |j*                  |      t
        j                  t-        |            }Y mw xY w)z=Return the alignments of two sequences using PairwiseAligner.r  c              3   (   K   | ]	  }|k(    y wrF   rt   r!  s     r$   rK   z(PairwiseAligner.align.<locals>.<genexpr>p  r#  r   r$  r  c              3   (   K   | ]	  }|k(    y wrF   rt   r!  s     r$   rK   z(PairwiseAligner.align.<locals>.<genexpr>  r#  r   )r   r   r   r   r   r   r(  uint8astypeint32r`   r{  r-  r|  r   r  rj  rQ   r#   r)  r  r   r*   r   	NameErrorr@  alignrH  )r!   rK  rL  strandsAr  r#   sBrP  rM  r   r"  r>   s              @r$   r  zPairwiseAligner.align`  sb    dUCY?@tBr299"((CBc"ytzz:"((KB4  S=B#D)BdUCY?@rBr299"((CBc"yTZZ8IB4 " w}RV4u'dE5A
[  &*&>&>#&.!H $ 2""I"II$OOD12  3;;H[[-RXXSY4  &*&>&>#&.& $ &#%& $ 2""I"II$OOD12  3;;H[[-RXXSYsV   <G I# 2I 9A#I I #L;I>=L>J	LJL)A#LLc                    t        |t        t        t        t        f      rNt        |      }t        j                  |t
        j                        j                  t
        j                        }nHt        |t              r,t        j                  t        || j                        d      }n	 t        |       |dk(  rt/        |      }t        |t        t        t        t        f      rNt        |      }t        j                  |t
        j                        j                  t
        j                        }nHt        |t              r,t        j                  t        || j                        d      }n	 t        |       t2        | i  |||      S # t        $ r | j                  }|0g }|D ](  t!        fd|D              r|j#                         * n|j$                  }t        j&                  t)        |j*                  |      t
        j                  t-        |            }Y pw xY w# t        $ r | j                  }|C	  n# t0        $ r g }Y nw xY w|D ](  t!        fd|D              r|j#                         * n|j$                  }t        j&                  t)        |j*                  |      t
        j                  t-        |            }Y Zw xY w)zBReturn the alignment score of two sequences using PairwiseAligner.r  r   c              3   (   K   | ]	  }|k(    y wrF   rt   r!  s     r$   rK   z(PairwiseAligner.score.<locals>.<genexpr>  r#  r   r$  r   c              3   (   K   | ]	  }|k(    y wrF   rt   r!  s     r$   rK   z(PairwiseAligner.score.<locals>.<genexpr>  r#  r   )r   r   r   r   r   r   r(  r  r  r  r`   r{  r-  r|  r   r  rj  rQ   r#   r)  r  r   r*   r   r  r@  rP  )r!   rK  rL  r  r  r#   r"  r>   s         @r$   rP  zPairwiseAligner.score  s2    dUCY?@;D==RXX6==bhhGDc"==4!<CHD4  S=%d+DdUCY?@;D==RXX6==bhhGDc"==4!<CHD4   w}T400K  &*&>&>#&.!H $ 2""I"II$OOD12  3;;H{{-RXXSY,  &*&>&>#&.& $ &#%& $ 2""I"II$OOD12  3;;H{{-RXXSYsV   .F 4H- 2H*A#H*)H*-KIKIKIK3A#KKc                    | j                   | j                  | j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                  d}| j                   | j                   |d<   | j"                  |d<   |S | j                  |d<   |S )N)r,  rg  ri  rm  ro  rs  ru  ry  r{  r}  r  r  r  r  epsilonmatch_scoremismatch_scorer  )r,  rg  ri  rm  ro  rs  ru  ry  r{  r}  r  r  r  r  r  r  r  r  )r!   states     r$   __getstate__zPairwiseAligner.__getstate__  s    -1-O-O/3/S/S)-)G)G+/+K+K*.*I*I,0,M,M,0,M,M.2.Q.Q(,(E(E*.*I*I)-)G)G+/+K+KII||
" ##+#'#3#3E- &*&9&9E"#  ,0+C+CE'(r&   c                    |d   | _         |d   | _        |d   | _        |d   | _        |d   | _        |d   | _        |d   | _        |d   | _        |d	   | _        |d
   | _	        |d   | _
        |d   | _        |d   | _        |d   | _        |d   | _        |j                  d      }||d   | _        |d   | _        y || _        y )Nr,  rg  ri  rm  ro  rs  ru  ry  r{  r}  r  r  r  r  r  r  r  r  )r,  rg  ri  rm  ro  rs  ru  ry  r{  r}  r  r  r  r  r  r   r  r  r  )r!   r  r  s      r$   __setstate__zPairwiseAligner.__setstate__  s   j)-23R-S*/45V/W,)./J)K&+01N+O(*/0L*M',12P,Q),12P,Q).34T.U+(-.H(I%*/0L*M')./J)K&+01N+O(&M	Y'#ii(=>&$]3D"'(8"9D':D$r&   rF   )r  )r?   r   r   r   r   r&  r-  r%   r  r  r  r  rP  r  r  rE  rF  s   @r$   r  r  ?  s%   Vp ==H4K+E"'H)(*I)*,M) 	$%?) 	%&A	)
 	'(E) 	 !7) 	&'C) 	()G) 	!"9) 	()G) 	*+K) 	$%?) 	&'C) 	%&A) 	'(E)  	9!)" 	7#)$ 	"#<%)& 	$%@')( 	4))* 	 !8+), 	 6-). 	!":/)0 	21)2 	 63)4 	-5)6 	 !77)8 	"#;9): 	 5;)< 	$%?=)> 	&'C?)@ 	+A)B 	 5C)D 	!"9E)F  4$=&A$= 5!7Q)IVG<L28t01d2;r&   r  c                   8     e Zd ZdZd fd	Z fdZ fdZ x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.
    c                     t         |           |t        j                  d   }|| _        yt	        |t        j                        st        d      || _        y)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>   s      r$   r%   zCodonAligner.__init__  sV     	$2215K ' K)>)>?DEE&r&   c                 6   | j                   }t        |t        t        t        f      rt        |      }n,t        |t              r|j                         }nt        d      |ddt        |      dz  z   }|dddt        |      dz
  dz  z  z    }|dddt        |      dz
  dz  z  z    }t        |t        t        t        f      rU|j                  |      }|j                  |      }	|j                  |      }
t        |      }t        |	      }	t        |
      }
npt        |t              rUt        ||      }t        ||      }	t        ||      }
|j                         }|	j                         }	|
j                         }
nt        d      t        | 1  |||	|
      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 objectNr9   r   r   ;seqB must be a string, Seq, MutableSeq, or SeqRecord object)r  r   r   r   r   r   r`   rq  r   r*   r   r@  rP  )r!   rK  rL  r  r  seqB0seqB1seqB2sB0sB1sB2r>   s              r$   rP  zCodonAligner.score  s~   P &&dS*i89tBc"BM  +qCIN+,QQ3t9q=Q"6778QQ3t9q=Q"6778dS*i89//+.C//+.C//+.C*C*C*Cc"E;/CE;/CE;/C**,C**,C**,CM  w}Rc3//r&   c                 \   | j                   }t        |t        t        t        f      rt        |      }n,t        |t              r|j                         }nt        d      |ddt        |      dz  z   }|dddt        |      dz
  dz  z  z    }|dddt        |      dz
  dz  z  z    }t        |t        t        t        f      rU|j                  |      }|j                  |      }	|j                  |      }
t        |      }t        |	      }	t        |
      }
npt        |t              rUt        ||      }t        ||      }	t        ||      }
|j                         }|	j                         }	|
j                         }
nt        d      t        | 1  |||	|
      \  }}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  Nr9   r   r   r  )r  r   r   r   r   r   r`   rq  r   r*   r   r@  r  rH  )r!   rK  rL  r  r  r  r  r  r  r  r  rP  rM  r   r>   s                 r$   r  zCodonAligner.align{  s   Z &&dS*i89tBc"BM  +qCIN+,QQ3t9q=Q"6778QQ3t9q=Q"6778dS*i89//+.C//+.C//+.C*C*C*Cc"E;/CE;/CE;/C**,C**,C**,CM  w}Rc37u'dE5A
r&   )Nr  )r?   r   r   r   r%   rP  r  rE  rF  s   @r$   r  r    s     'f0PM Mr&   r  )a2mbedbigbedbigmafbigpslchainclustalemboss	exoneratefastahhrmafmauvemsfnexusphylippslsam	stockholmtabular_modulesr  r   c                     | j                         } 	 t        |    S # t        $ r Y nw xY w| t        vrt	        d| z        t        j                  d|        }|t        | <   |S )NzUnknown file format %sz
Bio.Align.)lowerr  r   formatsr   	importlibimport_module)r  r  s     r$   r  r    sl    
))+C} 
'1C788$$z#%78FHSMMs    	''c                     t        | t              r| g} t        |      }	 |j                  } ||g|i |j                  |       S # t        $ r t        d| d      w xY w)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 r  )r   r   r  r  r   r   r^   )r   r2  r  r  r  r  r  s          r$   r^   r^     sz     *i( \
3ZF
''
 &*4*6*00<<	  
@WM
 	

s   A A c                 >    t        |      }|j                  |       }|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.
    )r  r  )sourcer  r  r   s       r$   parser    s#    8 3ZF))&1Jr&   c                     t        | |      5 }	 t        |      }	 t        |       t        d      # t        $ r t        d      dw xY w# t        $ r Y nw xY w	 ddd       |S # 1 sw Y   S xY 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)r  rl   rm   r   )rb   r  r   r   s       r$   readr	  2  s    J 
vs	 	z	FZ(I	DEE	  	F:;E	F
  			 	 s7   A$1A
AA$
	AA$AA$$A.__main__)run_doctest)9r   r   r  rx  r   typesr  abcr   r   	itertoolsr   numpyr   ImportErrorr]   r   r   	Bio.Alignr   r	   r
   r   r   Bio.Datar   Bio.Seqr   r   r   r   r   r   Bio.SeqRecordr   r   r   r   r4  r   r=  rH  r  r  r  r  r   r`   
ModuleType__annotations__r  r^   r  r	  r?   
Bio._utilsr  rt   r&   r$   <module>r     s\      
     ! ,   # & & +   &   * 1 ) #i iXP/ P/f^/# /<",d "*O4 Od{;&66 {;|K=-- K`0 )+$sE$$$
% *
s 
u'' 
=8B/d z&M QZ  0
&Vs   D4 4E	