
Lc           @   s  d  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	 m
 Z
 d Z d Z d	 f  d
     YZ d f  d     YZ e d d  Z e d k rd GHd d l m Z d d l m Z d Z d Z e
 j
 i d d 6d d 6d d 6d d 6e
 j e j  Z e j e e  e  Z x e D] Z e j j   GHq2Wd e j    GHe e  Z! e! j" d d  Z# e# GHe! j$ d d  Z# e# GHHe! j% d d g d e#  GHHe! j& d e d d g  GHHd  GHe j' e j( e j) d  d!  Z* e e*  Z+ e+ j, d" d#  e+ j, d$ d%  e+ j, d& d'  e+ GHd e+ j    GHe e+  Z- e- j" d d(  Z. e. GHe- j$ d d(  Z. e. GHHe- j% d d d! g d e.  GHe- j& d d d! g  GHd) GHn  d S(*   s  Extract information from alignment objects.

In order to try and avoid huge alignment objects with tons of functions,
functions which return summary type information about alignments should
be put into classes in this module.

classes:
o SummaryInfo
o PSSM
iN(   t   Alphabet(   t   IUPAC(   t   Seq(   t	   FreqTableg?g      ?t   SummaryInfoc           B   s   e  Z d  Z d   Z d d d d d  Z d d d d d  Z d   Z g  d  Z d	   Z	 d
   Z
 g  d  Z d g  d  Z d   Z d d d d g  d  Z d   Z d   Z d   Z RS(   s   Calculate summary info about the alignment.

    This class should be used to caclculate information summarizing the
    results of an alignment. This may either be straight consensus info
    or more complicated things.
    c         C   s   | |  _  i  |  _ d S(   s   Initialize with the alignment to calculate information on.
           ic_vector attribute. A dictionary. Keys: column numbers. Values:
        N(   t	   alignmentt	   ic_vector(   t   selfR   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   __init__!   s    	gffffff?t   Xi    c         C   s  d } |  j  j   } xt |  D]}} i  } d }	 x |  j  j D] }
 | t |
 j  k  rA |
 j | d k r |
 j | d k r |
 j | | k r d | |
 j | <n | |
 j | c d 7<|	 d }	 q qA qA Wg  } d } xT | D]L } | | | k r| g } | | } q | | | k r | j |  q q W| rV|	 d k rV| | 7} q" t |  d k rt |  t |	  | k r| | d 7} q" | | 7} q" W| d k r|  j	 |  } n  t
 | |  S(   s  Output a fast consensus sequence of the alignment.

        This doesn't do anything fancy at all. It will just go through the
        sequence residue by residue and count up the number of each type
        of residue (ie. A or G or T or C for DNA) in all sequences in the
        alignment. If the percentage of the most common residue type is
        greater then the passed threshold, then we will add that residue type,
        otherwise an ambiguous character will be added.

        This could be made a lot fancier (ie. to take a substitution matrix
        into account), but it just meant for a quick and dirty consensus.

        Arguments:
        o threshold - The threshold value that is required to add a particular
        atom.
        o ambiguous - The ambiguous character to be added when the threshold is
        not reached.
        o consensus_alpha - The alphabet to return for the consensus sequence.
        If this is None, then we will try to guess the alphabet.
        o require_multiple - If set as 1, this will require that more than
        1 sequence be part of an alignment to put it in the consensus (ie.
        not just 1 sequence and gaps).
        t    i    t   -t   .i   N(   R   t   get_alignment_lengtht   ranget   _recordst   lent   seqt   appendt   floatt   Nonet   _guess_consensus_alphabetR   (   R   t	   thresholdt	   ambiguoust   consensus_alphat   require_multiplet	   consensust   con_lent   nt	   atom_dictt	   num_atomst   recordt	   max_atomst   max_sizet   atom(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   dumb_consensus(   s:    &	%	c         C   s  d } |  j  j   } xbt |  D]T} i  } d }	 xt |  j  j D]f }
 | t |
 j  k  rA |
 j | | k r d | |
 j | <n | |
 j | c d 7<|	 d 7}	 qA qA Wg  } d } xT | D]L } | | | k r | g } | | } q | | | k r | j |  q q W| r-|	 d k r-| | 7} q" t |  d k rlt |  t |	  | k rl| | d 7} q" | | 7} q" W| d k r|  j	 |  } n  t
 | |  S(   s   Same as dumb_consensus(), but allows gap on the output.

        Things to do: Let the user define that with only one gap, the result
        character in consensus is gap. Let the user select gap character, now
        it takes the same is input.
        R
   i    i   N(   R   R   R   R   R   R   R   R   R   R   R   (   R   R   R   R   R   R   R   R   R   R   R   R    R!   R"   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   gap_consensusq   s8    		%	c         C   sb  t  j |  j j  } xG |  j D]< } t  j | j j  } t | | j  s t d   q q Wt	 | d  r^| j
 d k	 r^| | j
 k r^t | t j  r | t j   j
 k r t j   } q[t  j } q^t | t j  r| t j   j
 k rt j   } q[t  j } q^t | t j  rR| t j   j
 k rFt j   } q[t  j } q^t  j } n  | S(   s   Pick an (ungapped) alphabet for an alignment consesus sequence.

        This just looks at the sequences we have, checks their type, and
        returns as appropriate type which seems to make sense with the
        sequences we've got.
        s<   Alignment contains a sequence with an incompatible alphabet.t   lettersN(   R    t   _get_base_alphabetR   t	   _alphabetR   t   alphabett
   isinstancet	   __class__t
   ValueErrort   hasattrR%   R   R   t   IUPACUnambiguousDNAt   generic_dnat   IUPACUnambiguousRNAt   generic_rnat   IUPACProteint   ExtendedIUPACProteint   generic_proteint   single_letter_alphabet(   R   R   t   aR   t   alt(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR      s,    c      	   C   s   |  j  |  \ } } x t t |  j j   D] } x t | d t |  j j   D]p } |  j |  j j | j |  j j | j |  j j | j j d d  |  j j | j j d d  | |  } qT Wq. W| S(   s  Generate a replacement dictionary to plug into a substitution matrix
        
        This should look at an alignment, and be able to generate the number
        of substitutions of different residues for each other in the
        aligned object.

        Will then return a dictionary with this information:
        {('A', 'C') : 10, ('C', 'A') : 12, ('G', 'C') : 15 ....}

        This also treats weighted sequences. The following example shows how
        we calculate the replacement dictionary. Given the following
        multiple sequence alignments:

        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

        We then continue this for all of the columns in the alignment, summing
        the information for each substitution in each column, until we end
        up with the replacement dictionary.

        Arguments:
        o skip_chars - A list of characters to skip when creating the dictionary.
        For instance, you might have Xs (screened stuff) or Ns, and not want
        to include the ambiguity characters in the dictionary.
        i   t   weightg      ?(	   t   _get_base_replacementsR   R   R   R   t   _pair_replacementR   t   annotationst   get(   R   t
   skip_charst   rep_dictt
   skip_itemst   rec_num1t   rec_num2(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   replacement_dictionary   s    !&c   
      C   s   x t  t |   D] } | | } y | | }	 Wn t k
 rE | SX| | k r |	 | k r y | | |	 f c | | 7<Wq t k
 r t d | |	 |  j j f   q Xq q W| S(   s?  Compare two sequences and generate info on the replacements seen.

        Arguments:
        o seq1, seq2 - The two sequences to compare.
        o weight1, weight2 - The relative weights of seq1 and seq2.
        o start_dict - The dictionary containing the starting replacement
        info that we will modify.
        o ignore_chars - A list of characters to ignore when calculating
        replacements (ie. '-').

        Returns:
        o A replacment dictionary which is modified from initial_dict with
        the information from the sequence comparison.
        s(   Residues %s, %s not found in alphabet %s(   R   R   t
   IndexErrort   KeyErrorR+   R   R'   (
   R   t   seq1t   seq2t   weight1t   weight2t
   start_dictt   ignore_charst   residue_numt   residue1t   residue2(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR9     s    
c         C   s   |  j  j j } | d k sH t |  j  j t j  r | |  j  j j k r t   } x# |  j  D] } | j	 | j
  } q[ Wt |  } | j   d j |  } n  | S(   sB   Returns a string containing the expected letters in the alignment.R
   N(   R   R'   R%   R   R)   R    t   Gappedt   gap_chart   sett   unionR   t   listt   sortt   join(   R   t   all_letterst   set_lettersR   t   list_letters(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   _get_all_letters0  s    	
c         C   s   i  } |  j    } t |  j j t j  r^ | j |  j j j  | j |  j j j d  } n  xJ | D]B } x9 | D]1 } | | k rr | | k rr d | | | f <qr qr Wqe W| | f S(   s}  Get a zeroed dictonary of all possible letter combinations.

        This looks at the type of alphabet and gets the letters for it.
        It then creates a dictionary with all possible combinations of these
        letters as keys (ie. ('A', 'G')) and sets the values as zero.

        Returns:
        o The base dictionary created
        o A list of alphabet items to skip when filling the dictionary.Right
        now the only thing I can imagine in this list is gap characters, but
        maybe X's or something else might be useful later. This will also
        include any characters that are specified to be skipped.
        R
   i    (	   RW   R)   R   R'   R    RM   R   RN   t   replace(   R   R>   t   base_dictionaryRT   t   first_lettert   second_letter(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR8   C  s    c         C   s  |  j    } | s t  t | t  s6 t d   n  t |  j j t j  rg | j	 |  j j j
  n  x  | D] } | j | d  } qn W| r | } t |  |  j j   k s t  n |  j   } g  } x t t |   D] } |  j |  } x |  j j D] }	 y |	 j | }
 Wn t k
 r1d }
 n X|
 r|
 | k r|	 j j d d  } y | |
 c | 7<Wqt k
 rt d |
 |  j j f   qXqqW| j	 | | | f  q Wt |  S(   s  Create a position specific score matrix object for the alignment.

        This creates a position specific score matrix (pssm) which is an
        alternative method to look at a consensus sequence.

        Arguments:
        o chars_to_ignore - A listing of all characters not to include in
        the pssm.  If the alignment alphabet declares a gap character,
        then it will be excluded automatically.
        o axis_seq - An optional argument specifying the sequence to
        put on the axis of the PSSM. This should be a Seq object. If nothing
        is specified, the consensus sequence, calculated with default
        parameters, will be used.

        Returns:
        o A PSSM (position specific score matrix) object.
        s!   chars_to_ignore should be a list.R
   R7   g      ?s#   Residue %s not found in alphabet %sN(   RW   t   AssertionErrorR)   RQ   t	   TypeErrorR   R'   R    RM   R   RN   RX   R   R   R#   R   t   _get_base_lettersR   R   RB   R   R:   R;   RC   R+   t   PSSM(   R   t   axis_seqt   chars_to_ignoreRT   t   chart   left_seqt	   pssm_infoRJ   t
   score_dictR   t   this_residueR7   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   pos_specific_score_matrixd  s>    $
c         C   s%   i  } x | D] } d | | <q W| S(   sF   Create a zeroed dictionary with all of the specified letters.
        i    (    (   R   R%   t	   base_infot   letter(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR^     s    i   c      	   C   s  | d k r( t |  j j d j  } n  | d k  sS | t |  j j d j  k r t d | | d t |  j j d j  f   n  d } | s t j |  j j  } t	 | t j
  r t } n7 t	 | t j  r t } n d } | d 7} t |   ~ n! t	 | t j  st d   n  |  j   }	 x  | D] }
 |	 j |
 d  }	 q2Wi  } xW t | |  D]F } |  j | |  j j |	 |  } |  j | | | |  } | | | <qdWt | j    } x | D] } | | |  j | <qW| S(   s  Calculate the information content for each residue along an alignment.

        Arguments:
        o start, end - The starting an ending points to calculate the
        information content. These points should be relative to the first
        sequence in the alignment, starting at zero (ie. even if the 'real'
        first position in the seq is 203 in the initial sequence, for
        the info content, we need to use zero). This defaults to the entire
        length of the first sequence.
        o e_freq_table - A FreqTable object specifying the expected frequencies
        for each letter in the alphabet we are using (e.g. {'G' : 0.4,
        'C' : 0.4, 'T' : 0.1, 'A' : 0.1}). Gap characters should not be
        included, since these should not have expected frequencies.
        o log_base - The base of the logathrim to use in calculating the
        information content. This defaults to 2 so the info is in bits.
        o chars_to_ignore - A listing of characterw which should be ignored
        in calculating the info content.

        Returns:
        o A number representing the info content for the specified region.

        Please see the Biopython manual for more information on how information
        content is calculated.
        i    s5   Start (%s) and end (%s) are not in the range %s to %ss.   Error in alphabet: not Nucleotide or Protein, s   supply expected frequenciess)   e_freq_table should be a FreqTable objectR
   N(   R   R   R   R   R   R+   R    R&   R'   R)   t   ProteinAlphabett   Protein20Randomt   NucleotideAlphabett   Nucleotide4RandomR   RW   RX   R   t   _get_letter_freqst   _get_column_info_contentt   sumt
   itervaluesR   (   R   t   startt   endt   e_freq_tablet   log_baseRa   t   random_expectedt
   base_alphat   errstrRT   Rb   t   info_contentRJ   t	   freq_dictt   column_scoret
   total_infot   i(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   information_content  sH    +,		
				c   
      C   s
  |  j  |  } d } x | D] } yP | j | | k rq | j j d d  } | | j | c | 7<| | 7} n  Wq t k
 r t d | j | |  j j f   q Xq W| d k r xJ | D] }	 | |	 d k s t  q Wn# x  | D] }	 | |	 | | |	 <q W| S(   s  Determine the frequency of specific letters in the alignment.

        Arguments:
        o residue_num - The number of the column we are getting frequencies
        from.
        o all_records - All of the SeqRecords in the alignment.
        o letters - The letters we are interested in getting the frequency
        for.
        o to_ignore - Letters we are specifically supposed to ignore.

        This will calculate the frequencies of each of the specified letters
        in the alignment at the given frequency, and return this as a
        dictionary where the keys are the letters and the values are the
        frequencies.
        i    R7   g      ?s#   Residue %s not found in alphabet %s(	   R^   R   R:   R;   RC   R+   R   R'   R\   (
   R   RJ   t   all_recordsR%   t	   to_ignoret	   freq_infot   total_countR   R7   Ri   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyRn     s$    
