
    &h                        d 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  ej                  de       dZ
 ed	d
      Z G d d      Z e       Zd Zd Zd Z	 d%dZd Zd Zd Zd Zd ZdZefdZ G d d      Z G d d      Z G d d      Zd Zd Zd%dZeZeZ	 d d!l mZmZ e"d#k(  rdd$l#m$Z$  e$        yy# e!$ r  ej                  d"e       Y .w xY w)&ai!  Pairwise sequence alignment using a dynamic programming algorithm.

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. Local alignments must have a positive
score to be reported and they will not be extended for 'zero counting'
matches. This means a local alignment will always start and end with
a positive counting match.

When doing alignments, you can specify the match score and gap
penalties.  The match score indicates the compatibility between an
alignment of two characters in the sequences. Highly compatible
characters should be given positive scores, and incompatible ones
should be given negative scores or 0.  The gap penalties should be
negative.

The names of the alignment functions in this module follow the
convention
<alignment type>XX
where <alignment type> is either "global" or "local" and XX is a 2
character code indicating the parameters it takes.  The first
character indicates the parameters for matches (and mismatches), and
the second indicates the parameters for gap penalties.

The match parameters are::

    CODE  DESCRIPTION & OPTIONAL KEYWORDS
    x     No parameters. Identical characters have score of 1, otherwise 0.
    m     A match score is the score of identical chars, otherwise mismatch
          score. Keywords ``match``, ``mismatch``.
    d     A dictionary returns the score of any pair of characters.
          Keyword ``match_dict``.
    c     A callback function returns scores. Keyword ``match_fn``.

The gap penalty parameters are::

    CODE  DESCRIPTION & OPTIONAL KEYWORDS
    x     No gap penalties.
    s     Same open and extend gap penalties for both sequences.
          Keywords ``open``, ``extend``.
    d     The sequences have different open and extend gap penalties.
          Keywords ``openA``, ``extendA``, ``openB``, ``extendB``.
    c     A callback function returns the gap penalties.
          Keywords ``gap_A_fn``, ``gap_B_fn``.

All the different alignment functions are contained in an object
``align``. For example:

    >>> from Bio import pairwise2
    >>> alignments = pairwise2.align.globalxx("ACCGT", "ACG")

For better readability, the required arguments can be used with optional keywords:

    >>> alignments = pairwise2.align.globalxx(sequenceA="ACCGT", sequenceB="ACG")

The result is a list of the alignments between the two strings. Each alignment
is a named tuple consisting of the two aligned sequences, the score and the
start and end positions of the alignment:

   >>> print(alignments)
   [Alignment(seqA='ACCGT', seqB='A-CG-', score=3.0, start=0, end=5), ...

You can access each element of an alignment by index or name:

   >>> alignments[0][2]
   3.0
   >>> alignments[0].score
   3.0

For a nice printout of an alignment, use the ``format_alignment`` method of
the module:

    >>> from Bio.pairwise2 import format_alignment
    >>> print(format_alignment(*alignments[0]))
    ACCGT
    | || 
    A-CG-
      Score=3
    <BLANKLINE>

All alignment functions have the following arguments:

- Two sequences: strings, Biopython sequence objects or lists.
  Lists are useful for supplying sequences which contain residues that are
  encoded by more than one letter.

- ``penalize_extend_when_opening``: boolean (default: False).
  Whether to count an extension penalty when opening a gap. If false, a gap of
  1 is only penalized an "open" penalty, otherwise it is penalized
  "open+extend".

- ``penalize_end_gaps``: boolean.
  Whether to count the gaps at the ends of an alignment. By default, they are
  counted for global alignments but not for local ones. Setting
  ``penalize_end_gaps`` to (boolean, boolean) allows you to specify for the
  two sequences separately whether gaps at the end of the alignment should be
  counted.

- ``gap_char``: string (default: ``'-'``).
  Which character to use as a gap character in the alignment returned. If your
  input sequences are lists, you must change this to ``['-']``.

- ``force_generic``: boolean (default: False).
  Always use the generic, non-cached, dynamic programming function (slow!).
  For debugging.

- ``score_only``: boolean (default: False).
  Only get the best score, don't recover any alignments. The return value of
  the function is the score. Faster and uses less memory.

- ``one_alignment_only``: boolean (default: False).
  Only recover one alignment.

The other parameters of the alignment function depend on the function called.
Some examples:

- Find the best global alignment between the two sequences. Identical
  characters are given 1 point. No points are deducted for mismatches or gaps.

    >>> for a in pairwise2.align.globalxx("ACCGT", "ACG"):
    ...     print(format_alignment(*a))
    ACCGT
    | || 
    A-CG-
      Score=3
    <BLANKLINE>
    ACCGT
    || | 
    AC-G-
      Score=3
    <BLANKLINE>

- Same thing as before, but with a local alignment. Note that
  ``format_alignment`` will only show the aligned parts of the sequences,
  together with the starting positions.

    >>> for a in pairwise2.align.localxx("ACCGT", "ACG"):
    ...     print(format_alignment(*a))
    1 ACCG
      | ||
    1 A-CG
      Score=3
    <BLANKLINE>
    1 ACCG
      || |
    1 AC-G
      Score=3
    <BLANKLINE>

  To restore the 'historic' behaviour of ``format_alignemt``, i.e., showing
  also the un-aligned parts of both sequences, use the new keyword parameter
  ``full_sequences``:

    >>> for a in pairwise2.align.localxx("ACCGT", "ACG"):
    ...     print(format_alignment(*a, full_sequences=True))
    ACCGT
    | || 
    A-CG-
      Score=3
    <BLANKLINE>
    ACCGT
    || | 
    AC-G-
      Score=3
    <BLANKLINE>


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

    >>> for a in pairwise2.align.globalmx("ACCGT", "ACG", 2, -1):
    ...     print(format_alignment(*a))
    ACCGT
    | || 
    A-CG-
      Score=6
    <BLANKLINE>
    ACCGT
    || | 
    AC-G-
      Score=6
    <BLANKLINE>

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

    >>> for a in pairwise2.align.globalms("ACCGT", "ACG", 2, -1, -.5, -.1):
    ...     print(format_alignment(*a))
    ACCGT
    | || 
    A-CG-
      Score=5
    <BLANKLINE>
    ACCGT
    || | 
    AC-G-
      Score=5
    <BLANKLINE>

- Note that you can use keywords to increase the readability, e.g.:

    >>> a = pairwise2.align.globalms("ACGT", "ACG", match=2, mismatch=-1, open=-.5,
    ...                              extend=-.1)

- Depending on the penalties, a gap in one sequence may be followed by a gap in
  the other sequence.If you don't like this behaviour, increase the gap-open
  penalty:

    >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -1, -.1):
    ...     print(format_alignment(*a))
    A-
    <BLANKLINE>
    -T
      Score=-2
    <BLANKLINE>
    >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -3, -.1):
    ...	    print(format_alignment(*a))
    A
    .
    T
      Score=-4
    <BLANKLINE>

