o
    Rŀg~                     @   sj   d 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	 G dd dZ
G dd	 d	Zdd
dZdS )zExtract 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.
    N)Counter)BiopythonDeprecationWarning)Seqc                   @   s   e Zd ZdZdd ZdddZdd	d
ZdddZdd Zdd Z	dddZ
						d ddZ			d!ddZdd Zdd ZdS )"SummaryInfozCalculate summary info about the alignment.

    This class should be used to calculate information summarizing the
    results of an alignment. This may either be straight consensus info
    or more complicated things.
    c                 C   s   || _ g | _dS )zInitialize with the alignment to calculate information on.

        ic_vector attribute. A list of ic content for each column number.
        N)	alignment	ic_vector)selfr    r	   G/var/www/html/myenv/lib/python3.10/site-packages/Bio/Align/AlignInfo.py__init__   s   
zSummaryInfo.__init__ffffff?XFc              
   C   s  t dt d}| j }t|D ]u}t }d}| jD ]&}	z|	| }
W n	 ty,   Y qw |
dkrA|
dkrA||
  d7  < |d7 }qg }d}|D ]}|| |krX|g}|| }qH|| |krc|| qH|ro|dkro||7 }qt	|dkr|| |kr||d 7 }q||7 }qt
|S )a&  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:
         - threshold - The threshold value that is required to add a particular
           atom.
         - ambiguous - The ambiguous character to be added when the threshold is
           not reached.
         - require_multiple - If set as True, 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).

        a;  The `dumb_consensus` method is deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and then create a Motif object. You can then use the `.consensus` or `.degenerate_consensus` property of the Motif object to get a consensus sequence. For more control over how the consensus sequence is calculated, you can call the `calculate_consensus` method on the `.counts` property of the Motif object. This is an example for a multiple sequence alignment `msa` of DNA nucleotides:
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> from Bio.Align import MultipleSeqAlignment
>>> from Bio.Align.AlignInfo import SummaryInfo
>>> msa = MultipleSeqAlignment([SeqRecord(Seq('ACGT')),
...                             SeqRecord(Seq('ATGT')),
...                             SeqRecord(Seq('ATGT'))])
>>> summary = SummaryInfo(msa)
>>> dumb_consensus = summary.dumb_consensus(ambiguous='N')
>>> print(dumb_consensus)
ANGT
>>> alignment = msa.alignment
>>> from Bio.motifs import Motif
>>> motif = Motif('ACGT', alignment)
>>> print(motif.consensus)
ATGT
>>> print(motif.degenerate_consensus)
AYGT
>>> counts = motif.counts
>>> consensus = counts.calculate_consensus(identity=0.7)
>>> print(consensus)
ANGT

If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse. r   -.   warningswarnr   r   get_alignment_lengthranger   
IndexErrorappendlenr   r   	threshold	ambiguousrequire_multiple	consensuscon_lenn	atom_dict	num_atomsrecordc	max_atomsmax_sizeatomr	   r	   r
   dumb_consensus'   sD   '+





zSummaryInfo.dumb_consensusc              
   C   s  t dt d}| j }t|D ]m}t }d}| jD ]}	z|	| }
W n	 ty,   Y qw ||
  d7  < |d7 }qg }d}|D ]}|| |krP|g}|| }q@|| |kr[|| q@|rg|dkrg||7 }qt	|dkrz|| |krz||d 7 }q||7 }qt
|S )ah  Output a fast consensus sequence of the alignment, allowing gaps.

        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 as input.

        a  The `gap_consensus` method is deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and then create a Motif object. You can then use the `.consensus` or `.degenerate_consensus` property of the Motif object to get a consensus sequence. For more control over how the consensus sequence is calculated, you can call the `calculate_consensus` method on the `.counts` property of the Motif object. This is an example for a multiple sequence alignment `msa` of DNA nucleotides:
>>> from Bio.Seq import Seq
>>> from Bio.SeqRecord import SeqRecord
>>> from Bio.Align import MultipleSeqAlignment
>>> from Bio.Align.AlignInfo import SummaryInfo
>>> msa = MultipleSeqAlignment([SeqRecord(Seq('ACGT')),
...                             SeqRecord(Seq('AT-T')),
...                             SeqRecord(Seq('CT-T')),
...                             SeqRecord(Seq('GT-T'))])
>>> summary = SummaryInfo(msa)
>>> gap_consensus = summary.gap_consensus(ambiguous='N')
>>> print(gap_consensus)
NT-T
>>> alignment = msa.alignment
>>> from Bio.motifs import Motif
>>> motif = Motif('ACGT-', alignment)  # include '-' in alphabet
>>> print(motif.consensus)
AT-T
>>> print(motif.degenerate_consensus)
VT-T
>>> counts = motif.counts
>>> consensus = counts.calculate_consensus(identity=0.7)
>>> print(consensus)
NT-T

If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse.r   r   r   r   r   r	   r	   r
   gap_consensus   s@   (+






zSummaryInfo.gap_consensusNc                    s   t dt |durtd fdd D }tt| jD ]1}t|d t| jD ]$}| | j| j| j| j| j| j	
dd| j| j	
dd|  q*q|S )	a  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 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

        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:
         - skip_chars - Not used; setting it to anything other than None
           will raise a ValueError
         - letters - An iterable (e.g. a string or list of characters to include.
        a  The `replacement_dictionary` method is deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and then use the `.substitutions` property  of the `Alignment` object. For example, for a multiple sequence alignment `msa` of DNA nucleotides, you would do: 
>>> alignment = msa.alignment
>>> dictionary = alignment.substitutions

If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse.Nztargument skip_chars has been deprecated; instead, please use 'letters' to specify the characters you want to includec                    s    i | ]} D ]}||fd qqS )r   r	   ).0letter1letter2lettersr	   r
   
<dictcomp>,  s     z6SummaryInfo.replacement_dictionary.<locals>.<dictcomp>r   weight      ?)r   r   r   
ValueErrorr   r   r   _pair_replacementseqannotationsget)r   
skip_charsr.   rep_dictrec_num1rec_num2r	   r-   r
   replacement_dictionary   s*   "

z"SummaryInfo.replacement_dictionaryc           	      C   s@   t ||D ]\}}||v r||v r|||f  || 7  < qdS )a  Compare two sequences and generate info on the replacements seen (PRIVATE).

        Arguments:
         - seq1, seq2 - The two sequences to compare.
         - weight1, weight2 - The relative weights of seq1 and seq2.
         - dictionary - The dictionary containing the starting replacement
           info that we will modify.
         - letters - A list of characters to include when calculating replacements.

        N)zip)	r   seq1seq2weight1weight2
dictionaryr.   residue1residue2r	   r	   r
   r3   @  s
   zSummaryInfo._pair_replacementc                 C   s4   t  }| jD ]}||j qt|}d|}|S )zKReturn a string containing the expected letters in the alignment (PRIVATE).r   )setr   updater4   sortedjoin)r   set_lettersr#   list_lettersall_lettersr	   r	   r
   _get_all_lettersP  s   

zSummaryInfo._get_all_lettersc              
   C   sH  t dt |  }|std|du rg }t|tstdd}|| |D ]}|	|d}q(|rC|}t
|| j krBtdn|  }g }tt
|D ]P}t|d}	| jD ];}
z|
j| }W n tyn   d}Y nw |r||vr|
jd	d
}z
|	|  |7  < W qZ ty   td| dw qZ||| |	f qOt|S )a  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:
         - chars_to_ignore - A list of all characters not to include in
           the pssm.
         - 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:
         - A PSSM (position specific score matrix) object.

        a  The `pos_specific_score_matrix` method is deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and then create a Motif object. For example, for a multiple sequence alignment `msa` of DNA nucleotides, you would do: 