c         C   sB  y |  j  j j } Wn t k
 r, d } n X| r t | t j  sT t d   n  xU | D]J } | | k r[ | | k r[ t d | j   | j   | g f   q[ q[ Wn  d } x | D] } d }	 | | k r | r | | | | }	 q | | | }	 n  |	 d k r | | t j	 |	  t j	 |  }
 | |
 7} q q W| S(   s  Calculate the information content for a column.

        Arguments:
        o obs_freq - The frequencies observed for each letter in the column.
        o e_freq_table - An optional argument specifying the expected
        frequencies for each letter. This is a SubsMat.FreqTable instance.
        o log_base - The base of the logathrim to use in calculating the
        info content.
        R   s)   e_freq_table should be a FreqTable objects6   Expected frequency letters %s do not match observed %sg        i    (
   R   R'   RN   t   AttributeErrorR)   R   R+   t   keyst   matht   log(   R   t   obs_freqRt   Ru   Rv   RN   t   keyR|   Ri   t	   inner_logt   letter_info(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyRo   *  s.    
	$$c         C   s   |  j  j |  S(   N(   R   t
   get_column(   R   t   col(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR   [  s    N(   t   __name__t
   __module__t   __doc__R   R   R#   R$   R   RA   R9   RW   R8   Rg   R^   R~   Rn   Ro   R   (    (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR      s*   	H7	*3	*	!B		K	,	1R_   c           B   s2   e  Z d  Z d   Z d   Z d   Z d   Z RS(   s  Represent a position specific score matrix.

    This class is meant to make it easy to access the info within a PSSM
    and also make it easy to print out the information in a nice table.

    Let's say you had an alignment like this:
    GTATC
    AT--C
    CTGTC

    The position specific score matrix (when printed) looks like:

      G A T C
    G 1 1 0 1
    T 0 0 3 0
    A 1 1 0 0
    T 0 0 2 0
    C 0 0 0 3

    You can access a single element of the PSSM using the following:

    your_pssm[sequence_number][residue_count_name]

    For instance, to get the 'T' residue for the second element in the
    above alignment you would need to do:

    your_pssm[1]['T']
    c         C   s   | |  _  d S(   sW  Initialize with pssm data to represent.

        The pssm passed should be a list with the following structure:

        list[0] - The letter of the residue being represented (for instance,
        from the example above, the first few list[0]s would be GTAT...
        list[1] - A dictionary with the letter substitutions and counts.
        N(   t   pssm(   R   R   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR   {  s    	c         C   s   |  j  | d S(   Ni   (   R   (   R   t   pos(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   __getitem__  s    c         C   s   d } |  j  d d j   } | j   x | D] } | d | 7} q. W| d 7} xT |  j  D]I } | d | d 7} x$ | D] } | d | d | 7} qy W| d 7} qZ W| S(   Nt    i    i   s      %ss   
s   %s s    %.1f(   R   R   RR   (   R   t   outt   all_residuest   rest   item(    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   __str__  s    

c         C   s   |  j  | d S(   s=   Return the residue letter at the specified position.
        i    (   R   (   R   R   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   get_residue  s    (   R   R   R   R   R   R   R   (    (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyR_   ^  s
   			i    c         C   s   | p t  j } |  j s% |  j   n  |  j j | j } |  j j   } | j   x3 | D]+ } | j	 d | | | |  j | f  qX Wd S(   sV    Three column output: position, aa in representative sequence,
        ic_vector values   %d %s %.3f
N(
   t   syst   stdoutR   R~   R   R   R   R   RR   t   write(   t   summary_infot   foutt
   rep_recordt   rep_sequencet	   positionsR   (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   print_info_content  s    	
t   __main__s
   Quick test(   t   AlignIO(   t	   Alignments   ../../Tests/GFF/multi.fnat   fastat   At   Gt   Tt   Ct   =R   t   NRa   R   R`   Rt   s-   Trying a protein sequence with gaps and stopst   *t   ID001s    MHQAIFIYQIGYP*LKSGYIQSIRSPEYDNW-t   ID002s    MH--IFIYQIGYAYLKSGYIQSIRSPEY-NW*t   ID003s    MHQAIFIYQIGYPYLKSGYIQSIRSPEYDNW*R	   t   Done(/   R   R   R   t   BioR    t   Bio.AlphabetR   t   Bio.SeqR   t   Bio.SubsMatR   Rk   Rm   R   R_   R   R   R   R   t   Bio.Align.GenericR   t   filenamet   formatt   FREQt   unambiguous_dnat   expectedt   readt   openR   R   R   t   tostringR   t   summaryR#   R   R$   Rg   R~   t   HasStopCodonRM   R3   t   alphaR5   t   add_sequencet   st   c(    (    (    s4   C:\Python27\Lib\site-packages\Bio\Align\AlignInfo.pyt   <module>
   sn     FD%!