- The alignment function can also use known matrices already included in
  Biopython (in ``Bio.Align.substitution_matrices``):

    >>> from Bio.Align import substitution_matrices
    >>> matrix = substitution_matrices.load("BLOSUM62")
    >>> for a in pairwise2.align.globaldx("KEVLA", "EVL", matrix):
    ...     print(format_alignment(*a))
    KEVLA
     ||| 
    -EVL-
      Score=13
    <BLANKLINE>

- With the parameter ``c`` you can define your own match- and gap functions.
  E.g. to define an affine logarithmic gap function and using it:

    >>> from math import log
    >>> def gap_function(x, y):  # x is gap position in seq, y is gap length
    ...     if y == 0:  # No gap
    ...         return 0
    ...     elif y == 1:  # Gap open penalty
    ...         return -2
    ...     return - (2 + y/4.0 + log(y)/2.0)
    ...
    >>> alignment = pairwise2.align.globalmc("ACCCCCGT", "ACG", 5, -4,
    ...                                      gap_function, gap_function)

  You can define different gap functions for each sequence.
  Self-defined match functions must take the two residues to be compared and
  return a score.

To see a description of the parameters for a function, please look at
the docstring for the function via the help function, e.g.
type ``help(pairwise2.align.localds)`` at the Python prompt.

    N)
namedtuple)BiopythonDeprecationWarning)BiopythonWarning)substitution_matricesa  Bio.pairwise2 has been deprecated, and we intend to remove it in a future release of Biopython. As an alternative, please consider using Bio.Align.PairwiseAligner as a replacement, and contact the Biopython developers if you still need the Bio.pairwise2 module.i  	AlignmentzseqA, seqB, score, start, endc                   *    e Zd ZdZ G d d      Zd Zy)alignay  Provide functions that do alignments.

    Alignment functions are called as:

      pairwise2.align.globalXX

    or

      pairwise2.align.localXX

    Where XX is a 2 character code indicating the match/mismatch parameters
    (first character, either x, m, d or c) and the gap penalty parameters
    (second character, either x, s, d, or c).

    For a detailed description read the main module's docstring (e.g.,
    type ``help(pairwise2)``).
    To see a description of the parameters for a function, please
    look at the docstring for the function, e.g. type
    ``help(pairwise2.align.localds)`` at the Python prompt.
    c                   r    e Zd ZdZg dfddgdfdgdfdgd	fd
Zg dfddgdfg ddfddgdfdZd Zd Zd Zy)align.alignment_functionzCallable class which impersonates an alignment function.

        The constructor takes the name of the function.  This class
        will decode the name of the function to figure out how to
        interpret the parameters.
         matchmismatchzgmatch is the score to given to identical characters.