>>> alignment = msa.alignment
>>> from Bio.motifs import Motif
>>> motif = Motif('ACGT', alignment)
>>> counts = motif.counts

The `counts` object contains the same information as the PSSM returned by `pos_specific_score_matrix`, but note that the indices are reversed:

>>> counts[letter][i] == pssm[index][letter]
True

If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse.z&_get_all_letters returned empty stringNz!chars_to_ignore should be a list.r   r   z<Axis sequence length does not equal the get_alignment_lengthr   r0   r1   zResidue %s not found)r   r   r   rK   r2   
isinstancelist	TypeErrorr   replacer   r   r   r(   r   dictfromkeysr4   r   r5   r6   KeyErrorPSSM)r   axis_seqchars_to_ignorerJ   gap_charcharleft_seq	pssm_inforesidue_num
score_dictr#   this_residuer0   r	   r	   r
   pos_specific_score_matrixY  s\   


z%SummaryInfo.pos_specific_score_matrixr      c              
   C   s  t dt |du rt| jd j}|du rg }|dk s&|t| jd jkr6td||dt| jd jf d}|  }|D ]}	||	d}q>i }
t	||D ]}| 
|| j|||||}| ||||}||
|< qNt|
 }g | _t|
D ]\}}| j|
||   qv|S )a   Calculate the information content for each residue along an alignment.

        Arguments:
         - 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.
         - e_freq_table - A dictionary specifying the expected frequencies
           for each letter (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.
         - log_base - The base of the logarithm to use in calculating the
           information content. This defaults to 2 so the info is in bits.
         - chars_to_ignore - A listing of characters which should be ignored
           in calculating the info content. Defaults to none.

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

        Please see the Biopython manual for more information on how information
        content is calculated.

        a  The `information_content` method and `ic_vector` attribute of the `SummaryInfo` class are deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and use the `information_content` attribute of the Alignment obecjt. For example, for a multiple sequence alignment `msa` of DNA nucleotides, you would do: 
>>> alignment = msa.alignment
>>> from Bio.motifs import Motif
>>> motif = Motif('ACGT', alignment)
>>> information_content = motif.information_content

The `information_content` object contains the same values as the `ic_vector` attribute of the `SummaryInfo` object. Its sum is equal to the value return by the `information_content` method. 
If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse.Nr   z5Start (%s) and end (%s) are not in the range %s to %sr   )r   r   r   r   r   r4   r2   rK   rO   r   _get_letter_freqs_get_column_info_contentsumvaluesr   	enumerater   )r   startende_freq_tablelog_baserU   pseudo_countrandom_expectedrJ   rW   info_contentrZ   	freq_dictcolumn_score
total_infoikr	   r	   r
   information_content  sL   "