mismatch is the score given to non-identical ones.
match_dictzmatch_dict is a dictionary where the keys are tuples
of pairs of characters and the values are the scores,
e.g. ('A', 'C') : 2.5.match_fnz]match_fn is a callback function that takes two characters and returns the score between them.)xmdcopenextendzbopen and extend are the gap penalties when a gap is
opened and extended.  They should be negative.)openAextendAopenBextendBz~openA and extendA are the gap penalties for sequenceA,
and openB and extendB for sequenceB.  The penalties
should be negative.gap_A_fngap_B_fnzgap_A_fn and gap_B_fn are callback functions that takes
(1) the index where the gap is opened, and (2) the length
of the gap.  They should return a gap penalty.)r   sr   r   c                    |j                  d      rt        |      dk7  r@t        d      |j                  d      rt        |      dk7  rt        d      t        |      |dd |d   |d	   }}}	 | j                  |   \  }}	 | j
                  |   \  }}ddg}	|	j                  |       |	j                  |       || _        || _        |	| _	        | j                  | _
        | j                   ddj                  | j                         d}
|
dz  }
|r	|
d| dz  }
|r	|
d| dz  }
|
dz  }
|
| _        y# t        $ r t        d
|      w xY w# t        $ r t        d|      w xY w)z:Check to make sure the name of the function is reasonable.global   zfunction should be globalXXlocal   zfunction should be localXXNzunknown match type zunknown penalty type 	sequenceA	sequenceB(z, z) -> alignments
z
The following parameters can also be used with optional
keywords of the same name.


sequenceA and sequenceB must be of the same type, either
strings, lists or Biopython sequence objects.


a	  
alignments is a list of named tuples (seqA, seqB, score,
begin, end). seqA and seqB are strings showing the alignment
between the sequences.  score is the score of the alignment.
begin and end are indexes of seqA and seqB that indicate
where the alignment occurs.
)
startswithlenAttributeError
match2argsKeyErrorpenalty2argsr   function_name
align_typeparam_names__name__join__doc__)selfnamer0   
match_typepenalty_type
match_args	match_docpenalty_argspenalty_docr1   docs              \/mounts/lovelace/software/anaconda3/envs/py312/lib/python3.12/site-packages/Bio/pairwise2.py__init__z!align.alignment_function.__init__l  s   x(t9>()FGG)t9>()EFF$T**379d2hRL
JK(,
(C%
IO,0,=,=l,K)k
 '4Kz*|,!%D(DO*D ..DM]]O1TYYt/?/?%@$AARSC  C I;b))K=++  C DLG  K$'::.%IJJK  O$'<\<L%MNNOs   0D4 E 4EE'c           
         |j                         }|t        | j                        t        |      z
  dz  z  }|j                         D ]A  }|| j                  v s| j                  j                  |      }|d| ||   fz   ||d z   }||= C t	        d |D              }t        |      t        | j                        k7  r7t        d| j                  t        | j                        t        |      fz        d}|t        | j                        k  r| j                  |   dv r||   || j                  |   <   |dz  }nl| j                  |   dk(  r:| j                  |dz      d	k(  sJ ||   ||dz      }}t        ||      |d
<   |dz  }n | j                  |   dk(  rt        ||         |d
<   |dz  }n| j                  |   dk(  r\| j                  |dz      dk(  sJ ||   ||dz      }	}|j                  dd      }
t        ||	|
      |d<   t        ||	|
      |d<   |dz  }n| j                  |   dk(  r\| j                  |dz      dk(  sJ |||dz    \  }}}}|j                  dd      }
t        |||
      |d<   t        |||
      |d<   |dz  }nt        d| j                  |         |t        | j                        k  r|j                  dd      }
d
t        dd      fdt        dd|
      fdt        dd|
      fdd| j                  dk(  fd| j                  dk(  fddddg
}|D ]  \  }}|j                  ||      ||<    |d   }	 t        |      }|dk(  sJ |S # t
        $ r t	        |gdz        |d<   Y |S w xY w)zDecode the arguments for the _align function.

            keywds will get passed to it, so translate the arguments
            to this function into forms appropriate for _align.
            NNc              3   &   K   | ]	  }||  y wrA    ).0args     r>   	<genexpr>z2align.alignment_function.decode.<locals>.<genexpr>  s     @@s   z'%s takes exactly %d argument (%d given)r   )r%   r&   r   r   r      r   r   r      r   r   r   penalize_extend_when_openingr   r   r      r      zunknown parameter )rI   r   penalize_end_gapsr   align_globally)gap_char-)force_genericr   )
score_onlyr   )one_alignment_onlyr   )copyr*   r1   indextuple	TypeErrorr/   identity_matchdictionary_matchgetaffine_penalty
ValueErrorr0   )r5   argskeywdskey_indexir   r   r   r   per   r   r   r   default_paramsr6   defaultvaluens                       r>   decodezalign.alignment_function.decode  s    [[]F S))*SY6'AAD{{} $$***!--33C8F=F3K>9DMIDs	$
 @@@D4yC 0 011=))3t/?/?+@#d)LM 
 Ac$**++##A& +  37q'F4++A./FA%%a(G3++AE2j@@&*1gtAE{8E)7x)HF:&FA%%a(L8)9$q')BF:&FA%%a(F2++AE2h>>#'7DQK&D$BAFB)7fb)IF:&)7fb)IF:&FA%%a(G3++AE2i??59!a!e_2E7E7$BAFB)7w)KF:&)7w)KF:&FA$'9$:J:J1:M9P%QRRC c$**++J :A>B^Aq12^Aq"56^Aq"563$doo&AB!4??h#>?!$!)N "0 9g%zz$8t9./EJ AvM	  A.3UGaK.@*+ M	As   M M>=M>c                 <     | j                   |i |}t        di |S )z,Call the alignment instance already created.rC   )rf   _align)r5   r\   r]   s      r>   __call__z!align.alignment_function.__call__  s%     T[[$1&1F#F##    N)	r2   
__module____qualname__r4   r,   r.   r?   rf   ri   rC   rj   r>   alignment_functionr   :  s    	 b*%E ) A

* b"A 9& Z(A
*0	dS	j	$rj   rm   c                     | j                  |      }t        |      }|j                  j                         }|j                  |d<   t        dt
        f|      } ||      S )z=Call alignment_function() to check and decode the attributes.r4   rm   )rm   type__dict__rS   r4   object)r5   attrwrapperwrapper_typewrapper_dictnew_alignment_functions         r>   __getattr__zalign.__getattr__  s\     ))$/G}#,,113")//Y!%&:VI|!T%d++rj   N)r2   rk   rl   r4   rm   rw   rC   rj   r>   r	   r	   $  s    *|$ |$|
,rj   r	   c                    | r|sg S 	 | |z    ||z    t        | t              st        |       } t        |t              st        |      }|s$|d   s|d   rt	        j
                  dt               |	sft        |t              rVt        |t              rF|j                  |j                  }}|j                  |j                  }}t        | ||||||||||
      }nt        | |||||||
      }|\  }}}|
r|S t        |||      }t        | ||||||||||      }|sCt        ||      \  }}|D cg c]  \  }\  }}|||ff }}}}t        || |||||||||d      }|S # t         $ r t        d      w xY wc c}}}w )zReturn optimal alignments between two sequences (PRIVATE).

    This method either returns a list of optimal alignments (with the same
    score) or just the optimal score.
    zboth sequences must be of the same type, either string/sequence object or list. Gap character must fit the sequence type (string or list)r   rG   z]"penalize_end_gaps" should not be used in local alignments. The resulting score may be wrong.T)reverse)rV   
isinstanceliststrwarningswarnr   rZ   r   r   _make_score_matrix_fast_make_score_matrix_generic_find_start_recover_alignments_reverse_matrices)r%   r&   r   r   r   rI   rL   rM   rN   rP   rQ   rR   open_Aextend_Aopen_Bextend_Bmatricesscore_matrixtrace_matrix
best_scorestarts
alignmentszr   ys                            r>   rh   rh     s   & I	
HH i&	N	i&	N	037H7K<	
 x0x0#==(//#==(//*(
 .	
 .6*L,
 z>BF %J %6|\%R"l/566)!Va1q!f+66(

 {  
5
 	

\ 7s   
E +E3E0c           	      r   d}t        |       t        |      }
}	g g c}t        |	dz         D ]5  }j                  dg|
dz   z         |r|j                  dg|
dz   z         7 t        |	dz         D ]  }|d   r
 d|      }nd}||   d<    t        |
dz         D ]  }|d   r
 d|      }nd}|d   |<    t        d|	dz         D ]  t        d|
dz         D ]  dz
     dz
      || dz
     |dz
           z   }|d   s/|	k(  r*   dz
     }t        fdt              D              }n5   dz
      d      z   }t        fdt              D              }|d   s/|