zSummaryInfo.information_contentc              	   C   sL  t |d}d}	d}
|dk rtd| |D ]4}z|j| |vr6|jdd}||j|   |7  < |	|7 }	W q tyJ   td|j| |f dw |r`|D ]}||
kr_||vr_td| qO|	dkru|D ]}|| dkrrtd	qf|S |D ],}|r|s|r|r|| }n|}|| ||  }|	| }|| ||< qw|| |	 ||< qw|S )
a^  Determine the frequency of specific letters in the alignment (PRIVATE).

        Arguments:
         - residue_num - The number of the column we are getting frequencies
           from.
         - all_records - All of the SeqRecords in the alignment.
         - letters - The letters we are interested in getting the frequency
           for.
         - to_ignore - Letters we are specifically supposed to ignore.
         - pseudo_count - Optional argument specifying the Pseudo count (k)
           to add in order to prevent a frequency of 0 for a letter.
         - e_freq_table - An optional argument specifying a dictionary with
           the expected frequencies for each letter.
         - random_expected - Optional argument that specify the frequency to use
           when e_freq_table is not defined.

        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. Pseudo count can be added to prevent a null frequency
        r   r   z5Positive value required for pseudo_count, %s providedr0   r1   z"Residue %s not found in letters %sNz(%s not found in expected frequency tablezfreq_info[letter] is not 0)rP   rQ   r2   r4   r5   r6   rR   )r   rZ   all_recordsr.   	to_ignorerh   rf   ri   	freq_infototal_countrV   r#   r0   keyletter
ajust_freqajusted_letter_countajusted_totalr	   r	   r
   r_     sX   
zSummaryInfo._get_letter_freqsc                 C   s   d}|r|D ]}||kr||vrt d| qd}|D ]/}d}	||kr5|r/|| ||  }	n|| | }	|	dkrK|| t|	 t| }
||
7 }q|S )a  Calculate the information content for a column (PRIVATE).

        Arguments:
         - obs_freq - The frequencies observed for each letter in the column.
         - e_freq_table - An optional argument specifying a dictionary with
           the expected frequencies for each letter.
         - log_base - The base of the logarithm to use in calculating the
           info content.

        r   z:Frequency table provided does not contain observed letter g        r   )r2   mathlog)r   obs_freqrf   rg   ri   rV   ru   rm   rv   	inner_logletter_infor	   r	   r
   r`   t  s*   z$SummaryInfo._get_column_info_contentc                 C   s   | j dd|f S )zReturn column of alignment.N)r   )r   colr	   r	   r
   
get_column  s   zSummaryInfo.get_column)r   r   F)NN)r   NNr^   Nr   )r   NN)__name__
__module____qualname____doc__r   r(   r)   r;   r3   rK   r]   rp   r_   r`   r   r	   r	   r	   r
   r      s,    

l
`M
	a
l
V,r   c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )rS   a  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   t dt || _dS )aW  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.
        a  The `PSSM` class is deprecated and will be removed in a future release of Biopython. As an alternative, you can convert the multiple sequence alignment object to a new-style Alignment object by via its `.alignment` property, and then create a Motif object. For example, for a multiple sequence alignment `msa` of DNA nucleotides, you would do: 
>>> alignment = msa.alignment
>>> from Bio.motifs import Motif
>>> motif = Motif('ACGT', alignment)
>>> counts = motif.counts

The `counts` object contains the same information as the PSSM returned by `pos_specific_score_matrix`, but note that the indices are reversed:

>>> counts[letter][i] == pssm[index][letter]
True

If your multiple sequence alignment object was obtained using Bio.AlignIO, then you can obtain a new-style Alignment object directly by using Bio.Align.read instead of Bio.AlignIO.read, or Bio.Align.parse instead of Bio.AlignIO.parse.N)r   r   r   pssm)r   r   r	   r	   r
   r     s
   	
zPSSM.__init__c                 C      | j | d S )Nr   r   r   posr	   r	   r
   __getitem__  s   zPSSM.__getitem__c                 C   sz   d}t | jd d }|D ]}|d| 7 }q|d7 }| jD ]}|d|d  7 }|D ]}|d|d |  7 }q)|d7 }q|S )N r   r   z   %s
z%s z %.1f)rF   r   )r   outall_residuesresitemr	   r	   r
   __str__  s   

zPSSM.__str__c                 C   r   )z4Return the residue letter at the specified position.r   r   r   r	   r	   r
   get_residue  s   zPSSM.get_residueN)r   r   r   r   r   r   r   r   r	   r	   r	   r
   rS     s    %rS   c                 C   sd   t dt |p
tj}| js|   | j| }tt	|| jD ]\}\}}|
d|||f  qdS )zJ3 column output: position, aa in representative sequence, ic_vector value.zeThe `print_info_content` function is deprecated and will be removed in a future release of Biopython.z%d %s %.3f
N)r   r   r   sysstdoutr   rp   r   rc   r<   write)summary_infofout
rep_recordrep_sequencer   aaicr	   r	   r
   print_info_content  s   

r   )Nr   )r   rz   r   r   collectionsr   Bior   Bio.Seqr   r   rS   r   r	   r	   r	   r
   <module>   s        ^