k(  r*dz
        }t        fdt              D              }n5dz
         d      z   }t        fdt              D              }t        |||||      }t        ||      }|s|dk  r	d   <   n|   <   |r1d}t	        |      t	        |      k(  r|d	z  }t	        |      t	        |      k(  r|dz  }t	        |      t	        |      k(  r|d
z  }t	        |      t	        |      k(  r|dz  }t	        |      t	        |      k(  r|dz  }||   <     |s|}|fS )a;  Generate a score and traceback matrix (PRIVATE).

    This implementation according to Needleman-Wunsch allows the usage of
    general gap functions and is rather slow. It is automatically called if
    you define your own gap functions. You can force the usage of this method
    with ``force_generic=True``.
    r   rG   N        c              3   .   K   | ]  }   |     y wrA   rC   )rD   r   rowr   s     r>   rF   z-_make_score_matrix_generic.<locals>.<genexpr>  s      J!c!21!5 J   c              3   H   K   | ]  }   |    |z
        z     y wrA   rC   )rD   r   colr   r   r   s     r>   rF   z-_make_score_matrix_generic.<locals>.<genexpr>  s0      !FGL%a(8Cq+AA!   "c              3   .   K   | ]  }|        y wrA   rC   )rD   r   r   r   s     r>   rF   z-_make_score_matrix_generic.<locals>.<genexpr>  s      J!a!5 Jr   c              3   H   K   | ]  }|       |z
        z     y wrA   rC   )rD   r   r   r   r   r   s     r>   rF   z-_make_score_matrix_generic.<locals>.<genexpr>  s/      !FGLOC(8Cq+AA!r   rH   r    rK      )r*   rangeappendmaxrint)r%   r&   r   r   r   rL   rM   rQ   local_max_scorelenAlenBr   r`   scorenogap_scorerow_open
row_extendcol_open
col_extendr   trace_scorer   r   r   s      ``                @@@r>   r   r     sN   " O YY$D!#RL,4!8_ 5TFdQh/0$( 345 4!8_ #QQNEE"Q# 4!8_ #QQNEE"Q# Qq! 95D1H% 8	5C
 S1W%cAg.9S1W-yq/ABC  %Q'C4K',S1W5  JuSz JJ
',S1W5a8HH  !KPQT:! 

 %Q'C4K'a05  JuSz JJ
'a05a8HH  !KPQT:! 
 [(J*UJ!/:>O!j1n),S!#&)3S!#& $Z(881$K>T*%551$K
#tJ'771$K>T*%551$K
#tJ'772%K)4S!#&q8	595v $
z11rj   c           	         t        d|||      }t        d|||      }d}t        |       t        |      }}g g }}t        |dz         D ]5  }|j                  dg|dz   z         |
r|j                  dg|dz   z         7 t        |dz         D ]   }|d   rt        ||||      }nd}|||   d<   " t        |dz         D ]   }|d   rt        ||||      }nd}||d   |<   " dg}t        d|dz         D ]"  }|j                  t        |d|z  ||             $ t        d|dz         D ]  }t        |d|z  ||      }t        d|dz         D ]z  }||dz
     |dz
      || |dz
     ||dz
           z   }|d   s||k(  r||   |dz
     }|}n||   |dz
     |z   }||z   }t	        ||      }|d   s||k(  r||dz
     |   }||   }n||dz
     |   |z   }||   |z   }t	        ||      ||<   t	        |||   |      }t	        ||      }|	s|dk  r	d||   |<   n|||   |<   |
rt        |      }t        ||         }d} d}!t        |      |k(  r| dz  } t        |      |k(  r| dz  } t        |      |k(  r|!dz  }!t        |      |k(  r|!dz  }!d}"t        |      }#t        |      |#k(  r|"dz  }"||#k(  r|"| z  }"||#k(  r|"|!z  }"|"||   |<   }  |	s|}||fS )a  Generate a score and traceback matrix according to Gotoh (PRIVATE).

    This is an implementation of the Needleman-Wunsch dynamic programming
    algorithm as modified by Gotoh, implementing affine gap penalties.
    In short, we have three matrices, holding scores for alignments ending
    in (1) a match/mismatch, (2) a gap in sequence A, and (3) a gap in
    sequence B, respectively. However, we can combine them in one matrix,
    which holds the best scores, and store only those values from the
    other matrices that are actually used for the next step of calculation.
    The traceback matrix holds the positions for backtracing the alignment.
    rG   r   NrH   r    rK   r   )calc_affine_penaltyr*   r   r   r   r   )$r%   r&   r   r   r   r   r   rI   rL   rM   rQ   first_A_gapfirst_B_gapr   r   r   r   r   r`   r   	col_scorer   	row_scorer   r   r   r   r   r   r   row_score_rintcol_score_rintrow_trace_scorecol_trace_scorer   best_score_rints$                                       r>   r   r     s   0 &a;WXK%a;WXKO
 YY$D!#R,L4!8_ 5TFdQh/0$( 345 4!8_ #Q'68%AE E"Q# 4!8_ #Q'68%AE E"Q# I1dQh 
1v:x9UV	

 Qq! I5'VX'C
	 D1H% E	5C
 S1W%cAg.9S1W-yq/ABC  %Q'C4K',S1W5&
',S1W5C&1
Hj1I %Q'C4K'a05&s^
'a05C&s^h6
 :6IcN[)C.)DJ!/:>O!j1n)*S!#&)3S!#& !%i!%in!5"#"#>^3#q(O
#~5#q(O>^3#q(O
#~5#r)O"&z"2$71$K!_4?2K!_4?2K)4S!#&KE	5	I5V $
z11rj   c                    t        |       t        |      }}| dd |dd }}g }g }|D ]  }|\  }\  }}d}|rd}n||dz
  |dz
  ff|v r!|dk  r'||   |   }||dz  z
  dz  dk(  r	d||   |<   nGt        ||z
  ||z
         }|sd}||z
  }||z
  }||z
  |z  | |dz
  |dz
  d   z   }||z
  |z  ||dz
  |dz
  d   z   }||||||d||   |   fgz  } |rt        |      t        k  r d}|j                         \  }}}}}}}|dkD  s|dkD  rn|sk|dd |dd ||||f}|s|r|rd}nt	        | ||||||      \  }}n>|dz  dk(  r"|dz  }|rd}n|dz  }||z  }||||dz    z  }d}n|dz  dk(  r(|dz  }|dz  }|dz  }|| ||dz    z  }||||dz    z  }d}n|d	z  dk(  r|dz  }|dz  }|| ||dz    z  }||z  }d}ng|d
v r2|d	z  }|rd}nYd}t        | ||||||||||||	||d||      }|\  }}}}}}n1|dk(  r,|dz  }d}t        | ||||||||||||
||d||      }|\  }}}}}}|r||fz  }|j                  |       ||   |   }|s'||   |   |k(  rd}n||   |   dk  rt        ||      }d}|dkD  s|dkD  r|sk|sU|s#|j                  |ddd   |ddd   |f       n"|j                  |ddd   |ddd   |f       |r	 t        |      S |rt        |      t        k  r t        |      S )a  Do the backtracing and return a list of alignments (PRIVATE).

    Recover the alignments by following the traceback matrix.  This
    is a recursive procedure, but it's implemented here iteratively
    with a stack.

    sequenceA and sequenceB may be sequences, including strings,
    lists, or list-like objects.  In order to preserve the type of
    the object, we need to use slices on the sequences instead of
    indexes.  For example, sequenceA[row] may return a type that's
    not compatible with sequenceA, e.g. if sequenceA is a list and
    sequenceA[row] is a string.  Thus, avoid using indexes and use
    slices, e.g. sequenceA[row:row+1].  Assume that client-defined
    sequence classes preserve these semantics.
    r   NrG   rH   rK   r$   FTr    )r       r   r   r   )r*   r   MAX_ALIGNMENTSpop_finish_backtrace_find_gap_openr   _clean_alignments)r%   r&   r   r   r   r   rM   rN   rR   r   r   ry   r   r   ali_seqAali_seqB
tracebacks
in_processstartr   r   r   beginendtracecol_distancerow_distancedead_endcol_gapcacher   s                                  r>   r   r     s   : YY$D"1Q1QhHJJ %
!zSC aq)*f4z %c*E	!Q&!+)*S!#& tcz4#:..C#:L#:L ,8D1HsQw345 
 ,8D1HsQw345 
 	xc3|C7H7MN
 	

G%
L Z>9 <FNN<L9(Cc7EQw#'8a[(1+sCgFE
 7#H):!9h#sH*&Hh a
#H1HC(H	#a 88H#Ga
qqIcC!G44IcC!G44a
qIcC!G44H$'!
#H#G&!!   $$" "&%A( JKFHhS*h""  "%( FGB(Cj(%!!!%( %c*E!$S)Z7#H!#&s+q0SMEEI Qw#'8J !!8DbD>8DbD>5%QT"UV!!8DbD>8DbD>5%QT"UV!Z(({ Z>9z Z((rj   c                 $   t        |       t        | d         }}|r||dz
  |dz
  ffg}|S g }d}t        |      D ]S  }t        |      D ]C  }| |   |   }	t        t        |	|z
              t        |      k  s/|j	                  |	||ff       E U |S )zReturn a list of starting points (score, (row, col)) (PRIVATE).

    Indicating every possible place to start the tracebacks.
    r   rG   )r*   r   r   absr   )
r   r   rM   nrowsncolsr   	tolerancer   r   r   s
             r>   r   r   P  s    
 |$c,q/&:5E 	519567 M 	 < 	7CU| 7$S)#.EJ./0DOCMM53*"567	7
 Mrj   c                    g }g }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ddd
dddddddddddd d!}t        t        | d"               D ]r  }g }g }t        t        |             D ]3  }|j                  | |   |          |j                  |||   |             5 |j                  |       |j                  |       t ||fS )#z+Reverse score and trace matrices (PRIVATE).rG   rK   rH   rJ         r"   r    r   	      
                                    r                        N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   Nr   )r   r*   r   )	r   r   reverse_score_matrixreverse_trace_matrixreverse_tracer   new_score_rownew_trace_rowr   s	            r>   r   r   h  s   	1qQ !1&',-q23R9:B@BBHJBPRTV
BBB "A')23521"RTBBBBBBBB	M Sa)* 3\*+ 	HC  c!23!78  |C/@/E!FG	H 	##M2##M23  !555rj   c                    g }| D ]  }||vs|j                  |        d}|t        |      k  r[||   \  }}}}}|t        |      }n|dk  r|t        |      z   }||k\  r||= Ct        |||||      ||<   |dz  }|t        |      k  r[|S )zTake a list of alignments and return a cleaned version (PRIVATE).

    Remove duplicates, make sure begin and end are set correctly, remove
    empty alignments.
    r   rG   )r   r*   r   )	r   unique_alignmentsr	   r`   seqAseqBr   r   r   s	            r>   r   r     s      ,))$$U+, 	
A
c#$
$(9!(<%dE5#;d)C1WD	/CC<!!$(tUE3G!	Q c#$
$ rj   c                     |r|| |dz
  dd   z  }|r|||dz
  dd   z  }||kD  r!||t        |      t        |      z
  z  z  }||fS ||kD  r||t        |      t        |      z
  z  z  }||fS )zBAdd remaining sequences and fill with gaps if necessary (PRIVATE).rG   Nr$   )r*   )r%   r&   r   r   r   r   rN   s          r>   r   r     s    
IcAgmm,,
IcAgmm,,
SyHHH =>> X 
sHHH =>>Xrj   c                    d}|	|   |   }t        |      D ]  }|dk(  r|dz  }||z  }||||dz    z  }n|dz  }|| ||dz    z  }||z  }|	|   |    |||dz         z   }|s|	|   |   |k(  rd} nWt        |      t        |      k(  r3|dkD  r.|
|   |   s n1|j                  |dd |dd |||||
|   |   f       |
|   |   rd} ||||||fS )z9Find the starting point(s) of the extended gap (PRIVATE).Fr   rG   Tr   N)r   r   r   )r%   r&   r   r   r   r   r   r   rN   r   r   r   gap_fntargetrT   	directionr   rM   r   target_scorere   actual_scores                         r>   r   r     sI   * H$S)L6] 1HC H	#a00H1HC	#a00H H#C(-ua!e0DD,s"3C"8J"FHl!33A$S)!!  $S)#.
 C %H=> XsCX==rj   c                 $    t        | |z  dz         S )z%Print number with declared precision.g      ?)int)r   	precisions     r>   r   r     s    q9}s"##rj   c                       e Zd ZdZddZd Zy)rW   zCreate a match function for use in an alignment.

    match and mismatch are the scores to give when two residues are equal
    or unequal.  By default, match is 1 and mismatch is 0.
    c                      || _         || _        yInitialize the class.Nr   r   )r5   r   r   s      r>   r?   zidentity_match.__init__  s    
 rj   c                 <    ||k(  r| j                   S | j                  S )z/Call a match function instance already created.r   r5   charAcharBs      r>   ri   zidentity_match.__call__  s    E>::}}rj   N)rG   r   r2   rk   rl   r4   r?   ri   rC   rj   r>   rW   rW     s    !
rj   rW   c                       e Zd ZdZddZd Zy)rX   a0  Create a match function for use in an alignment.

    Attributes:
     - score_dict     - A dictionary where the keys are tuples (residue 1,
       residue 2) and the values are the match scores between those residues.
     - symmetric      - A flag that indicates whether the scores are symmetric.

    c                 j    t        |t        j                        rt        |      }|| _        || _        yr   )rz   r   Arraydict
score_dict	symmetric)r5   r  r  s      r>   r?   zdictionary_match.__init__  s+    j"7"="=>j)J$"rj   c                 d    | j                   r||f| j                  vr||}}| j                  ||f   S )z1Call a dictionary match instance already created.)r  r  r   s      r>   ri   zdictionary_match.__call__  s6    >>uenDOOC !%5Eu~..rj   N)rG   r  rC   rj   r>   rX   rX     s    #/rj   rX   c                       e Zd ZdZddZd Zy)rZ   z.Create a gap function for use in an alignment.c                 ~    |dkD  s|dkD  rt        d      |s||k  rt        d      ||c| _        | _        || _        y)r   r   z%Gap penalties should be non-positive.zJGap opening penalty should be higher than gap extension penalty (or equal)N)r[   r   r   rI   )r5   r   r   rI   s       r>   r?   zaffine_penalty.__init__  sP    !8vzDEE+$3  "&v	4;,H)rj   c                 Z    t        || j                  | j                  | j                        S )z-Call a gap function instance already created.)r   r   r   rI   )r5   rT   lengths      r>   ri   zaffine_penalty.__call__$  s&    "DIIt{{D,M,M
 	
rj   N)r   r  rC   rj   r>   rZ   rZ     s    8
I
rj   rZ   c                 0    | dk  ry||| z  z   }|s||z  }|S )z/Calculate a penalty score for the gap function.r   r   rC   )r  r   r   rI   penaltys        r>   r   r   +  s,    {Vf_$G'6Nrj   c                      t        t         d               D cg c]  }g  }}t        t                     D ]J  t        t                        D ].  }||   j                  t        t            |                      0 L |D cg c]  }t	        |       c}t        t                     D ]<  t        dj                   fdt        t                        D                     > yc c}w c c}w )z*Print out a matrix for debugging purposes.r    c              3   >   K   | ]  }d |      |   fz    yw)z%*s NrC   )rD   jr`   matrixndigitss     r>   rF   zprint_matrix.<locals>.<genexpr>@  s'     XQVwqz6!9Q<88Xs   N)r   r*   r   r|   r   printr3   )r  r   matrixTr  r`   r  s   `   @@r>   print_matrixr  5  s     !VAY01ar1G13v; 6s6!9~& 	6AAJc#fQil"345	66  ''!s1v'G3v; 
HHX%FSTIBWXX	

 2 (s   	C6C;c                    |}|}dx}}	|}
|s|dk7  s|t        |       k7  rt        t        | d|       | d| j                  d      z
  dz         dz   }t        t        |d|       |d| j                  d      z
  dz         dz   }	t        t        |      t        |	            }
n|rd}
d}t        |       }t	        | t
              r$| D cg c]  }|dz   	 } }|D cg c]  }|dz   	 }}dj                  ||
      g}d|
z  g}dj                  |	|
      g}t        t        | || |||             D ].  \  }\  }}t        t        |      t        |            }|j                  d	j                  ||             |j                  d	j                  ||             |r-||k  s||k\  r#|j                  d	j                  d|             ||k(  r#|j                  d	j                  d
|             |j                         dk(  s|j                         dk(  r$|j                  d	j                  d|             |j                  d	j                  d|             1 |j                  d|dd       dj                  dj                  |      dj                  |      dj                  |      g      S c c}w c c}w )aR  Format the alignment prettily into a string.

    IMPORTANT: Gap symbol must be "-" (or ['-'] for lists)!

    Since Biopython 1.71 identical matches are shown with a pipe
    character, mismatches as a dot, and gaps as a space.

    Prior releases just used the pipe character to indicate the
    aligned region (matches, mismatches and gaps).

    Also, in local alignments, if the alignment does not include
    the whole sequences, now only the aligned part is shown,
    together with the start positions of the aligned subsequences.
    The start positions are 1-based; so start position n is the
    n-th base/amino acid in the *un-aligned* sequence.

    NOTE: This is different to the alignment's begin/end values,
    which give the Python indices (0-based) of the bases/amino acids
    in the *aligned* sequences.

    If you want to restore the 'historic' behaviour, that means
    displaying the whole sequences (including the non-aligned parts),
    use ``full_sequences=True``. In this case, the non-aligned leading
    and trailing parts are also indicated by spaces in the match-line.
    r   r   NrO   rG   r  z{:>{width}})widthz{:^{width}}|.z	
  Score=gr(   )r*   r|   countr   rz   r{   format	enumeratezipr   stripr3   )align1align2r   r   r   full_sequencesalign_begin	align_endstart1start2start_mas1_linem_lines2_linere   bm_lens                     r>   format_alignmentr0  D  s   4 KIFVGuzSCK-? S(6&5>+?+?+DDqHICOS(6&5>+?+?+DDqHICOc&k3v;/	&k&$ $**a!c'**#)*a!c'**##F'#:;GGm_F##F'#:;Gs6%#4fU36GHI B	6Aq CFCF#}++AU+;<}++AU+;<q;!y.MM-..s%.@A6MM-..s%.@AWWY#c!1MM-..s%.@AMM-..s%.@AB  NNZay+,99bggg&9IJKK1 +*s   J:J?rG   )r   r   z\Import of C module failed. Falling back to pure Python implementation. This may be slooow...__main__)run_doctest)F)%r4   r}   collectionsr   Bior   r   	Bio.Alignr   r~   r   r   r	   rh   r   r   r   r   r   r   r   r   
_PRECISIONr   rW   rX   rZ   r   r  r0  _python_make_score_matrix_fast_python_rint
cpairwise2ImportErrorr2   
Bio._utilsr2  rC   rj   r>   <module>r<     s/  CJ  " +   + G   {%DF	^, ^,B 	upp2fR2B E)P06.6
6>r 
 ! $
 &/ /4
 
,
EL\ "9 9 z&M   HMM	0s   B; ;CC